Skip to main content

flow_abi/
unix_millis.rs

1//! [`UnixMillis`], a time on a host's wall clock, and the one rule every
2//! conversion into it keeps.
3
4use std::fmt;
5use std::str::FromStr;
6use std::time::Duration;
7
8use flow_value::{BigInt, Decimal, Instant, Int};
9
10use crate::binary::{ValueReader, ValueWriter};
11use crate::bytes::Reader;
12use crate::error::{DecodeError, DecodeErrorKind, EncodeError, Place};
13use crate::wire::{AnyWire, Opened, Shaped, Type, Wire, WireForm};
14
15/// A time on a host's wall clock, in whole milliseconds since the Unix
16/// epoch: when a run started or ended, when a held call is asked again,
17/// when a daemon started. A host reads it for its own records, and a run
18/// never sees it as a value.
19///
20/// Its range is the epoch through `u64::MAX` milliseconds after it, and
21/// every conversion into it keeps the one rule [`UnixMillis::since_epoch`]
22/// states. Only reading text refuses a time outside the range
23/// ([`Outside`]), since a person gave it. A clock is read where a host
24/// reads one: this type only does the arithmetic on what it read.
25///
26/// Its text is the `Instant` it names, as an `Instant` is written. Its
27/// integer form, which a lock file, the daemon's pipe and a log line carry,
28/// is [`UnixMillis::as_millis`], and it is what its `Debug` form shows.
29#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
30pub struct UnixMillis(u64);
31
32/// Which end of [`UnixMillis`]'s range a time falls beyond.
33#[derive(Clone, Copy, PartialEq, Eq, Debug)]
34pub enum Outside {
35    /// It is before the Unix epoch.
36    BeforeEpoch,
37    /// It is past `u64::MAX` milliseconds after the epoch.
38    PastLast,
39}
40
41/// Why text is no [`UnixMillis`].
42#[derive(Clone, Copy, PartialEq, Eq, Debug)]
43pub enum TimeTextError {
44    /// It is not an `Instant`'s text as decoding reads it (`abi.md`, *Decoding*).
45    NotInstantText,
46    /// It names a time outside the range.
47    Outside(Outside),
48}
49
50impl UnixMillis {
51    /// The Unix epoch.
52    pub const EPOCH: UnixMillis = UnixMillis(0);
53
54    /// The time `millis` milliseconds after the epoch: its integer form.
55    pub const fn from_millis(millis: u64) -> UnixMillis {
56        UnixMillis(millis)
57    }
58
59    /// Its milliseconds since the epoch: its integer form.
60    pub const fn as_millis(self) -> u64 {
61        self.0
62    }
63
64    /// The time `offset` from the epoch, `Ok` after it and `Err` before it,
65    /// as `SystemTime::duration_since(UNIX_EPOCH)` gives a clock reading.
66    ///
67    /// The one rule: a time before the epoch is the epoch, a time past
68    /// `u64::MAX` milliseconds is that last millisecond, and a fraction of
69    /// a millisecond is dropped.
70    pub fn since_epoch(offset: Result<Duration, Duration>) -> UnixMillis {
71        UnixMillis::saturating(match offset {
72            Ok(after) => u64::try_from(after.as_millis()).map_err(|_| Outside::PastLast),
73            Err(_) => Err(Outside::BeforeEpoch),
74        })
75    }
76
77    /// Its offset from the epoch: what [`UnixMillis::since_epoch`] reads
78    /// back as this time.
79    pub const fn offset(self) -> Duration {
80        Duration::from_millis(self.0)
81    }
82
83    /// The `Instant` this time names.
84    ///
85    /// # Panics
86    ///
87    /// Never: normalizing a count of milliseconds scaled by `10^-3` only
88    /// raises its exponent towards zero.
89    pub fn instant(self) -> Instant {
90        Instant::from_unix_seconds(
91            Decimal::new(BigInt::from(self.0), -3)
92                .expect("normalizing a count of milliseconds only raises its exponent towards 0"),
93        )
94    }
95
96    /// The time `at` is, by [`UnixMillis::since_epoch`]'s rule.
97    pub fn from_instant(at: &Instant) -> UnixMillis {
98        UnixMillis::saturating(millis(at))
99    }
100
101    /// The first time at or after `at`: [`UnixMillis::from_instant`]'s,
102    /// one millisecond on when that drops a fraction. What a host asks a
103    /// held call again at, so it is never asked before its `retry_at`.
104    pub fn at_or_after(at: &Instant) -> UnixMillis {
105        let time = UnixMillis::from_instant(at);
106        if time.instant() < *at {
107            UnixMillis(time.0.saturating_add(1))
108        } else {
109            time
110        }
111    }
112
113    /// The time `millis` gives, or the end of the range it falls beyond.
114    fn saturating(millis: Result<u64, Outside>) -> UnixMillis {
115        match millis {
116            Ok(millis) => UnixMillis(millis),
117            Err(Outside::BeforeEpoch) => UnixMillis::EPOCH,
118            Err(Outside::PastLast) => UnixMillis(u64::MAX),
119        }
120    }
121
122    /// The time `at` names when it is exactly one: a whole number of
123    /// milliseconds in the range.
124    fn exactly(at: &Instant) -> Option<UnixMillis> {
125        let time = UnixMillis::from_instant(at);
126        (time.instant() == *at).then_some(time)
127    }
128}
129
130/// The whole milliseconds from the epoch to `at`, its fraction dropped, or
131/// the end of the range it falls beyond.
132fn millis(at: &Instant) -> Result<u64, Outside> {
133    if *at < UnixMillis::EPOCH.instant() {
134        return Err(Outside::BeforeEpoch);
135    }
136    at.unix_seconds()
137        .mul(&Decimal::from(&Int::from(1000)))
138        .ok()
139        .and_then(|millis| millis.floor_within(64))
140        .and_then(|millis| u64::try_from(millis.as_bigint()).ok())
141        .ok_or(Outside::PastLast)
142}
143
144/// The `Instant` it names, such as `2026-11-19T10:02:11.482Z`, with the
145/// fewest fractional-second digits that are exact.
146impl fmt::Display for UnixMillis {
147    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148        self.instant().fmt(f)
149    }
150}
151
152impl fmt::Debug for UnixMillis {
153    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154        self.0.fmt(f)
155    }
156}
157
158/// An `Instant`'s text, read as decoding reads one ([`crate::primitives::instant`]),
159/// a fraction finer than a millisecond dropped.
160impl FromStr for UnixMillis {
161    type Err = TimeTextError;
162
163    fn from_str(text: &str) -> Result<UnixMillis, TimeTextError> {
164        let at = crate::time::instant(text).ok_or(TimeTextError::NotInstantText)?;
165        millis(&at).map(UnixMillis).map_err(TimeTextError::Outside)
166    }
167}
168
169impl fmt::Display for TimeTextError {
170    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171        f.write_str(match self {
172            TimeTextError::NotInstantText => {
173                "is not an Instant's text, such as 2026-11-19T10:02:11.482Z"
174            }
175            TimeTextError::Outside(Outside::BeforeEpoch) => "is before 1970-01-01T00:00:00Z",
176            TimeTextError::Outside(Outside::PastLast) => {
177                "is past the latest time a host keeps, 2^64 - 1 milliseconds after 1970"
178            }
179        })
180    }
181}
182
183impl std::error::Error for TimeTextError {}
184
185/// A time is written as the value encoding writes an `Instant`, which is
186/// how a note keeps one (`trace.md`, *Host notes*): an `Instant` that is not
187/// a whole number of milliseconds in the range is no such time.
188impl Shaped for UnixMillis {
189    const FORM: WireForm = WireForm::Instant;
190
191    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
192        out.instant(ty, &self.instant())
193    }
194
195    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
196        UnixMillis::exactly(&input.instant(ty)?).ok_or_else(|| input.mismatch(ty))
197    }
198}
199
200impl Wire for UnixMillis {
201    fn write_head<'a>(&'a self, out: &mut Vec<u8>, _: &mut Vec<&'a dyn AnyWire>) {
202        self.instant().write(out);
203    }
204
205    fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError> {
206        let at = reader.position();
207        UnixMillis::exactly(&Instant::read(reader)?)
208            .map(Opened::built)
209            .ok_or_else(|| DecodeError {
210                path: Place::default(),
211                problem: format!(
212                    "has a time at byte {at} that is not a whole number of milliseconds"
213                ),
214                kind: DecodeErrorKind::Mismatch,
215            })
216    }
217}
218
219#[cfg(test)]
220#[cfg_attr(coverage, coverage(off))]
221mod tests {
222    use super::*;
223
224    fn instant(seconds: &str) -> Instant {
225        Instant::from_unix_seconds(Decimal::parse(seconds).expect("a decimal"))
226    }
227
228    #[test]
229    fn the_time_at_or_after_an_instant_rounds_a_fraction_up_within_the_range() {
230        let at = |seconds| UnixMillis::at_or_after(&instant(seconds));
231        assert_eq!(at("1.5"), UnixMillis::from_millis(1500));
232        assert_eq!(at("1.5001"), UnixMillis::from_millis(1501));
233        assert_eq!(at("-60"), UnixMillis::EPOCH, "before the epoch");
234        assert_eq!(
235            at("1000000000000000000000000000000"),
236            UnixMillis::from_millis(u64::MAX)
237        );
238    }
239
240    #[test]
241    fn every_conversion_in_keeps_the_one_rule_at_both_ends() {
242        let last = UnixMillis::from_millis(u64::MAX);
243        let millis = Duration::from_millis;
244        assert_eq!(UnixMillis::since_epoch(Err(millis(1))), UnixMillis::EPOCH);
245        assert_eq!(
246            UnixMillis::from_instant(&instant("-0.001")),
247            UnixMillis::EPOCH
248        );
249        assert_eq!(
250            UnixMillis::from_instant(&instant("-1000000000000000000000000000000")),
251            UnixMillis::EPOCH
252        );
253        assert_eq!(
254            UnixMillis::since_epoch(Ok(millis(u64::MAX) + millis(1))),
255            last
256        );
257        assert_eq!(UnixMillis::since_epoch(Ok(Duration::MAX)), last);
258        assert_eq!(
259            UnixMillis::from_instant(&instant("18446744073709551.616")),
260            last
261        );
262        assert_eq!(
263            UnixMillis::from_instant(&instant("1000000000000000000000000000000")),
264            last
265        );
266        assert_eq!(
267            UnixMillis::since_epoch(Ok(Duration::from_micros(1_500_999))),
268            UnixMillis::from_millis(1_500)
269        );
270        assert_eq!(
271            UnixMillis::from_instant(&instant("1.5009")),
272            UnixMillis::from_millis(1_500)
273        );
274    }
275
276    #[test]
277    fn a_time_and_its_offset_and_instant_go_back_and_forth() {
278        for millis in [
279            0,
280            1,
281            1_500,
282            1_795_600_931_482,
283            253_402_300_800_000,
284            u64::MAX,
285        ] {
286            let at = UnixMillis::from_millis(millis);
287            assert_eq!(UnixMillis::since_epoch(Ok(at.offset())), at);
288            assert_eq!(UnixMillis::from_instant(&at.instant()), at);
289            assert_eq!(UnixMillis::decode(&at.bytes()), Ok(at));
290        }
291    }
292
293    #[test]
294    fn its_text_is_the_instant_it_names_and_reads_back() {
295        for (millis, text) in [
296            (0, "1970-01-01T00:00:00Z"),
297            (1_795_600_931_482, "2026-11-25T10:02:11.482Z"),
298            (1_795_600_931_400, "2026-11-25T10:02:11.4Z"),
299            (1_795_600_931_000, "2026-11-25T10:02:11Z"),
300            (253_402_128_000_000, "9999-12-30T00:00:00Z"),
301            (253_402_300_800_000, "+10000-01-01T00:00:00Z"),
302            (u64::MAX, "+584556019-04-03T14:25:51.615Z"),
303        ] {
304            let at = UnixMillis::from_millis(millis);
305            assert_eq!(at.to_string(), text);
306            assert_eq!(text.parse(), Ok(at), "{text}");
307        }
308    }
309
310    #[test]
311    fn text_reads_an_offset_drops_a_fraction_and_refuses_a_time_outside_the_range() {
312        let read = |text: &str| text.parse::<UnixMillis>();
313        assert_eq!(read("1970-01-01T01:00:00+01:00"), Ok(UnixMillis::EPOCH));
314        assert_eq!(
315            read("1970-01-01T00:00:01.2345Z"),
316            Ok(UnixMillis::from_millis(1_234))
317        );
318        assert_eq!(
319            read("1969-12-31T23:59:59.9995Z"),
320            Err(TimeTextError::Outside(Outside::BeforeEpoch))
321        );
322        assert_eq!(
323            read("+584556019-04-03T14:25:51.616Z"),
324            Err(TimeTextError::Outside(Outside::PastLast))
325        );
326        for refused in ["2h", "2026-11-19", "0", "", "2026-11-19 10:00:00Z"] {
327            assert_eq!(
328                read(refused),
329                Err(TimeTextError::NotInstantText),
330                "{refused}"
331            );
332        }
333    }
334
335    #[test]
336    fn a_note_refuses_an_instant_that_is_no_such_time() {
337        for refused in ["-0.001", "0.0005", "18446744073709551.616"] {
338            let bytes = instant(refused).bytes();
339            assert!(UnixMillis::decode(&bytes).is_err(), "{refused}");
340        }
341    }
342}