Skip to main content

mln_engine/storage/
http_header_transform.rs

1//! Headers a host adds to the HTTP requests of the online file source, for
2//! the C API's `mln_runtime_set_http_header_transform`.
3
4use std::sync::Arc;
5
6use crate::storage::resource::Kind;
7
8/// Header names and values, in the order they are sent.
9pub type HttpHeaders = Vec<(String, String)>;
10
11/// Returns the headers for a request of `kind` to `url`. It runs on the
12/// thread that starts the request, which waits for it, hence `Send + Sync`.
13pub(crate) type HttpHeaderCallback = Arc<dyn Fn(Kind, &str) -> HttpHeaders + Send + Sync>;
14
15/// The headers to add to each HTTP request: the callback gets the resource's
16/// kind and the URL the request goes to, after any resource transform, and
17/// runs again for every attempt of the request (retries and revalidations).
18/// Only `http` and `https` URLs reach it.
19///
20/// The names are HTTP field names that neither the file source nor a
21/// transport manages (not `Range`, `If-None-Match`, `If-Modified-Since`,
22/// `User-Agent`, `Accept-Encoding`, `Host`, `Connection`, `Content-Length`,
23/// `Transfer-Encoding`, ...), and the values are field values. An `Accept`
24/// replaces the one the file source sends for tiles and images. A redirect
25/// to another origin drops these headers.
26#[derive(Clone, Default)]
27pub struct HttpHeaderTransform {
28    callback: Option<HttpHeaderCallback>,
29}
30
31impl HttpHeaderTransform {
32    /// Adds the headers `callback` returns; `None` adds none.
33    #[must_use]
34    pub fn new(callback: Option<HttpHeaderCallback>) -> Self {
35        HttpHeaderTransform { callback }
36    }
37
38    /// The headers for a request of `kind` to `url`: none for a URL that
39    /// isn't `http` or `https`.
40    #[must_use]
41    pub(crate) fn headers(&self, kind: Kind, url: &str) -> HttpHeaders {
42        match &self.callback {
43            Some(callback) if is_http_url(url) => callback(kind, url),
44            _ => HttpHeaders::new(),
45        }
46    }
47}
48
49/// Whether `url`'s scheme is `http` or `https`, in any letter case.
50fn is_http_url(url: &str) -> bool {
51    url.split_once(':')
52        .is_some_and(|(scheme, _)| scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https"))
53}
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58
59    #[test]
60    fn only_http_urls_get_headers() {
61        let transform =
62            HttpHeaderTransform::new(Some(Arc::new(|_, _| vec![("X-Token".to_owned(), "secret".to_owned())])));
63        assert_eq!(1, transform.headers(Kind::Style, "http://example.test/style.json").len());
64        assert_eq!(1, transform.headers(Kind::Style, "HTTPS://example.test/style.json").len());
65        assert_eq!(transform.headers(Kind::Style, "file:///style.json"), HttpHeaders::new());
66        assert_eq!(transform.headers(Kind::Style, "mbtiles:///tiles.mbtiles"), HttpHeaders::new());
67        assert_eq!(transform.headers(Kind::Style, "httpx://example.test"), HttpHeaders::new());
68        assert_eq!(HttpHeaderTransform::default().headers(Kind::Style, "http://example.test"), HttpHeaders::new());
69    }
70}