Skip to main content

verctl_core/
http_date.rs

1//! The HTTP date a registry gives for a retry.
2//!
3//! crates.io names the time of its next new-crate slot as an IMF-fixdate.
4//! It appears in cargo's "try again after" message and in a `Retry-After`
5//! header, which may also contain a count of seconds ([RFC 9110 section
6//! 10.2.3]). [`wait`] reads both. The parser handles only the fixed form [RFC
7//! 9110 section 5.6.7] defines, such as `Fri, 13 Nov 2026 15:10:00 GMT`, so no
8//! date crate is needed.
9//!
10//! [RFC 9110 section 10.2.3]: https://www.rfc-editor.org/rfc/rfc9110#section-10.2.3
11//! [RFC 9110 section 5.6.7]: https://www.rfc-editor.org/rfc/rfc9110#section-5.6.7
12
13use std::time::{Duration, SystemTime, UNIX_EPOCH};
14
15/// The day names, Monday first, as the IMF-fixdate spells them.
16const WEEKDAYS: [&str; 7] = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
17
18/// The month names, January first, as the IMF-fixdate spells them.
19const MONTHS: [&str; 12] = [
20    "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
21];
22
23/// 1970-01-01, the epoch, fell on a Thursday: index 3 of [`WEEKDAYS`].
24const EPOCH_WEEKDAY: i64 = 3;
25
26/// How long to wait for `value`: a count of seconds, or an IMF-fixdate. A
27/// date already past is no wait. `None` when `value` is neither.
28#[must_use]
29pub fn wait(value: &str) -> Option<Duration> {
30    let value = value.trim();
31    if let Ok(seconds) = value.parse::<u64>() {
32        return Some(Duration::from_secs(seconds));
33    }
34    let when = parse(value)?;
35    Some(when.duration_since(SystemTime::now()).unwrap_or_default())
36}
37
38/// The instant an IMF-fixdate names, or `None` when `text` is not one: the
39/// weekday must name the date, the month must be a month, and the zone must
40/// be `GMT`.
41#[must_use]
42pub fn parse(text: &str) -> Option<SystemTime> {
43    let mut parts = text.split(' ');
44    let weekday = parts.next()?.strip_suffix(',')?;
45    let day = digits(parts.next()?, 2)?;
46    let month = parts.next()?;
47    let year = digits(parts.next()?, 4)?;
48    let clock = parts.next()?;
49    let zone = parts.next()?;
50    if parts.next().is_some() || zone != "GMT" {
51        return None;
52    }
53    let weekday = WEEKDAYS
54        .iter()
55        .zip(0_i64..)
56        .find_map(|(name, index)| (*name == weekday).then_some(index))?;
57    let month = MONTHS
58        .iter()
59        .zip(1_i64..)
60        .find_map(|(name, index)| (*name == month).then_some(index))?;
61    if !(1..=days_in_month(year, month)).contains(&day) {
62        return None;
63    }
64    let mut clock = clock.split(':');
65    let hour = digits(clock.next()?, 2).filter(|hour| *hour < 24)?;
66    let minute = digits(clock.next()?, 2).filter(|minute| *minute < 60)?;
67    let second = digits(clock.next()?, 2).filter(|second| *second < 60)?;
68    if clock.next().is_some() {
69        return None;
70    }
71    let days = days_from_civil(year, month, day);
72    if (days + EPOCH_WEEKDAY).rem_euclid(7) != weekday {
73        return None;
74    }
75    let seconds = days * 86_400 + hour * 3_600 + minute * 60 + second;
76    UNIX_EPOCH.checked_add(Duration::from_secs(u64::try_from(seconds).ok()?))
77}
78
79/// `text` as a number of exactly `width` ASCII digits.
80fn digits(text: &str, width: usize) -> Option<i64> {
81    if text.len() != width || !text.bytes().all(|byte| byte.is_ascii_digit()) {
82        return None;
83    }
84    text.parse().ok()
85}
86
87/// How many days `month` (1 to 12) of `year` has.
88fn days_in_month(year: i64, month: i64) -> i64 {
89    let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
90    match month {
91        2 if leap => 29,
92        2 => 28,
93        4 | 6 | 9 | 11 => 30,
94        _ => 31,
95    }
96}
97
98/// The days from 1970-01-01 to the given date of the proleptic Gregorian
99/// calendar, negative before it. Howard Hinnant's `days_from_civil`
100/// ([chrono-Compatible Low-Level Date Algorithms]), with March as the first
101/// month of the shifted year.
102///
103/// [chrono-Compatible Low-Level Date Algorithms]: https://howardhinnant.github.io/date_algorithms.html#days_from_civil
104fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
105    let year = if month <= 2 { year - 1 } else { year };
106    let era = year.div_euclid(400);
107    let year_of_era = year.rem_euclid(400);
108    let shifted_month = (month + 9) % 12;
109    let day_of_year = (153 * shifted_month + 2) / 5 + day - 1;
110    let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
111    era * 146_097 + day_of_era - 719_468
112}
113
114#[cfg(test)]
115mod tests {
116    use std::time::{Duration, UNIX_EPOCH};
117
118    use super::{parse, wait};
119
120    fn seconds(text: &str) -> Option<u64> {
121        parse(text).map(|when| {
122            when.duration_since(UNIX_EPOCH)
123                .expect("after the epoch")
124                .as_secs()
125        })
126    }
127
128    /// RFC 9110's own example, and a date crates.io gave in 2026.
129    #[test]
130    fn a_known_date_is_its_unix_seconds() {
131        assert_eq!(seconds("Sun, 06 Nov 1994 08:49:37 GMT"), Some(784_111_777));
132        assert_eq!(
133            seconds("Fri, 13 Nov 2026 15:10:00 GMT"),
134            Some(1_794_582_600)
135        );
136    }
137
138    /// A leap day counts, and the epoch is day zero.
139    #[test]
140    fn leap_days_and_the_epoch() {
141        assert_eq!(seconds("Thu, 01 Jan 1970 00:00:00 GMT"), Some(0));
142        assert_eq!(
143            seconds("Thu, 29 Feb 2024 12:00:00 GMT"),
144            Some(1_709_208_000)
145        );
146        assert_eq!(seconds("Thu, 29 Feb 2023 12:00:00 GMT"), None);
147    }
148
149    #[test]
150    fn a_bad_weekday_or_month_is_refused() {
151        assert_eq!(seconds("Fry, 13 Nov 2026 15:10:00 GMT"), None);
152        assert_eq!(seconds("Sat, 13 Nov 2026 15:10:00 GMT"), None);
153        assert_eq!(seconds("Fri, 13 Nob 2026 15:10:00 GMT"), None);
154        assert_eq!(seconds("Fri, 13 November 2026 15:10:00 GMT"), None);
155    }
156
157    #[test]
158    fn a_zone_other_than_gmt_is_refused() {
159        assert_eq!(seconds("Fri, 13 Nov 2026 15:10:00 UTC"), None);
160        assert_eq!(seconds("Fri, 13 Nov 2026 15:10:00 +0000"), None);
161        assert_eq!(seconds("Fri, 13 Nov 2026 15:10:00"), None);
162    }
163
164    #[test]
165    fn another_shape_is_refused() {
166        for text in [
167            "",
168            "Friday, 13-Nov-26 15:10:00 GMT",
169            "Fri Nov 13 15:10:00 2026",
170            "Fri, 13 Nov 2026 25:10:00 GMT",
171            "Fri, 13 Nov 2026 15:10 GMT",
172            "Fri, 13 Nov 2026 15:10:00 GMT extra",
173        ] {
174            assert_eq!(seconds(text), None, "{text:?}");
175        }
176    }
177
178    /// Seconds wait as given, and a date in the past is no wait.
179    #[test]
180    fn a_retry_after_is_seconds_or_a_date() {
181        assert_eq!(wait("0"), Some(Duration::ZERO));
182        assert_eq!(wait(" 30 "), Some(Duration::from_secs(30)));
183        assert!(wait("Fri, 13 Nov 2026 15:10:00 GMT").is_some());
184        assert_eq!(wait("Sun, 06 Nov 1994 08:49:37 GMT"), Some(Duration::ZERO));
185        assert_eq!(wait("soon"), None);
186        assert_eq!(wait("-5"), None);
187    }
188}