Skip to main content

schedr_ui/
page.rs

1//! What every page needs from its request: the path prefix links start with, and the
2//! browser's time zone (from the cookie the page's script sets).
3
4use axum::http::HeaderMap;
5use jiff::Timestamp;
6use jiff::tz::TimeZone;
7use schedr_client::times::{show, show_seconds};
8
9#[cfg(test)]
10mod tests;
11
12/// The header a reverse proxy serving the UI under a path sets (e.g. `/schedr`).
13pub const PREFIX_HEADER: &str = "x-forwarded-prefix";
14
15/// The cookie holding the browser's IANA time zone, set by the page's inline script.
16pub const ZONE_COOKIE: &str = "schedr_tz";
17
18/// A page's context.
19#[derive(Debug, Clone)]
20pub struct Page {
21    /// What links start with: the proxy's prefix, without a trailing slash (`""` at the root).
22    pub base: String,
23    /// The browser's zone, once its cookie is set; `None`: times in UTC only.
24    pub zone: Option<TimeZone>,
25    /// Whether the documentation is served (a link in the header).
26    pub docs: bool,
27    /// The page's stream of changes (`/events?...`), with the prefix; empty: the page isn't
28    /// live.
29    pub events: String,
30    /// Where the page's live parts are read again from when something changed, with the
31    /// prefix.
32    pub refresh: String,
33}
34
35impl Page {
36    /// The context of a request with `headers`.
37    #[must_use]
38    pub fn new(headers: &HeaderMap, docs: bool) -> Self {
39        Self {
40            base: prefix(headers),
41            zone: zone(headers),
42            docs,
43            events: String::new(),
44            refresh: String::new(),
45        }
46    }
47
48    /// This page live: it follows `/events?<follow>` and reads its live parts again from
49    /// `refresh` (both without the prefix, which is added).
50    #[must_use]
51    pub fn live(self, follow: &str, refresh: &str) -> Self {
52        Self {
53            // When it was made: a change after it, which it may not show, is sent as soon
54            // as its stream opens (B144).
55            events: format!(
56                "{}/events?{follow}{}since={}",
57                self.base,
58                if follow.is_empty() { "" } else { "&" },
59                Timestamp::now().as_millisecond()
60            ),
61            refresh: format!("{}{refresh}", self.base),
62            ..self
63        }
64    }
65
66    /// Whether the page is live.
67    #[must_use]
68    pub const fn is_live(&self) -> bool {
69        !self.events.is_empty()
70    }
71
72    /// Whether the browser's zone is known (the script then doesn't reload the page).
73    #[must_use]
74    pub const fn has_zone(&self) -> bool {
75        self.zone.is_some()
76    }
77
78    /// A moment as people read it: `2026-10-15 03:00 UTC (05:00 CEST)`, UTC only until the
79    /// browser's zone is known.
80    #[must_use]
81    pub fn time(&self, at: &Timestamp) -> String {
82        show(*at, self.zone.as_ref().unwrap_or(&TimeZone::UTC))
83    }
84
85    /// As [`Self::time`], always with seconds: for a column of moments, so they line up.
86    #[must_use]
87    pub fn column_time(&self, at: &Timestamp) -> String {
88        show_seconds(*at, self.zone.as_ref().unwrap_or(&TimeZone::UTC))
89    }
90
91    /// As [`Self::time`], for a narrow column, in lines: the date, the UTC time, the local
92    /// time in brackets (shown by a cell with `white-space: pre-line`; non-breaking spaces
93    /// keep each line whole).
94    #[must_use]
95    pub fn narrow_time(&self, at: &Timestamp) -> String {
96        let text = self.time(at);
97        let (utc, local) = text.split_once(" (").unwrap_or((&text, ""));
98        let (date, clock) = utc.split_once(' ').unwrap_or((utc, ""));
99        let keep = |part: &str| part.replace(' ', "\u{a0}");
100        let mut lines = vec![date.to_owned(), keep(clock)];
101        if !local.is_empty() {
102            lines.push(format!("({}", keep(local)));
103        }
104        lines.join("\n")
105    }
106}
107
108/// `X-Forwarded-Prefix` when it is a plain path (`/` and letters, digits, `-`, `_`, `.`,
109/// `~`; no `..`), without its trailing slash; else `""`. Anything else is ignored rather than
110/// put into links.
111#[must_use]
112pub fn prefix(headers: &HeaderMap) -> String {
113    let Some(value) = headers.get(PREFIX_HEADER).and_then(|v| v.to_str().ok()) else {
114        return String::new();
115    };
116    let plain = value.starts_with('/')
117        && !value.contains("..")
118        && !value.contains("//")
119        && value
120            .bytes()
121            .all(|b| b.is_ascii_alphanumeric() || b"/-_.~".contains(&b));
122    if plain {
123        value.trim_end_matches('/').to_owned()
124    } else {
125        String::new()
126    }
127}
128
129/// The cookie remembering which deployment's DAGs the DAGs page shows (M5.1l): a deployment's
130/// name, or empty for all.
131pub const DAGS_VIEW_COOKIE: &str = "schedr_dags_view";
132
133/// The cookie remembering which DAGs by their trigger the DAGs page shows: `active`, `paused`,
134/// or empty for all.
135pub const DAGS_TRIGGER_COOKIE: &str = "schedr_dags_trigger";
136
137/// Cookie `name`'s value, `%XX` escapes decoded; `None` without it or when it doesn't decode.
138#[must_use]
139pub fn cookie(headers: &HeaderMap, name: &str) -> Option<String> {
140    headers
141        .get_all(axum::http::header::COOKIE)
142        .iter()
143        .filter_map(|v| v.to_str().ok())
144        .flat_map(|cookies| cookies.split(';'))
145        .filter_map(|cookie| cookie.trim().strip_prefix(name)?.strip_prefix('='))
146        .find_map(percent_decoded)
147}
148
149/// The time zone in the `schedr_tz` cookie, when it names one jiff knows.
150#[must_use]
151pub fn zone(headers: &HeaderMap) -> Option<TimeZone> {
152    headers
153        .get_all(axum::http::header::COOKIE)
154        .iter()
155        .filter_map(|v| v.to_str().ok())
156        .flat_map(|cookies| cookies.split(';'))
157        .filter_map(|cookie| cookie.trim().strip_prefix(ZONE_COOKIE)?.strip_prefix('='))
158        .find_map(|name| TimeZone::get(&percent_decoded(name)?).ok())
159}
160
161/// `text` with its `%XX` escapes decoded (as `encodeURIComponent` writes them); `None` for a
162/// malformed escape or bytes that aren't UTF-8.
163pub(crate) fn percent_decoded(text: &str) -> Option<String> {
164    let bytes = text.as_bytes();
165    let mut out = Vec::with_capacity(bytes.len());
166    let mut i = 0;
167    while i < bytes.len() {
168        if bytes[i] == b'%' {
169            let hex = std::str::from_utf8(bytes.get(i + 1..i + 3)?).ok()?;
170            out.push(u8::from_str_radix(hex, 16).ok()?);
171            i += 3;
172        } else {
173            out.push(bytes[i]);
174            i += 1;
175        }
176    }
177    String::from_utf8(out).ok()
178}