flow-abi 0.1.0-rc.5

The host boundary's value encoding: the binary encoding and the JSON form, the canonical form and its hash, JSON Schemas, Tool signatures, and the answers a Tool call passes.
Documentation
//! [`UnixMillis`], a time on a host's wall clock, and the one rule every
//! conversion into it keeps.

use std::fmt;
use std::str::FromStr;
use std::time::Duration;

use flow_value::{BigInt, Decimal, Instant, Int};

use crate::binary::{ValueReader, ValueWriter};
use crate::bytes::Reader;
use crate::error::{DecodeError, DecodeErrorKind, EncodeError, Place};
use crate::wire::{AnyWire, Opened, Shaped, Type, Wire, WireForm};

/// A time on a host's wall clock, in whole milliseconds since the Unix
/// epoch: when a run started or ended, when a held call is asked again,
/// when a daemon started. A host reads it for its own records, and a run
/// never sees it as a value.
///
/// Its range is the epoch through `u64::MAX` milliseconds after it, and
/// every conversion into it keeps the one rule [`UnixMillis::since_epoch`]
/// states. Only reading text refuses a time outside the range
/// ([`Outside`]), since a person gave it. A clock is read where a host
/// reads one: this type only does the arithmetic on what it read.
///
/// Its text is the `Instant` it names, as an `Instant` is written. Its
/// integer form, which a lock file, the daemon's pipe and a log line carry,
/// is [`UnixMillis::as_millis`], and it is what its `Debug` form shows.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct UnixMillis(u64);

/// Which end of [`UnixMillis`]'s range a time falls beyond.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Outside {
    /// It is before the Unix epoch.
    BeforeEpoch,
    /// It is past `u64::MAX` milliseconds after the epoch.
    PastLast,
}

/// Why text is no [`UnixMillis`].
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum TimeTextError {
    /// It is not an `Instant`'s text as decoding reads it (`abi.md`, *Decoding*).
    NotInstantText,
    /// It names a time outside the range.
    Outside(Outside),
}

impl UnixMillis {
    /// The Unix epoch.
    pub const EPOCH: UnixMillis = UnixMillis(0);

    /// The time `millis` milliseconds after the epoch: its integer form.
    pub const fn from_millis(millis: u64) -> UnixMillis {
        UnixMillis(millis)
    }

    /// Its milliseconds since the epoch: its integer form.
    pub const fn as_millis(self) -> u64 {
        self.0
    }

    /// The time `offset` from the epoch, `Ok` after it and `Err` before it,
    /// as `SystemTime::duration_since(UNIX_EPOCH)` gives a clock reading.
    ///
    /// The one rule: a time before the epoch is the epoch, a time past
    /// `u64::MAX` milliseconds is that last millisecond, and a fraction of
    /// a millisecond is dropped.
    pub fn since_epoch(offset: Result<Duration, Duration>) -> UnixMillis {
        UnixMillis::saturating(match offset {
            Ok(after) => u64::try_from(after.as_millis()).map_err(|_| Outside::PastLast),
            Err(_) => Err(Outside::BeforeEpoch),
        })
    }

    /// Its offset from the epoch: what [`UnixMillis::since_epoch`] reads
    /// back as this time.
    pub const fn offset(self) -> Duration {
        Duration::from_millis(self.0)
    }

    /// The `Instant` this time names.
    ///
    /// # Panics
    ///
    /// Never: normalizing a count of milliseconds scaled by `10^-3` only
    /// raises its exponent towards zero.
    pub fn instant(self) -> Instant {
        Instant::from_unix_seconds(
            Decimal::new(BigInt::from(self.0), -3)
                .expect("normalizing a count of milliseconds only raises its exponent towards 0"),
        )
    }

    /// The time `at` is, by [`UnixMillis::since_epoch`]'s rule.
    pub fn from_instant(at: &Instant) -> UnixMillis {
        UnixMillis::saturating(millis(at))
    }

    /// The first time at or after `at`: [`UnixMillis::from_instant`]'s,
    /// one millisecond on when that drops a fraction. What a host asks a
    /// held call again at, so it is never asked before its `retry_at`.
    pub fn at_or_after(at: &Instant) -> UnixMillis {
        let time = UnixMillis::from_instant(at);
        if time.instant() < *at {
            UnixMillis(time.0.saturating_add(1))
        } else {
            time
        }
    }

