Skip to main content

vertigo_cli/serve/
vary.rs

1use actix_web::{
2    Error,
3    body::MessageBody,
4    dev::{ServiceRequest, ServiceResponse},
5    http::{
6        StatusCode,
7        header::{self, HeaderMap, HeaderValue},
8    },
9    middleware::Next,
10    mime::{self, Mime},
11};
12
13/// Middleware making every response `Compress` would compress for a client accepting it say
14/// `Vary: accept-encoding`, also when sent as it is.
15///
16/// `Compress` says it only on what it compresses. Sending the same response as it is, to a client
17/// without `Accept-Encoding` (a crawler, curl), it says nothing, and a cache on the way (nginx,
18/// a CDN) gives that version to everyone. `vertigo serve` uses it, a back-end with its own
19/// `Compress` wraps it around that one, i.e. after it:
20///
21/// ```no_run
22/// use actix_web::{App, middleware::{Compress, from_fn}};
23/// use vertigo_cli::serve::vary_accept_encoding;
24///
25/// let app = App::new()
26///     .wrap(Compress::default())
27///     .wrap(from_fn(vary_accept_encoding));
28/// ```
29pub async fn vary_accept_encoding(
30    req: ServiceRequest,
31    next: Next<impl MessageBody>,
32) -> Result<ServiceResponse<impl MessageBody>, Error> {
33    let mut res = next.call(req).await?;
34    if compressible(&res) && !varies_on_encoding(res.headers()) {
35        res.headers_mut()
36            .append(header::VARY, HeaderValue::from_static("accept-encoding"));
37    }
38    Ok(res)
39}
40
41/// What `Compress` compresses: a response not encoded already, with content, not an image (but
42/// SVG) or a video. A revalidation (304) or a range (206) of it too, the response they stand for
43/// is compressed.
44fn compressible<B>(res: &ServiceResponse<B>) -> bool {
45    if matches!(
46        res.status(),
47        StatusCode::SWITCHING_PROTOCOLS | StatusCode::NO_CONTENT
48    ) || res.headers().contains_key(header::CONTENT_ENCODING)
49    {
50        return false;
51    }
52    let content_type = res
53        .headers()
54        .get(header::CONTENT_TYPE)
55        .and_then(|value| value.to_str().ok())
56        .and_then(|value| value.parse::<Mime>().ok());
57    match content_type {
58        Some(mime) if mime.type_() == mime::IMAGE => mime.subtype() == mime::SVG,
59        Some(mime) => mime.type_() != mime::VIDEO,
60        None => true,
61    }
62}
63
64/// Already says it, f. ex. the precompressed files or what `Compress` compressed
65fn varies_on_encoding(headers: &HeaderMap) -> bool {
66    headers
67        .get_all(header::VARY)
68        .filter_map(|value| value.to_str().ok())
69        .flat_map(|value| value.split(','))
70        .map(str::trim)
71        .any(|name| name == "*" || name.eq_ignore_ascii_case("accept-encoding"))
72}
73
74#[cfg(test)]
75mod tests {
76    use actix_web::{
77        App, HttpResponse,
78        http::{StatusCode, header},
79        middleware::{Compress, from_fn},
80        test, web,
81    };
82
83    use super::vary_accept_encoding;
84
85    /// `Vary` and `Content-Encoding` of the response to a GET of `uri`
86    async fn get(uri: &str, accept_encoding: Option<&str>) -> (Vec<String>, Option<String>) {
87        let respond = |status: StatusCode, content_type: &'static str| {
88            move || async move {
89                HttpResponse::build(status)
90                    .content_type(content_type)
91                    .body("<p>Some content</p>")
92            }
93        };
94        let app = test::init_service(
95            App::new()
96                .wrap(Compress::default())
97                .wrap(from_fn(vary_accept_encoding))
98                .route("/page", web::get().to(respond(StatusCode::OK, "text/html")))
99                .route(
100                    "/page-revalidated",
101                    web::get().to(|| async {
102                        HttpResponse::NotModified()
103                            .content_type("text/html")
104                            .finish()
105                    }),
106                )
107                .route(
108                    "/page-range",
109                    web::get().to(respond(StatusCode::PARTIAL_CONTENT, "text/html")),
110                )
111                .route(
112                    "/logo.png",
113                    web::get().to(respond(StatusCode::OK, "image/png")),
114                )
115                .route(
116                    "/logo.svg",
117                    web::get().to(respond(StatusCode::OK, "image/svg+xml")),
118                )
119                .route(
120                    "/intro.mp4",
121                    web::get().to(respond(StatusCode::OK, "video/mp4")),
122                )
123                .route(
124                    "/proxied",
125                    web::get().to(|| async {
126                        HttpResponse::Ok()
127                            .content_type("text/html")
128                            .insert_header((header::CONTENT_ENCODING, "gzip"))
129                            .body("gzipped upstream")
130                    }),
131                )
132                .route(
133                    "/per-origin",
134                    web::get().to(|| async {
135                        HttpResponse::Ok()
136                            .content_type("application/json")
137                            .insert_header((header::VARY, "Origin"))
138                            .body("{}")
139                    }),
140                )
141                .route(
142                    "/nothing",
143                    web::get().to(|| async { HttpResponse::NoContent().finish() }),
144                ),
145        )
146        .await;
147
148        let mut req = test::TestRequest::get().uri(uri);
149        if let Some(accept_encoding) = accept_encoding {
150            req = req.insert_header((header::ACCEPT_ENCODING, accept_encoding));
151        }
152        let res = test::call_service(&app, req.to_request()).await;
153        let header = |name| {
154            res.headers()
155                .get_all(name)
156                .map(|value| String::from_utf8_lossy(value.as_bytes()).into_owned())
157                .collect::<Vec<_>>()
158        };
159        (header(header::VARY), header(header::CONTENT_ENCODING).pop())
160    }
161
162    #[actix_web::test]
163    async fn compressed_or_not_the_response_depends_on_accept_encoding() {
164        let vary = |values: &[&str]| values.iter().map(|value| value.to_string()).collect();
165
166        // Sent as it is
167        for accept_encoding in [None, Some("identity"), Some("gzip;q=0")] {
168            assert_eq!(
169                get("/page", accept_encoding).await,
170                (vary(&["accept-encoding"]), None),
171                "{accept_encoding:?}"
172            );
173        }
174        // Compressed, `Compress` says it once
175        assert_eq!(
176            get("/page", Some("gzip")).await,
177            (vary(&["accept-encoding"]), Some("gzip".to_string()))
178        );
179
180        // The revalidation and the range of a compressed response
181        assert_eq!(
182            get("/page-revalidated", None).await,
183            (vary(&["accept-encoding"]), None)
184        );
185        assert_eq!(
186            get("/page-range", Some("gzip")).await,
187            (vary(&["accept-encoding"]), None)
188        );
189
190        assert_eq!(
191            get("/logo.svg", None).await,
192            (vary(&["accept-encoding"]), None)
193        );
194
195        // To the other `Vary`
196        assert_eq!(
197            get("/per-origin", None).await,
198            (vary(&["Origin", "accept-encoding"]), None)
199        );
200        assert_eq!(
201            get("/per-origin", Some("gzip")).await,
202            (
203                vary(&["Origin", "accept-encoding"]),
204                Some("gzip".to_string())
205            )
206        );
207    }
208
209    #[actix_web::test]
210    async fn never_compressed_is_left_as_it_is() {
211        for uri in ["/logo.png", "/intro.mp4", "/nothing"] {
212            for accept_encoding in [None, Some("gzip")] {
213                assert_eq!(
214                    get(uri, accept_encoding).await,
215                    (vec![], None),
216                    "{uri} {accept_encoding:?}"
217                );
218            }
219        }
220        // Encoded by the back-end, which says what it depends on
221        assert_eq!(
222            get("/proxied", Some("gzip")).await,
223            (vec![], Some("gzip".to_string()))
224        );
225    }
226}