Skip to main content

serenade_http/
http_cache.rs

1//! HTTP response cache headers and conditional GET (304).
2//!
3//! This is **wire** caching (`Cache-Control`, `ETag`, …), not the `serenade-cache`
4//! item pool. Apps use both: pools for application data, these helpers for
5//! browser/proxy freshness.
6
7use crate::{Method, Request, Response};
8
9/// Cache-related headers to apply on a [`Response`].
10#[derive(Clone, Debug, Default, Eq, PartialEq)]
11pub struct HttpCacheHeaders {
12    cache_control: Option<String>,
13    etag: Option<String>,
14    last_modified: Option<String>,
15    vary: Option<String>,
16}
17
18impl HttpCacheHeaders {
19    /// Empty policy (no headers until builders set them).
20    #[must_use]
21    pub fn new() -> Self {
22        Self::default()
23    }
24
25    /// `Cache-Control: public, max-age={seconds}`.
26    #[must_use]
27    pub fn public_max_age(seconds: u64) -> Self {
28        Self::new().with_cache_control(format!("public, max-age={seconds}"))
29    }
30
31    /// `Cache-Control: private, max-age={seconds}`.
32    #[must_use]
33    pub fn private_max_age(seconds: u64) -> Self {
34        Self::new().with_cache_control(format!("private, max-age={seconds}"))
35    }
36
37    /// `Cache-Control: no-store`.
38    #[must_use]
39    pub fn no_store() -> Self {
40        Self::new().with_cache_control("no-store")
41    }
42
43    /// Sets `Cache-Control` to an arbitrary value.
44    #[must_use]
45    pub fn with_cache_control(mut self, value: impl Into<String>) -> Self {
46        self.cache_control = Some(value.into());
47        self
48    }
49
50    /// Sets `ETag`. Pass an already-quoted value, or use [`etag`] / [`weak_etag`].
51    #[must_use]
52    pub fn with_etag(mut self, value: impl Into<String>) -> Self {
53        self.etag = Some(value.into());
54        self
55    }
56
57    /// Sets `Last-Modified` (HTTP-date string as produced by the app).
58    #[must_use]
59    pub fn with_last_modified(mut self, value: impl Into<String>) -> Self {
60        self.last_modified = Some(value.into());
61        self
62    }
63
64    /// Sets `Vary` (for example `Accept-Encoding`).
65    #[must_use]
66    pub fn with_vary(mut self, value: impl Into<String>) -> Self {
67        self.vary = Some(value.into());
68        self
69    }
70
71    /// Applies configured headers onto `response`.
72    #[must_use]
73    pub fn apply(self, mut response: Response) -> Response {
74        if let Some(value) = self.cache_control {
75            response = response.with_header("cache-control", value);
76        }
77        if let Some(value) = self.etag {
78            response = response.with_header("etag", value);
79        }
80        if let Some(value) = self.last_modified {
81            response = response.with_header("last-modified", value);
82        }
83        if let Some(value) = self.vary {
84            response = response.with_header("vary", value);
85        }
86        response
87    }
88}
89
90/// Strong `ETag`: `"tag"` (quotes added when missing).
91#[must_use]
92pub fn etag(tag: &str) -> String {
93    quote_etag(tag, false)
94}
95
96/// Weak `ETag`: `W/"tag"`.
97#[must_use]
98pub fn weak_etag(tag: &str) -> String {
99    quote_etag(tag, true)
100}
101
102fn quote_etag(tag: &str, weak: bool) -> String {
103    let inner = tag.trim();
104    let quoted = if inner.starts_with('"') && inner.ends_with('"') && inner.len() >= 2 {
105        inner.to_owned()
106    } else {
107        format!("\"{inner}\"")
108    };
109    if weak { format!("W/{quoted}") } else { quoted }
110}
111
112/// Returns a **304 Not Modified** when `request` is a conditional GET/HEAD that
113/// matches validators on `response`; otherwise returns `response` unchanged.
114///
115/// Precedence: `If-None-Match` (vs `ETag`) wins over `If-Modified-Since`
116/// (vs `Last-Modified`) when both are present.
117#[must_use]
118pub fn maybe_not_modified(request: &Request, response: Response) -> Response {
119    if !matches!(request.method(), Method::Get | Method::Head) {
120        return response;
121    }
122    if !validators_match(request, &response) {
123        return response;
124    }
125    not_modified_from(&response)
126}
127
128fn validators_match(request: &Request, response: &Response) -> bool {
129    if let Some(inm) = request.headers().get("if-none-match") {
130        let Some(etag) = response.headers().get("etag") else {
131            return false;
132        };
133        return etag_matches(inm, etag);
134    }
135    if let Some(ims) = request.headers().get("if-modified-since") {
136        let Some(last_modified) = response.headers().get("last-modified") else {
137            return false;
138        };
139        return ims.trim().eq_ignore_ascii_case(last_modified.trim());
140    }
141    false
142}
143
144fn etag_matches(if_none_match: &str, response_etag: &str) -> bool {
145    let response_norm = normalize_etag(response_etag);
146    for part in if_none_match.split(',') {
147        let candidate = part.trim();
148        if candidate.is_empty() {
149            continue;
150        }
151        if candidate == "*" {
152            return true;
153        }
154        if normalize_etag(candidate) == response_norm {
155            return true;
156        }
157    }
158    false
159}
160
161fn normalize_etag(value: &str) -> String {
162    let trimmed = value.trim();
163    let without_weak = trimmed
164        .strip_prefix("W/")
165        .or_else(|| trimmed.strip_prefix("w/"))
166        .unwrap_or(trimmed)
167        .trim();
168    without_weak.to_owned()
169}
170
171fn not_modified_from(response: &Response) -> Response {
172    let mut out = Response::new(304);
173    for name in ["cache-control", "etag", "last-modified", "vary", "expires"] {
174        if let Some(value) = response.headers().get(name) {
175            out = out.with_header(name, value.to_owned());
176        }
177    }
178    out
179}
180
181#[cfg(test)]
182mod tests {
183    use super::{
184        HttpCacheHeaders, etag, etag_matches, maybe_not_modified, normalize_etag, weak_etag,
185    };
186    use crate::{Method, Request, Response};
187
188    #[test]
189    fn builders_set_headers() {
190        let response = HttpCacheHeaders::public_max_age(60)
191            .with_etag(etag("v1"))
192            .with_last_modified("Wed, 21 Oct 2015 07:28:00 GMT")
193            .with_vary("Accept-Encoding")
194            .apply(Response::text(200, "body"));
195        assert_eq!(
196            response.headers().get("cache-control"),
197            Some("public, max-age=60")
198        );
199        assert_eq!(response.headers().get("etag"), Some("\"v1\""));
200        assert_eq!(
201            response.headers().get("last-modified"),
202            Some("Wed, 21 Oct 2015 07:28:00 GMT")
203        );
204        assert_eq!(response.headers().get("vary"), Some("Accept-Encoding"));
205
206        let private = HttpCacheHeaders::private_max_age(10).apply(Response::new(200));
207        assert_eq!(
208            private.headers().get("cache-control"),
209            Some("private, max-age=10")
210        );
211        let no_store = HttpCacheHeaders::no_store().apply(Response::new(200));
212        assert_eq!(no_store.headers().get("cache-control"), Some("no-store"));
213    }
214
215    #[test]
216    fn etag_helpers_quote_and_weak() {
217        assert_eq!(etag("abc"), "\"abc\"");
218        assert_eq!(etag("\"abc\""), "\"abc\"");
219        assert_eq!(weak_etag("abc"), "W/\"abc\"");
220        assert_eq!(normalize_etag("W/\"x\""), "\"x\"");
221        assert!(etag_matches("W/\"x\", \"y\"", "\"x\""));
222        assert!(etag_matches("*", "\"anything\""));
223        assert!(!etag_matches("\"a\"", "\"b\""));
224    }
225
226    #[test]
227    fn maybe_not_modified_on_etag() {
228        let response = HttpCacheHeaders::public_max_age(30)
229            .with_etag(etag("1"))
230            .apply(Response::text(200, "payload"));
231        let request = Request::new(Method::Get, "/x").with_header("If-None-Match", "\"1\"");
232        let not_mod = maybe_not_modified(&request, response.clone());
233        assert_eq!(not_mod.status(), 304);
234        assert_eq!(not_mod.body(), &[] as &[u8]);
235        assert_eq!(not_mod.headers().get("etag"), Some("\"1\""));
236        assert_eq!(
237            not_mod.headers().get("cache-control"),
238            Some("public, max-age=30")
239        );
240
241        let miss = Request::new(Method::Get, "/x").with_header("If-None-Match", "\"2\"");
242        assert_eq!(maybe_not_modified(&miss, response).status(), 200);
243    }
244
245    #[test]
246    fn maybe_not_modified_on_last_modified() {
247        let lm = "Wed, 21 Oct 2015 07:28:00 GMT";
248        let response = HttpCacheHeaders::new()
249            .with_last_modified(lm)
250            .apply(Response::text(200, "x"));
251        let request = Request::new(Method::Head, "/").with_header("If-Modified-Since", lm);
252        assert_eq!(maybe_not_modified(&request, response.clone()).status(), 304);
253
254        let post = Request::new(Method::Post, "/").with_header("If-Modified-Since", lm);
255        assert_eq!(maybe_not_modified(&post, response).status(), 200);
256    }
257
258    #[test]
259    fn if_none_match_wins_over_if_modified_since() {
260        let response = HttpCacheHeaders::new()
261            .with_etag(etag("a"))
262            .with_last_modified("Wed, 21 Oct 2015 07:28:00 GMT")
263            .apply(Response::text(200, "x"));
264        let request = Request::new(Method::Get, "/")
265            .with_header("If-None-Match", "\"b\"")
266            .with_header("If-Modified-Since", "Wed, 21 Oct 2015 07:28:00 GMT");
267        // ETag mismatch → 200 even though Last-Modified matches.
268        assert_eq!(maybe_not_modified(&request, response).status(), 200);
269    }
270
271    #[test]
272    fn custom_cache_control() {
273        let response = HttpCacheHeaders::new()
274            .with_cache_control("max-age=0, must-revalidate")
275            .apply(Response::new(204));
276        assert_eq!(
277            response.headers().get("cache-control"),
278            Some("max-age=0, must-revalidate")
279        );
280    }
281
282    #[test]
283    fn conditional_misses_without_validators_or_headers() {
284        let bare = Response::text(200, "x");
285        let with_inm = Request::new(Method::Get, "/").with_header("If-None-Match", "\"a\"");
286        assert_eq!(maybe_not_modified(&with_inm, bare.clone()).status(), 200);
287
288        let with_ims = Request::new(Method::Get, "/")
289            .with_header("If-Modified-Since", "Wed, 21 Oct 2015 07:28:00 GMT");
290        assert_eq!(maybe_not_modified(&with_ims, bare.clone()).status(), 200);
291
292        let plain = Request::new(Method::Get, "/");
293        assert_eq!(maybe_not_modified(&plain, bare).status(), 200);
294
295        assert!(etag_matches(" , \"a\" , ", "\"a\""));
296    }
297}