geolith-tiles-builder 0.4.2

Builds tiles from OpenStreetMap and Overture Maps: protomaps-schema vector PMTiles, Terrain-RGB, raster archives and 3D Tiles from Gaussian splats
Documentation
//! Polite HTTP tile fetching with retry and backoff.

use std::thread::sleep;
use std::time::Duration;

use geolith::error::{GeolithError, Result};

/// Outcome of one tile request.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FetchOutcome {
    /// The tile exists; payload bytes attached.
    Tile(Vec<u8>),
    /// The upstream has no tile at this coordinate (HTTP 404 / 204).
    Missing,
}

/// A tile HTTP client. Trait-shaped so tests can stub responses.
pub trait TileFetcher: Sync {
    /// Fetch one URL.
    ///
    /// # Errors
    ///
    /// Returns an error for network failures and non-2xx/404 statuses.
    fn fetch(&self, url: &str) -> Result<FetchOutcome>;
}

/// `ureq`-backed fetcher used by the CLI.
#[derive(Debug)]
pub struct HttpFetcher {
    agent: ureq::Agent,
}

impl HttpFetcher {
    /// Build a fetcher with connect/read timeouts suited to tile servers.
    #[must_use]
    pub fn new() -> Self {
        // Browser-like UA: some tile endpoints (e.g. ArcGIS World_Imagery)
        // serve a generic UA differently or gate it entirely.
        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";
        let agent = ureq::Agent::config_builder()
            .timeout_global(Some(Duration::from_secs(30)))
            .user_agent(UA)
            .build()
            .into();
        Self { agent }
    }
}

impl Default for HttpFetcher {
    fn default() -> Self {
        Self::new()
    }
}

impl TileFetcher for HttpFetcher {
    fn fetch(&self, url: &str) -> Result<FetchOutcome> {
        match self.agent.get(url).call() {
            Ok(mut response) => {
                if response.status() == 204 {
                    return Ok(FetchOutcome::Missing);
                }
                let bytes = response
                    .body_mut()
                    .with_config()
                    .limit(64 * 1024 * 1024)
                    .read_to_vec()
                    .map_err(|e| {
                        GeolithError::RasterSource(format!("reading body of {url}: {e}"))
                    })?;
                Ok(FetchOutcome::Tile(bytes))
            }
            Err(ureq::Error::StatusCode(404)) => Ok(FetchOutcome::Missing),
            Err(e) => Err(GeolithError::RasterSource(format!("GET {url}: {e}"))),
        }
    }
}

/// Retry `fetcher` up to `attempts` times with exponential backoff.
///
/// # Errors
///
/// Returns the final error once every attempt has failed.
pub fn fetch_with_retry(
    fetcher: &dyn TileFetcher,
    url: &str,
    attempts: u32,
) -> Result<FetchOutcome> {
    let attempts = attempts.max(1);
    let mut delay = Duration::from_millis(500);
    let mut attempt = 1;
    loop {
        match fetcher.fetch(url) {
            Ok(outcome) => return Ok(outcome),
            Err(e) if attempt >= attempts => return Err(e),
            Err(_) => {}
        }
        sleep(delay);
        delay = delay.saturating_mul(2).min(Duration::from_secs(16));
        attempt += 1;
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Mutex;

    use super::*;

    struct FlakyFetcher {
        failures_before_success: Mutex<u32>,
        calls: Mutex<u32>,
    }

    impl TileFetcher for FlakyFetcher {
        fn fetch(&self, _url: &str) -> Result<FetchOutcome> {
            *self.calls.lock().expect("lock") += 1;
            let mut remaining = self.failures_before_success.lock().expect("lock");
            if *remaining > 0 {
                *remaining -= 1;
                return Err(GeolithError::RasterSource("transient".into()));
            }
            Ok(FetchOutcome::Tile(vec![1, 2, 3]))
        }
    }

    #[test]
    fn retries_transient_failures_until_success() {
        let fetcher = FlakyFetcher {
            failures_before_success: Mutex::new(2),
            calls: Mutex::new(0),
        };
        let outcome = fetch_with_retry(&fetcher, "https://t.example/1/2/3", 5).expect("succeeds");
        assert_eq!(outcome, FetchOutcome::Tile(vec![1, 2, 3]));
        assert_eq!(*fetcher.calls.lock().expect("lock"), 3);
    }

    #[test]
    fn surfaces_the_error_after_exhausting_attempts() {
        let fetcher = FlakyFetcher {
            failures_before_success: Mutex::new(10),
            calls: Mutex::new(0),
        };
        let err = fetch_with_retry(&fetcher, "https://t.example/1/2/3", 2).expect_err("fails");
        assert!(format!("{err}").contains("transient"));
        assert_eq!(*fetcher.calls.lock().expect("lock"), 2);
    }

    struct MissingFetcher;

    impl TileFetcher for MissingFetcher {
        fn fetch(&self, _url: &str) -> Result<FetchOutcome> {
            Ok(FetchOutcome::Missing)
        }
    }

    #[test]
    fn missing_is_not_retried_as_an_error() {
        let outcome = fetch_with_retry(&MissingFetcher, "https://t.example/9/9/9", 3)
            .expect("missing is a clean outcome");
        assert_eq!(outcome, FetchOutcome::Missing);
    }
}