Skip to main content

sunday_slate/
background.rs

1//! Background-job presentation helpers.
2
3use time::OffsetDateTime;
4use time::format_description::well_known::Rfc3339;
5use utils::background::LastRun;
6
7/// What a page shows about the last run: when it finished, whether it
8/// succeeded, and one line of text.
9pub struct LastRunView {
10    pub finished_at: String,
11    pub ok: bool,
12    pub text: String,
13}
14
15pub trait LastRunExt<R> {
16    fn view(self, describe: impl FnOnce(R) -> String) -> LastRunView;
17}
18
19impl<R> LastRunExt<R> for LastRun<R> {
20    /// `describe` turns a successful outcome into its display text. An error
21    /// outcome shows the error string.
22    fn view(self, describe: impl FnOnce(R) -> String) -> LastRunView {
23        let (ok, text) = match self.outcome {
24            Ok(value) => (true, describe(value)),
25            Err(error) => (false, error),
26        };
27        LastRunView {
28            finished_at: format_timestamp(self.finished_at),
29            ok,
30            text,
31        }
32    }
33}
34
35/// Format a timestamp as RFC3339, truncated to whole seconds.
36pub fn format_timestamp(timestamp: OffsetDateTime) -> String {
37    timestamp
38        .to_offset(time::UtcOffset::UTC)
39        .replace_nanosecond(0)
40        .expect("0 ns is valid")
41        .format(&Rfc3339)
42        .expect("RFC3339 formatting cannot fail")
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48    use time::macros::datetime;
49
50    #[test]
51    fn format_timestamp_truncates_to_whole_seconds() {
52        assert_eq!(
53            format_timestamp(datetime!(2026-08-25 03:31:58.513 UTC)),
54            "2026-08-25T03:31:58Z"
55        );
56    }
57}