Skip to main content

schedr_client/
times.rs

1//! Times in the CLI: reading `--for` and showing a moment in UTC and local time (see
2//! archive/PROJECT.md, Web UI and CLI: times and time zones).
3//!
4//! `--for` without an offset is **UTC**, with a warning naming the moment taken; an explicit
5//! offset is used as given. Every time shown to a person appears twice, UTC and the machine's
6//! zone (`2026-10-15 03:00 UTC (05:00 CEST)`); JSON output has UTC only.
7
8use jiff::civil::{Date, DateTime};
9use jiff::tz::TimeZone;
10use jiff::{Timestamp, Zoned};
11
12#[cfg(test)]
13mod tests;
14
15/// A moment read from `--for`.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct ForTime {
18    /// The moment.
19    pub at: Timestamp,
20    /// A warning when it had no offset and was read as UTC.
21    pub warning: Option<String>,
22}
23
24/// Reads a `--for` value: an RFC 3339 / ISO 8601 date-time with an offset, or one without
25/// (UTC), or a date (midnight UTC).
26///
27/// # Errors
28///
29/// A message naming the accepted forms.
30pub fn parse_for(text: &str) -> Result<ForTime, String> {
31    parse_time_flag("--for", text)
32}
33
34/// Reads a moment given as `flag` (`--from`, `--to`) as [`parse_for`] reads `--for`.
35///
36/// # Errors
37///
38/// A message naming the flag and the accepted forms.
39pub fn parse_time_flag(flag: &str, text: &str) -> Result<ForTime, String> {
40    if let Ok(at) = text.parse::<Timestamp>() {
41        return Ok(ForTime { at, warning: None });
42    }
43    let civil = text
44        .parse::<DateTime>()
45        .or_else(|_| {
46            text.parse::<Date>()
47                .map(|d| d.to_datetime(jiff::civil::Time::midnight()))
48        })
49        .map_err(|_| {
50            format!(
51                "`{flag} {text}` isn't a date or a date-time \
52                 (e.g. 2026-10-15T03:00, 2026-10-15T03:00+02:00, 2026-10-15)"
53            )
54        })?;
55    let at = civil
56        .to_zoned(TimeZone::UTC)
57        .map_err(|e| e.to_string())?
58        .timestamp();
59    Ok(ForTime {
60        at,
61        warning: Some(format!(
62            "warning: no offset given: interpreted as {} (UTC)",
63            short_utc(at)
64        )),
65    })
66}
67
68/// A moment in UTC and in `local`, e.g. `2026-10-15 03:00 UTC (05:00 CEST)`; the local date is
69/// shown only when it differs, and the local part is left out when `local` is UTC.
70#[must_use]
71pub fn show(at: Timestamp, local: &TimeZone) -> String {
72    shown(at, local, clock)
73}
74
75/// As [`show`], always with seconds (`03:00:00`): moments in a column line up (the UI's run
76/// lists, where whole-minute planned times were shorter than the rest).
77#[must_use]
78pub fn show_seconds(at: Timestamp, local: &TimeZone) -> String {
79    shown(at, local, |zoned| zoned.strftime("%H:%M:%S").to_string())
80}
81
82fn shown(at: Timestamp, local: &TimeZone, clock: impl Fn(&Zoned) -> String) -> String {
83    let utc = at.to_zoned(TimeZone::UTC);
84    let text = format!("{} {} UTC", utc.strftime("%Y-%m-%d"), clock(&utc));
85    let here = at.to_zoned(local.clone());
86    if here.offset() == utc.offset() && local.iana_name() == Some("UTC") {
87        return text;
88    }
89    let date = if here.date() == utc.date() {
90        String::new()
91    } else {
92        format!("{} ", here.strftime("%Y-%m-%d"))
93    };
94    format!("{text} ({date}{} {})", clock(&here), here.strftime("%Z"))
95}
96
97/// A moment in short form, where space matters: UTC, then the local zone's offset from UTC
98/// at that moment, e.g. `2026-01-01 00:00Z (local:+1h)`, `2026-10-15 01:00Z
99/// (local:-4h)`, `2026-10-15 03:00Z (local:+5h30m)`; no offset part when it is zero.
100#[must_use]
101pub fn show_short(at: Timestamp, local: &TimeZone) -> String {
102    let utc = at.to_zoned(TimeZone::UTC);
103    let text = format!("{} {}Z", utc.strftime("%Y-%m-%d"), clock(&utc));
104    let seconds = local.to_offset(at).seconds();
105    if seconds == 0 {
106        return text;
107    }
108    let sign = if seconds < 0 { '-' } else { '+' };
109    let (hours, minutes) = (seconds.abs() / 3600, seconds.abs() % 3600 / 60);
110    let offset = if minutes == 0 {
111        format!("{hours}h")
112    } else {
113        format!("{hours}h{minutes:02}m")
114    };
115    format!("{text} (local:{sign}{offset})")
116}
117
118/// `HH:MM`, with seconds when they aren't zero.
119fn clock(zoned: &Zoned) -> String {
120    if zoned.second() == 0 && zoned.subsec_nanosecond() == 0 {
121        zoned.strftime("%H:%M").to_string()
122    } else {
123        zoned.strftime("%H:%M:%S").to_string()
124    }
125}
126
127/// `2026-10-15T03:00Z`, as the `--for` warning shows it.
128fn short_utc(at: Timestamp) -> String {
129    let utc = at.to_zoned(TimeZone::UTC);
130    format!("{}T{}Z", utc.strftime("%Y-%m-%d"), clock(&utc))
131}
132
133/// The machine's time zone: `TZ` when set and known, else the system's, else UTC.
134#[must_use]
135pub fn local_zone(tz: Option<&str>) -> TimeZone {
136    tz.and_then(|name| TimeZone::get(name.trim_start_matches(':')).ok())
137        .or_else(|| TimeZone::try_system().ok())
138        .unwrap_or(TimeZone::UTC)
139}
140
141/// A trigger as people write it: `0 3 * * * (Europe/Warsaw)`, `every 1h, catchup`,
142/// `@daily, 2025-12-31 23:00Z (local:+1h)..` (its window, either end open), `once at …`,
143/// `-`; times in UTC with `local`'s offset. `trigger` is a DAG's trigger in DAG JSON.
144#[must_use]
145pub fn trigger_text(trigger: &serde_json::Value, local: &TimeZone) -> String {
146    let time = |key: &str| {
147        trigger[key]
148            .as_str()
149            .and_then(|text| text.parse::<Timestamp>().ok())
150            .map(|at| show_short(at, local))
151    };
152    let text = match trigger["kind"].as_str() {
153        Some("cron") => {
154            let expression = trigger["expression"].as_str().unwrap_or_default();
155            match trigger["timezone"].as_str() {
156                Some("UTC") | None => expression.to_owned(),
157                Some(zone) => format!("{expression} ({zone})"),
158            }
159        }
160        Some("every") => {
161            let ms = trigger["interval_ms"].as_u64().unwrap_or(0);
162            format!(
163                "every {:#}",
164                jiff::SignedDuration::from_millis(i64::try_from(ms).unwrap_or(i64::MAX))
165            )
166        }
167        Some("once") => format!("once at {}", time("at").unwrap_or_default()),
168        Some("run_of") => {
169            let of = &trigger["run_of"];
170            let dag = of["dag"].as_str().unwrap_or_default();
171            match of["task"].as_str() {
172                Some(task) => format!("after {dag} {task}"),
173                None => format!("after {dag}"),
174            }
175        }
176        Some("chained") => match trigger["by"].as_array() {
177            Some(by) => {
178                let names: Vec<&str> = by.iter().filter_map(serde_json::Value::as_str).collect();
179                format!("chained from {}", names.join(", "))
180            }
181            None => "chained".to_owned(),
182        },
183        Some("event") => format!(
184            "@trigger {}",
185            trigger["task"]["id"].as_str().unwrap_or_default()
186        ),
187        Some("event_named") => format!(
188            "event {}",
189            trigger["event"]["name"].as_str().unwrap_or_default()
190        ),
191        _ => "-".to_owned(),
192    };
193    let mut parts = vec![text];
194    if trigger["catchup"].as_bool() == Some(true) {
195        parts.push("catchup".to_owned());
196    }
197    match (time("start"), time("end")) {
198        (None, None) => {}
199        (start, end) => parts.push(format!(
200            "{}..{}",
201            start.unwrap_or_default(),
202            end.unwrap_or_default()
203        )),
204    }
205    parts.join(", ")
206}