Skip to main content

geolith_tiles_builder/raster/
fetch.rs

1//! Polite HTTP tile fetching with retry and backoff.
2
3use std::thread::sleep;
4use std::time::Duration;
5
6use geolith::error::{GeolithError, Result};
7
8/// Outcome of one tile request.
9#[non_exhaustive]
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub enum FetchOutcome {
12    /// The tile exists; payload bytes attached.
13    Tile(Vec<u8>),
14    /// The upstream has no tile at this coordinate (HTTP 404 / 204).
15    Missing,
16}
17
18/// A tile HTTP client. Trait-shaped so tests can stub responses.
19pub trait TileFetcher: Sync {
20    /// Fetch one URL.
21    ///
22    /// # Errors
23    ///
24    /// Returns an error for network failures and non-2xx/404 statuses.
25    fn fetch(&self, url: &str) -> Result<FetchOutcome>;
26}
27
28/// `ureq`-backed fetcher used by the CLI.
29#[derive(Debug)]
30pub struct HttpFetcher {
31    agent: ureq::Agent,
32}
33
34impl HttpFetcher {
35    /// Build a fetcher with connect/read timeouts suited to tile servers.
36    #[must_use]
37    pub fn new() -> Self {
38        // Browser-like UA: some tile endpoints (e.g. ArcGIS World_Imagery)
39        // serve a generic UA differently or gate it entirely.
40        const UA: &str = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/151.0.0.0 Safari/537.36";
41        let agent = ureq::Agent::config_builder()
42            .timeout_global(Some(Duration::from_secs(30)))
43            .user_agent(UA)
44            .build()
45            .into();
46        Self { agent }
47    }
48}
49
50impl Default for HttpFetcher {
51    fn default() -> Self {
52        Self::new()
53    }
54}
55
56impl TileFetcher for HttpFetcher {
57    fn fetch(&self, url: &str) -> Result<FetchOutcome> {
58        match self.agent.get(url).call() {
59            Ok(mut response) => {
60                if response.status() == 204 {
61                    return Ok(FetchOutcome::Missing);
62                }
63                let bytes = response
64                    .body_mut()
65                    .with_config()
66                    .limit(64 * 1024 * 1024)
67                    .read_to_vec()
68                    .map_err(|e| {
69                        GeolithError::RasterSource(format!("reading body of {url}: {e}"))
70                    })?;
71                Ok(FetchOutcome::Tile(bytes))
72            }
73            Err(ureq::Error::StatusCode(404)) => Ok(FetchOutcome::Missing),
74            Err(e) => Err(GeolithError::RasterSource(format!("GET {url}: {e}"))),
75        }
76    }
77}
78
79/// Retry `fetcher` up to `attempts` times with exponential backoff.
80///
81/// # Errors
82///
83/// Returns the final error once every attempt has failed.
84pub fn fetch_with_retry(
85    fetcher: &dyn TileFetcher,
86    url: &str,
87    attempts: u32,
88) -> Result<FetchOutcome> {
89    let attempts = attempts.max(1);
90    let mut delay = Duration::from_millis(500);
91    let mut attempt = 1;
92    loop {
93        match fetcher.fetch(url) {
94            Ok(outcome) => return Ok(outcome),
95            Err(e) if attempt >= attempts => return Err(e),
96            Err(_) => {}
97        }
98        sleep(delay);
99        delay = delay.saturating_mul(2).min(Duration::from_secs(16));
100        attempt += 1;
101    }
102}
103
104#[cfg(test)]
105mod tests {
106    use std::sync::Mutex;
107
108    use super::*;
109
110    struct FlakyFetcher {
111        failures_before_success: Mutex<u32>,
112        calls: Mutex<u32>,
113    }
114
115    impl TileFetcher for FlakyFetcher {
116        fn fetch(&self, _url: &str) -> Result<FetchOutcome> {
117            *self.calls.lock().expect("lock") += 1;
118            let mut remaining = self.failures_before_success.lock().expect("lock");
119            if *remaining > 0 {
120                *remaining -= 1;
121                return Err(GeolithError::RasterSource("transient".into()));
122            }
123            Ok(FetchOutcome::Tile(vec![1, 2, 3]))
124        }
125    }
126
127    #[test]
128    fn retries_transient_failures_until_success() {
129        let fetcher = FlakyFetcher {
130            failures_before_success: Mutex::new(2),
131            calls: Mutex::new(0),
132        };
133        let outcome = fetch_with_retry(&fetcher, "https://t.example/1/2/3", 5).expect("succeeds");
134        assert_eq!(outcome, FetchOutcome::Tile(vec![1, 2, 3]));
135        assert_eq!(*fetcher.calls.lock().expect("lock"), 3);
136    }
137
138    #[test]
139    fn surfaces_the_error_after_exhausting_attempts() {
140        let fetcher = FlakyFetcher {
141            failures_before_success: Mutex::new(10),
142            calls: Mutex::new(0),
143        };
144        let err = fetch_with_retry(&fetcher, "https://t.example/1/2/3", 2).expect_err("fails");
145        assert!(format!("{err}").contains("transient"));
146        assert_eq!(*fetcher.calls.lock().expect("lock"), 2);
147    }
148
149    struct MissingFetcher;
150
151    impl TileFetcher for MissingFetcher {
152        fn fetch(&self, _url: &str) -> Result<FetchOutcome> {
153            Ok(FetchOutcome::Missing)
154        }
155    }
156
157    #[test]
158    fn missing_is_not_retried_as_an_error() {
159        let outcome = fetch_with_retry(&MissingFetcher, "https://t.example/9/9/9", 3)
160            .expect("missing is a clean outcome");
161        assert_eq!(outcome, FetchOutcome::Missing);
162    }
163}