Skip to main content

gemini_adk_rs/utils/
time.rs

1//! Wall-clock timestamps without a date-time dependency.
2//!
3//! The runtime reads time through a [`Clock`](crate::clock::Clock) wherever a
4//! decision depends on it. These helpers are for the other case: stamping a
5//! record (a session, a trace, a stored artifact) with when it was written.
6
7use std::time::{SystemTime, UNIX_EPOCH};
8
9/// Seconds since the Unix epoch; `0` if the system clock is before it.
10pub(crate) fn now_secs() -> u64 {
11    SystemTime::now()
12        .duration_since(UNIX_EPOCH)
13        .unwrap_or_default()
14        .as_secs()
15}
16
17/// The current time as RFC 3339 in UTC, to the second:
18/// `2024-02-29T12:34:56Z`.
19pub fn now_rfc3339() -> String {
20    format_rfc3339(SystemTime::now())
21}
22
23/// The current time as RFC 3339 in UTC, to the millisecond:
24/// `2024-02-29T12:34:56.789Z`.
25pub fn now_rfc3339_millis() -> String {
26    format_rfc3339_millis(SystemTime::now())
27}
28
29/// `time` as RFC 3339 in UTC, to the second (`2024-02-29T12:34:56Z`).
30///
31/// A time before the Unix epoch is formatted as the epoch.
32///
33/// ```
34/// use std::time::{Duration, UNIX_EPOCH};
35/// use gemini_adk_rs::utils::time::format_rfc3339;
36///
37/// assert_eq!(format_rfc3339(UNIX_EPOCH), "1970-01-01T00:00:00Z");
38/// assert_eq!(
39///     format_rfc3339(UNIX_EPOCH + Duration::from_secs(1_709_210_096)),
40///     "2024-02-29T12:34:56Z"
41/// );
42/// ```
43pub fn format_rfc3339(time: SystemTime) -> String {
44    let since_epoch = time.duration_since(UNIX_EPOCH).unwrap_or_default();
45    let (date, clock) = civil(since_epoch.as_secs());
46    format!("{date}T{clock}Z")
47}
48
49/// `time` as RFC 3339 in UTC, to the millisecond (`2024-02-29T12:34:56.789Z`).
50///
51/// A time before the Unix epoch is formatted as the epoch.
52pub fn format_rfc3339_millis(time: SystemTime) -> String {
53    let since_epoch = time.duration_since(UNIX_EPOCH).unwrap_or_default();
54    let (date, clock) = civil(since_epoch.as_secs());
55    format!("{date}T{clock}.{:03}Z", since_epoch.subsec_millis())
56}
57
58/// `("YYYY-MM-DD", "HH:MM:SS")` for `secs` since the Unix epoch.
59fn civil(secs: u64) -> (String, String) {
60    let (days, rem) = (secs / 86_400, secs % 86_400);
61    // Civil date from days since 1970-01-01 (Howard Hinnant's algorithm).
62    let z = days as i64 + 719_468;
63    let era = z.div_euclid(146_097);
64    let doe = z.rem_euclid(146_097);
65    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
66    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
67    let mp = (5 * doy + 2) / 153;
68    let day = doy - (153 * mp + 2) / 5 + 1;
69    let month = if mp < 10 { mp + 3 } else { mp - 9 };
70    let year = yoe + era * 400 + i64::from(month <= 2);
71    (
72        format!("{year:04}-{month:02}-{day:02}"),
73        format!("{:02}:{:02}:{:02}", rem / 3_600, rem % 3_600 / 60, rem % 60),
74    )
75}
76
77#[cfg(test)]
78mod tests {
79    use super::*;
80    use std::time::Duration;
81
82    fn at(secs: u64) -> SystemTime {
83        UNIX_EPOCH + Duration::from_secs(secs)
84    }
85
86    #[test]
87    fn known_instants_format_as_rfc_3339() {
88        let cases = [
89            (0, "1970-01-01T00:00:00Z"),
90            (86_399, "1970-01-01T23:59:59Z"),
91            (86_400, "1970-01-02T00:00:00Z"),
92            // 2000 is a leap year (divisible by 400): Feb 29 exists.
93            (951_782_400, "2000-02-29T00:00:00Z"),
94            (951_868_800, "2000-03-01T00:00:00Z"),
95            // 2024 leap day, mid-day.
96            (1_709_210_096, "2024-02-29T12:34:56Z"),
97            // Century rule: 2100 is not a leap year, so no Feb 29 there.
98            (4_107_542_400, "2100-03-01T00:00:00Z"),
99            (1_000_000_000, "2001-09-09T01:46:40Z"),
100            (2_000_000_000, "2033-05-18T03:33:20Z"),
101            (4_102_444_799, "2099-12-31T23:59:59Z"),
102        ];
103        for (secs, expected) in cases {
104            assert_eq!(format_rfc3339(at(secs)), expected, "{secs}");
105        }
106    }
107
108    #[test]
109    fn leap_day_is_followed_by_march_first() {
110        assert_eq!(format_rfc3339(at(1_709_164_800)), "2024-02-29T00:00:00Z");
111        assert_eq!(
112            format_rfc3339(at(1_709_164_800 + 86_400)),
113            "2024-03-01T00:00:00Z"
114        );
115    }
116
117    #[test]
118    fn millis_variant_adds_three_digits() {
119        let t = at(1_709_210_096) + Duration::from_millis(7);
120        assert_eq!(format_rfc3339_millis(t), "2024-02-29T12:34:56.007Z");
121        assert_eq!(
122            format_rfc3339_millis(UNIX_EPOCH),
123            "1970-01-01T00:00:00.000Z"
124        );
125    }
126
127    #[test]
128    fn a_time_before_the_epoch_is_the_epoch() {
129        assert_eq!(
130            format_rfc3339(UNIX_EPOCH - Duration::from_secs(5)),
131            "1970-01-01T00:00:00Z"
132        );
133    }
134
135    #[test]
136    fn now_is_well_formed() {
137        let now = now_rfc3339();
138        assert_eq!(now.len(), "2024-02-29T12:34:56Z".len(), "{now}");
139        assert!(now.ends_with('Z') && now.as_bytes()[10] == b'T', "{now}");
140        assert!(now_rfc3339_millis().len() == now.len() + 4);
141        assert!(now_secs() > 1_700_000_000);
142    }
143}