    /// The time `millis` gives, or the end of the range it falls beyond.
    fn saturating(millis: Result<u64, Outside>) -> UnixMillis {
        match millis {
            Ok(millis) => UnixMillis(millis),
            Err(Outside::BeforeEpoch) => UnixMillis::EPOCH,
            Err(Outside::PastLast) => UnixMillis(u64::MAX),
        }
    }

    /// The time `at` names when it is exactly one: a whole number of
    /// milliseconds in the range.
    fn exactly(at: &Instant) -> Option<UnixMillis> {
        let time = UnixMillis::from_instant(at);
        (time.instant() == *at).then_some(time)
    }
}

/// The whole milliseconds from the epoch to `at`, its fraction dropped, or
/// the end of the range it falls beyond.
fn millis(at: &Instant) -> Result<u64, Outside> {
    if *at < UnixMillis::EPOCH.instant() {
        return Err(Outside::BeforeEpoch);
    }
    at.unix_seconds()
        .mul(&Decimal::from(&Int::from(1000)))
        .ok()
        .and_then(|millis| millis.floor_within(64))
        .and_then(|millis| u64::try_from(millis.as_bigint()).ok())
        .ok_or(Outside::PastLast)
}

/// The `Instant` it names, such as `2026-11-19T10:02:11.482Z`, with the
/// fewest fractional-second digits that are exact.
impl fmt::Display for UnixMillis {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.instant().fmt(f)
    }
}

impl fmt::Debug for UnixMillis {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// An `Instant`'s text, read as decoding reads one ([`crate::primitives::instant`]),
/// a fraction finer than a millisecond dropped.
impl FromStr for UnixMillis {
    type Err = TimeTextError;

    fn from_str(text: &str) -> Result<UnixMillis, TimeTextError> {
        let at = crate::time::instant(text).ok_or(TimeTextError::NotInstantText)?;
        millis(&at).map(UnixMillis).map_err(TimeTextError::Outside)
    }
}

impl fmt::Display for TimeTextError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            TimeTextError::NotInstantText => {
                "is not an Instant's text, such as 2026-11-19T10:02:11.482Z"
            }
            TimeTextError::Outside(Outside::BeforeEpoch) => "is before 1970-01-01T00:00:00Z",
            TimeTextError::Outside(Outside::PastLast) => {
                "is past the latest time a host keeps, 2^64 - 1 milliseconds after 1970"
            }
        })
    }
}

impl std::error::Error for TimeTextError {}

/// A time is written as the value encoding writes an `Instant`, which is
/// how a note keeps one (`trace.md`, *Host notes*): an `Instant` that is not
/// a whole number of milliseconds in the range is no such time.
impl Shaped for UnixMillis {
    const FORM: WireForm = WireForm::Instant;

    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
        out.instant(ty, &self.instant())
    }

    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
        UnixMillis::exactly(&input.instant(ty)?).ok_or_else(|| input.mismatch(ty))
    }
}

impl Wire for UnixMillis {
    fn write_head<'a>(&'a self, out: &mut Vec<u8>, _: &mut Vec<&'a dyn AnyWire>) {
        self.instant().write(out);
    }

    fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError> {
        let at = reader.position();
        UnixMillis::exactly(&Instant::read(reader)?)
            .map(Opened::built)
            .ok_or_else(|| DecodeError {
                path: Place::default(),
                problem: format!(
                    "has a time at byte {at} that is not a whole number of milliseconds"
                ),
                kind: DecodeErrorKind::Mismatch,
            })
    }
}

#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
mod tests {
    use super::*;

    fn instant(seconds: &str) -> Instant {
        Instant::from_unix_seconds(Decimal::parse(seconds).expect("a decimal"))
    }

    #[test]
    fn the_time_at_or_after_an_instant_rounds_a_fraction_up_within_the_range() {
        let at = |seconds| UnixMillis::at_or_after(&instant(seconds));
        assert_eq!(at("1.5"), UnixMillis::from_millis(1500));
        assert_eq!(at("1.5001"), UnixMillis::from_millis(1501));
        assert_eq!(at("-60"), UnixMillis::EPOCH, "before the epoch");
        assert_eq!(
            at("1000000000000000000000000000000"),
            UnixMillis::from_millis(u64::MAX)
        );
    }

