Skip to main content

aidaemon_tools/
duration_format.rs

1//! Compact durations for messages to the owner (`45s`, `3m 10s`, `2h`).
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4pub enum ZeroUnitStyle {
5    Keep,
6    Trim,
7}
8
9pub fn compact_seconds(secs: i64, zero_style: ZeroUnitStyle) -> String {
10    let secs = secs.max(0);
11    if secs < 60 {
12        format!("{}s", secs)
13    } else if secs < 3600 {
14        let mins = secs / 60;
15        let remaining_secs = secs % 60;
16        if zero_style == ZeroUnitStyle::Trim && remaining_secs == 0 {
17            format!("{}m", mins)
18        } else {
19            format!("{}m {}s", mins, remaining_secs)
20        }
21    } else {
22        let hours = secs / 3600;
23        let mins = (secs % 3600) / 60;
24        if zero_style == ZeroUnitStyle::Trim && mins == 0 {
25            format!("{}h", hours)
26        } else {
27            format!("{}h {}m", hours, mins)
28        }
29    }
30}
31
32pub fn compact_chrono_duration(duration: chrono::Duration, zero_style: ZeroUnitStyle) -> String {
33    compact_seconds(duration.num_seconds(), zero_style)
34}
35
36pub fn compact_elapsed_timestamps(
37    started_at: Option<&str>,
38    completed_at: Option<&str>,
39    zero_style: ZeroUnitStyle,
40) -> String {
41    let Some(start_raw) = started_at else {
42        return "n/a".to_string();
43    };
44    let Some(started) = parse_ts(start_raw) else {
45        return "n/a".to_string();
46    };
47    let Some(end_raw) = completed_at else {
48        return "running".to_string();
49    };
50    let Some(ended) = parse_ts(end_raw) else {
51        return "n/a".to_string();
52    };
53
54    compact_chrono_duration(ended - started, zero_style)
55}
56
57/// How long ago an RFC 3339 timestamp was, in its largest whole unit
58/// ("3d ago", "5h ago", "12m ago", "just now"); "n/a" when it does not parse.
59pub fn format_age(ts: &str) -> String {
60    let Some(dt) = parse_ts(ts) else {
61        return "n/a".to_string();
62    };
63    let age = chrono::Utc::now() - dt;
64    if age.num_days() > 0 {
65        format!("{}d ago", age.num_days())
66    } else if age.num_hours() > 0 {
67        format!("{}h ago", age.num_hours())
68    } else if age.num_minutes() > 0 {
69        format!("{}m ago", age.num_minutes())
70    } else {
71        "just now".to_string()
72    }
73}
74
75fn parse_ts(ts: &str) -> Option<chrono::DateTime<chrono::Utc>> {
76    chrono::DateTime::parse_from_rfc3339(ts)
77        .ok()
78        .map(|d| d.with_timezone(&chrono::Utc))
79}
80
81#[cfg(test)]
82mod tests {
83    use chrono::Duration;
84
85    use super::*;
86
87    #[test]
88    fn format_age_names_the_largest_whole_unit() {
89        let ago = |age: Duration| format_age(&(chrono::Utc::now() - age).to_rfc3339());
90        assert_eq!(ago(Duration::days(3) + Duration::hours(5)), "3d ago");
91        assert_eq!(ago(Duration::hours(5) + Duration::minutes(2)), "5h ago");
92        assert_eq!(ago(Duration::minutes(12)), "12m ago");
93        assert_eq!(ago(Duration::seconds(5)), "just now");
94        assert_eq!(format_age("not a time"), "n/a");
95    }
96
97    #[test]
98    fn compact_seconds_preserves_zero_units() {
99        assert_eq!(compact_seconds(40, ZeroUnitStyle::Keep), "40s");
100        assert_eq!(compact_seconds(60, ZeroUnitStyle::Keep), "1m 0s");
101        assert_eq!(compact_seconds(3600, ZeroUnitStyle::Keep), "1h 0m");
102    }
103
104    #[test]
105    fn compact_seconds_can_trim_zero_units() {
106        assert_eq!(compact_seconds(60, ZeroUnitStyle::Trim), "1m");
107        assert_eq!(compact_seconds(90, ZeroUnitStyle::Trim), "1m 30s");
108        assert_eq!(compact_seconds(3600, ZeroUnitStyle::Trim), "1h");
109        assert_eq!(compact_seconds(3660, ZeroUnitStyle::Trim), "1h 1m");
110    }
111
112    #[test]
113    fn compact_chrono_duration_clamps_negative_to_zero() {
114        assert_eq!(
115            compact_chrono_duration(Duration::seconds(-5), ZeroUnitStyle::Keep),
116            "0s"
117        );
118    }
119
120    #[test]
121    fn compact_elapsed_timestamps_handles_missing_and_running() {
122        assert_eq!(
123            compact_elapsed_timestamps(None, None, ZeroUnitStyle::Keep),
124            "n/a"
125        );
126        assert_eq!(
127            compact_elapsed_timestamps(Some("2026-01-01T00:00:00Z"), None, ZeroUnitStyle::Keep),
128            "running"
129        );
130        assert_eq!(
131            compact_elapsed_timestamps(
132                Some("2026-01-01T00:00:00Z"),
133                Some("2026-01-01T01:02:03Z"),
134                ZeroUnitStyle::Keep
135            ),
136            "1h 2m"
137        );
138    }
139}