1use crate::storage::chrono::{Timestamp, now, parse_http_date, parse_timestamp_i32};
5
6#[derive(Clone, Debug, Default, PartialEq, Eq)]
9pub struct CacheControl {
10 pub max_age: Option<u64>,
11 pub must_revalidate: bool,
12 pub no_cache: bool,
15 pub no_store: bool,
16}
17
18const MAX_DELTA_SECONDS: u64 = 1 << 31;
20
21fn delta_seconds(value: &str) -> Option<u64> {
23 if value.is_empty() || !value.bytes().all(|b| b.is_ascii_digit()) {
24 return None;
25 }
26 Some(value.parse::<u64>().map_or(MAX_DELTA_SECONDS, |seconds| seconds.min(MAX_DELTA_SECONDS)))
27}
28
29fn list_elements(value: &str) -> Vec<&str> {
32 let mut elements = Vec::new();
33 let (mut start, mut quoted, mut escaped) = (0, false, false);
34 for (index, byte) in value.bytes().enumerate() {
35 match byte {
36 _ if escaped => escaped = false,
37 b'\\' if quoted => escaped = true,
38 b'"' => quoted = !quoted,
39 b',' if !quoted => {
40 elements.push(&value[start..index]);
41 start = index + 1;
42 }
43 _ => {}
44 }
45 }
46 elements.push(&value[start..]);
47 elements
48}
49
50fn unquote(value: &str) -> String {
52 match value.strip_prefix('"').and_then(|rest| rest.strip_suffix('"')) {
53 Some(inner) => {
54 let mut unquoted = String::with_capacity(inner.len());
55 let mut chars = inner.chars();
56 while let Some(c) = chars.next() {
57 unquoted.push(if c == '\\' { chars.next().unwrap_or(c) } else { c });
58 }
59 unquoted
60 }
61 None => value.to_owned(),
62 }
63}
64
65impl CacheControl {
66 #[must_use]
73 pub fn parse(value: &str) -> CacheControl {
74 let mut result = CacheControl::default();
75 for element in list_elements(value) {
76 let (name, argument) = match element.split_once('=') {
77 Some((name, argument)) => (name.trim(), Some(unquote(argument.trim()))),
78 None => (element.trim(), None),
79 };
80 let seconds = || argument.as_deref().and_then(delta_seconds);
81 match name.to_ascii_lowercase().as_str() {
82 "max-age" => result.max_age = result.max_age.or_else(seconds),
83 "must-revalidate" => result.must_revalidate = true,
84 "no-cache" if argument.is_none() => result.no_cache = true,
85 "no-store" => result.no_store = true,
86 _ => {}
87 }
88 }
89 result
90 }
91}
92
93const MAX_HEURISTIC_LIFETIME: u64 = 7 * 24 * 60 * 60;
96
97#[derive(Clone, Debug)]
99pub struct CachingHeaders<'a> {
100 pub cache_control: &'a CacheControl,
101 pub expires: Option<&'a str>,
103 pub date: Option<Timestamp>,
104 pub age: Option<u64>,
106 pub last_modified: Option<Timestamp>,
110}
111
112#[derive(Clone, Copy, Debug, PartialEq, Eq)]
114pub struct Freshness {
115 pub expires: Timestamp,
117 pub must_revalidate: bool,
120 pub no_store: bool,
121}
122
123impl CachingHeaders<'_> {
124 #[must_use]
132 pub fn freshness(&self, received: Timestamp) -> Freshness {
133 let cc = self.cache_control;
134 let origin = self.date.unwrap_or(received);
135 let lifetime = if cc.no_cache {
136 0
137 } else if let Some(max_age) = cc.max_age {
138 max_age
139 } else if let Some(expires) = self.expires {
140 let expires = parse_http_date(expires).unwrap_or_default();
141 u64::try_from(expires.secs_since_epoch() - origin.secs_since_epoch()).unwrap_or(0)
142 } else if let Some(modified) = self.last_modified {
143 (u64::try_from(origin.secs_since_epoch() - modified.secs_since_epoch()).unwrap_or(0) / 10)
144 .min(MAX_HEURISTIC_LIFETIME)
145 } else {
146 0
147 };
148 let remaining = lifetime as i64 - self.age.unwrap_or(0).min(MAX_DELTA_SECONDS) as i64;
149 Freshness {
150 expires: Timestamp::from_secs(received.secs_since_epoch() + remaining),
151 must_revalidate: cc.must_revalidate || cc.no_cache,
152 no_store: cc.no_store,
153 }
154 }
155}
156
157fn stoi(s: &str) -> Option<i32> {
160 let t = s.trim_start_matches([' ', '\t', '\n', '\r', '\x0b', '\x0c']);
161 let (negative, digits) = match t.as_bytes().first() {
162 Some(b'-') => (true, &t[1..]),
163 Some(b'+') => (false, &t[1..]),
164 _ => (false, t),
165 };
166 let len = digits.bytes().take_while(u8::is_ascii_digit).count();
167 if len == 0 {
168 return None;
169 }
170 let magnitude: i64 = digits[..len].parse().ok()?;
171 let value = if negative { -magnitude } else { magnitude };
172 i32::try_from(value).ok()
173}
174
175pub fn parse_retry_headers(retry_after: &Option<String>, x_rate_limit_reset: &Option<String>) -> Option<Timestamp> {
179 if let Some(retry_after) = retry_after {
180 match stoi(retry_after) {
181 Some(secs) => Some(Timestamp::from_secs(now().secs_since_epoch() + i64::from(secs))),
182 None => parse_http_date(retry_after),
183 }
184 } else if let Some(x_rate_limit_reset) = x_rate_limit_reset {
185 stoi(x_rate_limit_reset).map(parse_timestamp_i32)
186 } else {
187 None
188 }
189}
190
191#[cfg(test)]
192mod tests {
193 use super::*;
194
195 #[test]
196 fn parsing() {
197 let cases: &[(&str, Option<u64>, bool)] = &[
198 ("", None, false),
199 ("max-age=34", Some(34), false),
200 ("max-age =34", Some(34), false),
201 (",max-age=1", Some(1), false),
202 ("MAX-AGE=5", Some(5), false),
203 ("max-age=\"7\"", Some(7), false),
204 ("max-age=-1", None, false),
205 ("max-age=foo", None, false),
206 ("max-age=99999999999999999999", Some(MAX_DELTA_SECONDS), false),
207 ("max-age=3, max-age=4", Some(3), false),
208 ("foo=\"max-age=3, bar\", max-age=4", Some(4), false),
209 ("max-age-x=3", None, false),
210 ("private, max-age=0, no-cache", Some(0), false),
211 ("max-age=3600, must-revalidate", Some(3600), true),
212 ("no-cache=\"Expires,Via\",max-age=3600, must-revalidate", Some(3600), true),
213 ];
214 for &(value, max_age, must_revalidate) in cases {
215 let cc = CacheControl::parse(value);
216 assert_eq!(cc.max_age, max_age, "{value}");
217 assert_eq!(cc.must_revalidate, must_revalidate, "{value}");
218 }
219 }
220
221 #[test]
222 fn directives() {
223 let cc = CacheControl::parse("public,max-age=300,stale-if-error=86400, No-Store");
224 assert_eq!(cc.max_age, Some(300));
225 assert!(cc.no_store && !cc.no_cache);
226 assert!(CacheControl::parse("no-cache").no_cache);
227 assert!(!CacheControl::parse("no-cache=\"Set-Cookie\"").no_cache);
228 }
229
230 fn freshness(
231 cache_control: &str,
232 expires: Option<&str>,
233 date: Option<i64>,
234 age: Option<u64>,
235 modified: Option<i64>,
236 ) -> Freshness {
237 let cc = CacheControl::parse(cache_control);
238 let headers = CachingHeaders {
239 cache_control: &cc,
240 expires,
241 date: date.map(Timestamp::from_secs),
242 age,
243 last_modified: modified.map(Timestamp::from_secs),
244 };
245 headers.freshness(Timestamp::from_secs(RECEIVED))
246 }
247
248 const RECEIVED: i64 = 100_000_000;
249
250 fn at(offset: i64) -> Timestamp {
251 Timestamp::from_secs(RECEIVED + offset)
252 }
253
254 #[test]
255 fn max_age_counts_from_the_age_and_wins_over_expires() {
256 let f = freshness(
258 "max-age=88823, stale-while-revalidate=604800, stale-if-error=604800",
259 Some("Thu, 01 Jan 1970 00:00:00 GMT"),
260 None,
261 Some(67981),
262 None,
263 );
264 assert_eq!(f.expires, at(88823 - 67981));
265 assert!(!f.must_revalidate);
266 }
267
268 #[test]
269 fn expires_counts_from_the_date() {
270 let server_now = RECEIVED + 3600;
272 let expires = crate::storage::chrono::rfc1123(Timestamp::from_secs(server_now + 600));
273 let f = freshness("public", Some(&expires), Some(server_now), Some(30), None);
274 assert_eq!(f.expires, at(570));
275 let f = freshness("", Some(&expires), None, None, None);
277 assert_eq!(f.expires, Timestamp::from_secs(server_now + 600));
278 assert_eq!(freshness("", Some("0"), None, None, None).expires, at(0));
280 }
281
282 #[test]
283 fn without_a_lifetime_a_heuristic_or_none() {
284 let f = freshness("", None, None, None, Some(RECEIVED - 1000));
285 assert_eq!(f.expires, at(100));
286 let f = freshness("", None, Some(RECEIVED + 1000), None, Some(RECEIVED - 1000));
288 assert_eq!(f.expires, at(200));
289 let f = freshness("", None, None, None, Some(0));
290 assert_eq!(f.expires, at(MAX_HEURISTIC_LIFETIME as i64));
291 assert_eq!(freshness("public", None, None, None, None).expires, at(0));
292 }
293
294 #[test]
295 fn no_cache_is_stale_at_once_and_must_revalidate() {
296 let f = freshness("no-cache, max-age=600", None, None, None, Some(0));
297 assert_eq!(f.expires, at(0));
298 assert!(f.must_revalidate);
299 }
300}