    #[test]
    fn every_conversion_in_keeps_the_one_rule_at_both_ends() {
        let last = UnixMillis::from_millis(u64::MAX);
        let millis = Duration::from_millis;
        assert_eq!(UnixMillis::since_epoch(Err(millis(1))), UnixMillis::EPOCH);
        assert_eq!(
            UnixMillis::from_instant(&instant("-0.001")),
            UnixMillis::EPOCH
        );
        assert_eq!(
            UnixMillis::from_instant(&instant("-1000000000000000000000000000000")),
            UnixMillis::EPOCH
        );
        assert_eq!(
            UnixMillis::since_epoch(Ok(millis(u64::MAX) + millis(1))),
            last
        );
        assert_eq!(UnixMillis::since_epoch(Ok(Duration::MAX)), last);
        assert_eq!(
            UnixMillis::from_instant(&instant("18446744073709551.616")),
            last
        );
        assert_eq!(
            UnixMillis::from_instant(&instant("1000000000000000000000000000000")),
            last
        );
        assert_eq!(
            UnixMillis::since_epoch(Ok(Duration::from_micros(1_500_999))),
            UnixMillis::from_millis(1_500)
        );
        assert_eq!(
            UnixMillis::from_instant(&instant("1.5009")),
            UnixMillis::from_millis(1_500)
        );
    }

    #[test]
    fn a_time_and_its_offset_and_instant_go_back_and_forth() {
        for millis in [
            0,
            1,
            1_500,
            1_795_600_931_482,
            253_402_300_800_000,
            u64::MAX,
        ] {
            let at = UnixMillis::from_millis(millis);
            assert_eq!(UnixMillis::since_epoch(Ok(at.offset())), at);
            assert_eq!(UnixMillis::from_instant(&at.instant()), at);
            assert_eq!(UnixMillis::decode(&at.bytes()), Ok(at));
        }
    }

    #[test]
    fn its_text_is_the_instant_it_names_and_reads_back() {
        for (millis, text) in [
            (0, "1970-01-01T00:00:00Z"),
            (1_795_600_931_482, "2026-11-25T10:02:11.482Z"),
            (1_795_600_931_400, "2026-11-25T10:02:11.4Z"),
            (1_795_600_931_000, "2026-11-25T10:02:11Z"),
            (253_402_128_000_000, "9999-12-30T00:00:00Z"),
            (253_402_300_800_000, "+10000-01-01T00:00:00Z"),
            (u64::MAX, "+584556019-04-03T14:25:51.615Z"),
        ] {
            let at = UnixMillis::from_millis(millis);
            assert_eq!(at.to_string(), text);
            assert_eq!(text.parse(), Ok(at), "{text}");
        }
    }

    #[test]
    fn text_reads_an_offset_drops_a_fraction_and_refuses_a_time_outside_the_range() {
        let read = |text: &str| text.parse::<UnixMillis>();
        assert_eq!(read("1970-01-01T01:00:00+01:00"), Ok(UnixMillis::EPOCH));
        assert_eq!(
            read("1970-01-01T00:00:01.2345Z"),
            Ok(UnixMillis::from_millis(1_234))
        );
        assert_eq!(
            read("1969-12-31T23:59:59.9995Z"),
            Err(TimeTextError::Outside(Outside::BeforeEpoch))
        );
        assert_eq!(
            read("+584556019-04-03T14:25:51.616Z"),
            Err(TimeTextError::Outside(Outside::PastLast))
        );
        for refused in ["2h", "2026-11-19", "0", "", "2026-11-19 10:00:00Z"] {
            assert_eq!(
                read(refused),
                Err(TimeTextError::NotInstantText),
                "{refused}"
            );
        }
    }

    #[test]
    fn a_note_refuses_an_instant_that_is_no_such_time() {
        for refused in ["-0.001", "0.0005", "18446744073709551.616"] {
            let bytes = instant(refused).bytes();
            assert!(UnixMillis::decode(&bytes).is_err(), "{refused}");
        }
    }
}