use std::thread::sleep;
use std::time::Duration;
use geolith::error::{GeolithError, Result};
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FetchOutcome {
Tile(Vec<u8>),
Missing,
}
pub trait TileFetcher: Sync {
fn fetch(&self, url: &str) -> Result<FetchOutcome>;
}
#[derive(Debug)]
pub struct HttpFetcher {
agent: ureq::Agent,
}
impl HttpFetcher {
#[must_use]
pub fn new() -> Self {
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}"))),
}
}
}
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);
}
}