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