Skip to main content

basemapper_core/
tile_fetcher.rs

1use crate::bbox::mercator_to_tile;
2use crate::error::BasemapError;
3use lru::LruCache;
4use once_cell::sync::Lazy;
5use std::num::NonZeroUsize;
6use std::sync::Mutex;
7use std::time::Duration;
8use tokio::task::JoinSet;
9
10// In-memory LRU cache shared across all render calls in a session.
11// Keyed by fully-expanded tile URL; stores raw response bytes.
12static TILE_CACHE: Lazy<Mutex<LruCache<String, Vec<u8>>>> =
13    Lazy::new(|| Mutex::new(LruCache::new(NonZeroUsize::new(512).unwrap())));
14
15/// A source's tile URL templates (MapLibre's `tiles`) and `scheme`.
16#[derive(Debug, Clone, Default, PartialEq)]
17pub struct TileUrls {
18    /// Templates; tiles are spread over them as MapLibre does.
19    pub templates: Vec<String>,
20    /// `scheme: "tms"`: tile rows count from the south.
21    pub tms: bool,
22}
23
24impl TileUrls {
25    /// One `scheme: "xyz"` template.
26    pub fn xyz(template: impl Into<String>) -> Self {
27        TileUrls { templates: vec![template.into()], tms: false }
28    }
29
30    /// The URL of a tile, as MapLibre's `CanonicalTileID.url()`.
31    pub fn url(&self, coord: TileCoord, pixel_ratio: f64) -> String {
32        tile_url(&self.templates, coord, pixel_ratio, self.tms)
33    }
34}
35
36#[derive(Debug, Clone)]
37pub enum TileSource {
38    XyzRaster {
39        urls: TileUrls,
40        auth_header: Option<String>,
41        /// Server-advertised maximum zoom from the source object or TileJSON.
42        maxzoom: Option<u8>,
43    },
44    MapboxVectorTile {
45        urls: TileUrls,
46        api_key: Option<String>,
47        /// Server-advertised maximum zoom from the source object or TileJSON.
48        maxzoom: Option<u8>,
49    },
50    PMTiles {
51        url: String,
52        maxzoom: Option<u8>,
53    },
54}
55
56impl TileSource {
57    pub fn maxzoom(&self) -> Option<u8> {
58        match self {
59            TileSource::XyzRaster { maxzoom, .. } => *maxzoom,
60            TileSource::MapboxVectorTile { maxzoom, .. } => *maxzoom,
61            TileSource::PMTiles { maxzoom, .. } => *maxzoom,
62        }
63    }
64}
65
66#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
67pub struct TileCoord {
68    pub z: u8,
69    pub x: u32,
70    pub y: u32,
71}
72
73pub type TileData = Vec<u8>;
74
75/// Where a PMTiles archive is read from: HTTP range requests (with our
76/// reqwest 0.12 client, avoiding the reqwest 0.13 pulled in by pmtiles'
77/// `http-async` feature), or a local file (`file://` URL or a path).
78pub struct ArchiveBackend {
79    location: ArchiveLocation,
80}
81
82enum ArchiveLocation {
83    Http { url: String, client: reqwest::Client },
84    File(std::path::PathBuf),
85}
86
87impl ArchiveBackend {
88    /// `url`: `http(s)://...`, `file://...` or a file path.
89    pub fn new(url: String, client: reqwest::Client) -> Self {
90        let location = if url.starts_with("http://") || url.starts_with("https://") {
91            ArchiveLocation::Http { url, client }
92        } else {
93            ArchiveLocation::File(local_path(&url))
94        };
95        Self { location }
96    }
97}
98
99/// The file a `file://` URL or a path names.
100pub fn local_path(url: &str) -> std::path::PathBuf {
101    if url.starts_with("file://") {
102        if let Ok(p) = reqwest::Url::parse(url).map(|u| u.to_file_path()) {
103            if let Ok(p) = p {
104                return p;
105            }
106        }
107    }
108    std::path::PathBuf::from(url)
109}
110
111fn read_error(msg: String) -> pmtiles::PmtError {
112    pmtiles::PmtError::Reading(std::io::Error::other(msg))
113}
114
115impl pmtiles::AsyncBackend for ArchiveBackend {
116    fn read(
117        &self,
118        offset: usize,
119        length: usize,
120    ) -> impl std::future::Future<Output = pmtiles::PmtResult<pmtiles::BackendResponse>> + Send {
121        let location = match &self.location {
122            ArchiveLocation::Http { url, client } => Ok((url.clone(), client.clone())),
123            ArchiveLocation::File(path) => Err(path.clone()),
124        };
125        async move {
126            match location {
127                Ok((url, client)) => {
128                    let end = offset + length - 1;
129                    // Ranges of the file itself: a server free to compress
130                    // (GitHub Pages) would otherwise return a range of the
131                    // gzipped file, which is not the archive's bytes.
132                    let resp = client
133                        .get(&url)
134                        .header("Range", format!("bytes={offset}-{end}"))
135                        .header("Accept-Encoding", "identity")
136                        .send()
137                        .await
138                        .map_err(|e| read_error(e.to_string()))?;
139                    if !resp.status().is_success() {
140                        return Err(read_error(format!("HTTP {} fetching PMTiles range from {url}", resp.status())));
141                    }
142                    let bytes = resp.bytes().await.map_err(|e| read_error(e.to_string()))?;
143                    Ok(pmtiles::BackendResponse::new(bytes))
144                }
145                Err(path) => {
146                    use std::io::{Read, Seek, SeekFrom};
147                    let mut f = std::fs::File::open(&path)
148                        .map_err(|e| read_error(format!("{}: {e}", path.display())))?;
149                    f.seek(SeekFrom::Start(offset as u64)).map_err(|e| read_error(e.to_string()))?;
150                    // A range past the end (the header read asks for more
151                    // than a small archive holds) returns what there is.
152                    let mut buf = Vec::with_capacity(length);
153                    f.take(length as u64).read_to_end(&mut buf).map_err(|e| read_error(e.to_string()))?;
154                    Ok(pmtiles::BackendResponse::new(bytes::Bytes::from(buf)))
155                }
156            }
157        }
158    }
159}
160
161/// The URL of a tile from a source's templates, as MapLibre's
162/// `CanonicalTileID.url()`: the template is picked by `(x + y) % n` (spreading
163/// tiles over subdomains), then `{prefix}`, `{z}`, `{x}`, `{y}` (flipped for
164/// `scheme: "tms"`), `{ratio}` (`@2x` above pixel ratio 1), `{quadkey}` and
165/// `{bbox-epsg-3857}` (for WMS) are replaced. WMTS's `{TileMatrix}`,
166/// `{TileCol}` and `{TileRow}` work too (an extension: MapLibre has none).
167pub fn tile_url(templates: &[String], coord: TileCoord, pixel_ratio: f64, tms: bool) -> String {
168    let Some(first) = templates.first() else { return String::new() };
169    let template = templates
170        .get(((coord.x as u64 + coord.y as u64) % templates.len() as u64) as usize)
171        .unwrap_or(first);
172    let n = 1u64 << coord.z;
173    let y = if tms { n - 1 - coord.y as u64 } else { coord.y as u64 };
174    let mut s = template
175        .replace("{prefix}", &format!("{:x}{:x}", coord.x % 16, coord.y % 16))
176        .replace("{z}", &coord.z.to_string())
177        .replace("{x}", &coord.x.to_string())
178        .replace("{y}", &y.to_string())
179        .replace("{ratio}", if pixel_ratio > 1.0 { "@2x" } else { "" });
180    // WMTS ResourceURL templates (GoogleMapsCompatible matrix sets), so a
181    // template copied from GetCapabilities works as is.
182    if s.contains("{Tile") {
183        s = s
184            .replace("{TileMatrix}", &coord.z.to_string())
185            .replace("{TileCol}", &coord.x.to_string())
186            .replace("{TileRow}", &y.to_string());
187    }
188    if s.contains("{quadkey}") {
189        s = s.replace("{quadkey}", &quadkey(coord));
190    }
191    if s.contains("{bbox-epsg-3857}") {
192        s = s.replace("{bbox-epsg-3857}", &tile_bbox(coord));
193    }
194    s
195}
196
197/// [`tile_url`] for one `scheme: "xyz"` template at pixel ratio 1.
198pub fn expand_url(template: &str, coord: TileCoord) -> String {
199    tile_url(&[template.to_owned()], coord, 1.0, false)
200}
201
202/// Bing-style quadkey of a tile (MapLibre's `getQuadkey`).
203fn quadkey(c: TileCoord) -> String {
204    (1..=c.z)
205        .rev()
206        .map(|i| {
207            let mask = 1u32 << (i - 1);
208            char::from(b'0' + u8::from(c.x & mask != 0) + 2 * u8::from(c.y & mask != 0))
209        })
210        .collect()
211}
212
213/// `xmin,ymin,xmax,ymax` of a tile in EPSG:3857 metres, computed and printed
214/// exactly as MapLibre's `{bbox-epsg-3857}` (whoots-js `getTileBBox`, numbers
215/// as JavaScript prints them), so WMS requests match MapLibre's byte for byte.
216fn tile_bbox(c: TileCoord) -> String {
217    use std::f64::consts::PI;
218    let y = 2f64.powi(c.z as i32) - c.y as f64 - 1.0;
219    let merc = |px: f64, py: f64| {
220        let resolution = (2.0 * PI * 6378137.0 / 256.0) / 2f64.powi(c.z as i32);
221        let half = 2.0 * PI * 6378137.0 / 2.0;
222        (px * resolution - half, py * resolution - half)
223    };
224    let x = c.x as f64;
225    let (x0, y0) = merc(x * 256.0, y * 256.0);
226    let (x1, y1) = merc((x + 1.0) * 256.0, (y + 1.0) * 256.0);
227    format!("{},{},{},{}", js_number(x0), js_number(y0), js_number(x1), js_number(y1))
228}
229
230/// A number as JavaScript's `String(n)` prints it (shortest round trip;
231/// exponent form below 1e-6). Values here stay well under 1e21.
232fn js_number(v: f64) -> String {
233    if v == 0.0 {
234        "0".to_owned()
235    } else if v.abs() < 1e-6 {
236        format!("{v:e}")
237    } else {
238        format!("{v}")
239    }
240}
241
242/// Compute all tile coordinates that cover a given EPSG:3857 bbox at zoom.
243pub fn build_tile_coords(bbox: [f64; 4], zoom: u8) -> Vec<TileCoord> {
244    let (x0, y0) = mercator_to_tile(bbox[0], bbox[3], zoom);
245    let (x1, y1) = mercator_to_tile(bbox[2], bbox[1], zoom);
246    let mut coords = Vec::new();
247    for tx in x0..=x1 {
248        for ty in y0..=y1 {
249            coords.push(TileCoord {
250                z: zoom,
251                x: tx,
252                y: ty,
253            });
254        }
255    }
256    coords
257}
258
259/// Build the URL list for a given tile source and set of coordinates;
260/// `pixel_ratio` fills `{ratio}`.
261pub fn build_tile_urls(source: &TileSource, coords: &[TileCoord], pixel_ratio: f64) -> Vec<(TileCoord, String)> {
262    coords
263        .iter()
264        .map(|&coord| {
265            let url = match source {
266                TileSource::XyzRaster { urls, .. } => urls.url(coord, pixel_ratio),
267                TileSource::MapboxVectorTile { urls, api_key, .. } => {
268                    let base = urls.url(coord, pixel_ratio);
269                    match api_key {
270                        Some(key) => {
271                            let sep = if base.contains('?') { '&' } else { '?' };
272                            format!("{base}{sep}access_token={key}")
273                        }
274                        None => base,
275                    }
276                }
277                // PMTiles fetch bypasses the URL template system.
278                TileSource::PMTiles { .. } => String::new(),
279            };
280            (coord, url)
281        })
282        .collect()
283}
284
285/// Fetch all tiles concurrently, respecting timeout and concurrency limits.
286///
287/// Tiles come from the in-process LRU cache, else the disk cache
288/// ([`crate::cache`]), else the network; fetched tiles are added to both.
289///
290/// When `fail_on_tile_error` is `false`, individual tile failures are logged
291/// and skipped; the render continues with whatever tiles succeeded.
292pub async fn fetch_all_tiles(
293    client: &reqwest::Client,
294    urls: Vec<(TileCoord, String)>,
295    source: &TileSource,
296    timeout_ms: u32,
297    concurrency: u32,
298    fail_on_tile_error: bool,
299) -> Result<Vec<(TileCoord, TileData)>, BasemapError> {
300    let timeout = Duration::from_millis(timeout_ms as u64);
301    let semaphore = std::sync::Arc::new(tokio::sync::Semaphore::new(concurrency as usize));
302    let mut set: JoinSet<Result<(TileCoord, TileData), BasemapError>> = JoinSet::new();
303
304    for (coord, url) in urls {
305        let client = client.clone();
306        let sem = semaphore.clone();
307        let url = url.clone();
308        let auth = match source {
309            TileSource::XyzRaster { auth_header, .. } => auth_header.clone(),
310            TileSource::MapboxVectorTile { .. } => None,
311            TileSource::PMTiles { .. } => None,
312        };
313
314        set.spawn(async move {
315            let _permit = sem.acquire().await.unwrap();
316
317            // Cache hit — skip network entirely.
318            if let Ok(mut cache) = TILE_CACHE.lock() {
319                if let Some(cached) = cache.get(&url) {
320                    return Ok((coord, cached.clone()));
321                }
322            }
323
324            let cache_on_disk = auth.is_none();
325            if cache_on_disk {
326                if let Some(data) = crate::cache::get(&url) {
327                    if let Ok(mut cache) = TILE_CACHE.lock() {
328                        cache.put(url.clone(), data.clone());
329                    }
330                    return Ok((coord, data));
331                }
332            }
333
334            let mut req = client.get(&url).timeout(timeout);
335            if let Some(header) = auth {
336                req = req.header("Authorization", header);
337            }
338            let resp = req
339                .send()
340                .await
341                .map_err(|_| BasemapError::TileFetchFailed {
342                    url: url.clone(),
343                    status: 0,
344                })?;
345            if !resp.status().is_success() {
346                return Err(BasemapError::TileFetchFailed {
347                    url: url.clone(),
348                    status: resp.status().as_u16(),
349                });
350            }
351            let headers = resp.headers().clone();
352            let bytes = resp
353                .bytes()
354                .await
355                .map_err(|_| BasemapError::TileFetchFailed {
356                    url: url.clone(),
357                    status: 0,
358                })?;
359            let data = bytes.to_vec();
360            if is_web_page(&headers, &data) {
361                return Err(BasemapError::TileIsWebPage { url: url.clone() });
362            }
363            if cache_on_disk {
364                crate::cache::put(&url, &headers, &data);
365            }
366
367            // Populate cache for future renders.
368            if let Ok(mut cache) = TILE_CACHE.lock() {
369                cache.put(url, data.clone());
370            }
371
372            Ok((coord, data))
373        });
374    }
375
376    let mut results = Vec::new();
377    let mut refused: Option<u16> = None;
378    let mut web_page = false;
379    let mut other_failures = false;
380    while let Some(res) = set.join_next().await {
381        let tile_result = res.map_err(|e| BasemapError::RenderError(e.to_string()))?;
382        match tile_result {
383            Ok(tile) => results.push(tile),
384            Err(e) => {
385                if fail_on_tile_error {
386                    return Err(e);
387                }
388                match e {
389                    BasemapError::TileFetchFailed { status: s @ (401 | 403), .. } => refused = Some(s),
390                    BasemapError::TileIsWebPage { .. } => web_page = true,
391                    _ => other_failures = true,
392                }
393                log::warn!("tile fetch failed (skipped): {e}");
394            }
395        }
396    }
397    // Every tile refused (or answered with a web page) is a key problem, not
398    // a flaky tile: say so rather than draw nothing. (No URL: it may carry
399    // the key.)
400    if results.is_empty() && !other_failures {
401        if let Some(status) = refused {
402            return Err(BasemapError::InvalidInput(format!(
403                "the tile server refused every tile (HTTP {status}): check that the API key (or quad word) gives access to this basemap"
404            )));
405        }
406        if web_page {
407            return Err(BasemapError::TileIsWebPage { url: String::new() });
408        }
409    }
410    Ok(results)
411}
412
413/// Whether a tile response is a web page (a sign-in or error page) rather
414/// than tile data: by its content type, or an HTML start.
415fn is_web_page(headers: &reqwest::header::HeaderMap, body: &[u8]) -> bool {
416    let html_type = headers
417        .get(reqwest::header::CONTENT_TYPE)
418        .and_then(|v| v.to_str().ok())
419        .is_some_and(|t| t.to_ascii_lowercase().starts_with("text/html"));
420    let start: Vec<u8> = body.iter().skip_while(|b| b.is_ascii_whitespace()).take(15).map(u8::to_ascii_lowercase).collect();
421    html_type || start.starts_with(b"<!doctype html") || start.starts_with(b"<html")
422}
423
424#[cfg(test)]
425mod url_tests {
426    use super::*;
427
428    fn c(z: u8, x: u32, y: u32) -> TileCoord {
429        TileCoord { z, x, y }
430    }
431
432    #[test]
433    fn tokens_expand_as_maplibre() {
434        let t = |tpl: &str, coord, ratio, tms| tile_url(&[tpl.to_owned()], coord, ratio, tms);
435        assert_eq!(t("https://t/{z}/{x}/{y}.png", c(5, 3, 7), 1.0, false), "https://t/5/3/7.png");
436        // scheme "tms": rows from the south.
437        assert_eq!(t("https://t/{z}/{x}/{y}.png", c(5, 3, 7), 1.0, true), "https://t/5/3/24.png");
438        assert_eq!(t("https://t/{z}/{x}/{y}{ratio}.png", c(1, 0, 0), 2.0, false), "https://t/1/0/0@2x.png");
439        assert_eq!(t("https://t/{z}/{x}/{y}{ratio}.png", c(1, 0, 0), 1.0, false), "https://t/1/0/0.png");
440        // Bing's documented example: tile (3, 5) at level 3 is "213".
441        assert_eq!(t("https://t/{quadkey}.jpeg", c(3, 3, 5), 1.0, false), "https://t/213.jpeg");
442        assert_eq!(t("https://t/{prefix}/{z}", c(5, 17, 30), 1.0, false), "https://t/1e/5");
443        assert_eq!(
444            t("https://t/{TileMatrix}/{TileRow}/{TileCol}.png", c(5, 3, 7), 1.0, false),
445            "https://t/5/7/3.png"
446        );
447    }
448
449    #[test]
450    fn templates_are_picked_by_x_plus_y() {
451        let urls = TileUrls { templates: vec!["a/{x}".into(), "b/{x}".into(), "c/{x}".into()], tms: false };
452        assert_eq!(urls.url(c(4, 0, 0), 1.0), "a/0");
453        assert_eq!(urls.url(c(4, 1, 0), 1.0), "b/1");
454        assert_eq!(urls.url(c(4, 1, 1), 1.0), "c/1");
455        assert_eq!(urls.url(c(4, 2, 1), 1.0), "a/2");
456    }
457
458    #[test]
459    fn bbox_matches_maplibre_strings() {
460        // Strings from MapLibre GL JS 5.24 (whoots-js getTileBBox, String(n)).
461        let b = |coord| tile_url(&["{bbox-epsg-3857}".to_owned()], coord, 1.0, false);
462        assert_eq!(b(c(0, 0, 0)), "-20037508.342789244,-20037508.342789244,20037508.342789244,20037508.342789244");
463        assert_eq!(b(c(1, 1, 0)), "0,0,20037508.342789244,20037508.342789244");
464        assert_eq!(b(c(1, 0, 1)), "-20037508.342789244,-20037508.342789244,0,0");
465        assert_eq!(b(c(3, 4, 2)), "0,5009377.085697312,5009377.085697312,10018754.17139462");
466        assert_eq!(
467            b(c(19, 154308, 197167)),
468            "-8242663.382160267,4966572.349857613,-8242586.945131982,4966648.786885899"
469        );
470    }
471}