martin-core 0.16.0

Basic building blocks of MapLibre's Martin tile server.
Documentation
//! `MBTiles` tile source implementation.

use std::fmt;
use std::io;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use backon::{FibonacciBuilder, Retryable as _};
use martin_tile_utils::{TileCoord, TileData, TileInfo};
use mbtiles::sqlx::error::DatabaseError;
use mbtiles::{MbtError, MbtilesPool};
use tilejson::TileJSON;
use tracing::{debug, trace, warn};

use crate::CacheZoomRange;
use crate::tiles::mbtiles::MbtilesError;
use crate::tiles::source::cap_zoom_range;
use crate::tiles::{MartinCoreResult, Source, UrlQuery};

/// Tile source that reads from `MBTiles` files.
#[derive(Clone)]
pub struct MbtSource {
    id: String,
    mbtiles: Arc<MbtilesPool>,
    tilejson: TileJSON,
    tile_info: TileInfo,
    cache_zoom: CacheZoomRange,
}

impl fmt::Debug for MbtSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Self {
            id,
            mbtiles,
            tilejson: _,
            tile_info: _,
            cache_zoom: _,
        } = self;
        f.debug_struct("MbtSource")
            .field("id", id)
            .field("path", mbtiles)
            .finish_non_exhaustive()
    }
}

// SQLITE_BUSY (code: 5)
// https://sqlite.org/rescode.html#busy
fn is_sqlite_busy(err: &MbtError) -> bool {
    matches!(
        err,
        MbtError::SqlxError(se)
            if se
                .as_database_error()
                .and_then(DatabaseError::code)
                .is_some_and(|code| code == "5")
    )
}

impl MbtSource {
    /// Creates a new `MBTiles` source from the given file path.
    pub async fn new(id: String, path: PathBuf, cache_zoom: CacheZoomRange) -> Result<Self, MbtilesError> {
        let mbt = MbtilesPool::open_readonly(&path)
            .await
            .map_err(|e| io::Error::other(format!("{e:?}: Cannot open file {}", path.display())))
            .map_err(|e| MbtilesError::IoError(e, path.clone()))?;

        // Attempt to fetch metadata with backoff
        let start_delay = Duration::from_millis(50);
        let max_attempts = 10; // from 50ms to 2.75s
        let meta = (|| async { mbt.get_metadata().await })
            .retry(
                FibonacciBuilder::default()
                    .with_min_delay(start_delay)
                    .with_max_times(max_attempts)
                    .with_jitter(),
            )
            .sleep(tokio::time::sleep)
            .when(is_sqlite_busy)
            .notify(|_err, dur| {
                warn!(
                    source.path = ?path.display(),
                    retry.delay = ?dur,
                    "Database file locked (SQLITE_BUSY), retrying"
                );
            })
            .await
            .map_err(|e| MbtilesError::InvalidMetadata(e.to_string(), path.clone()))?;

        match mbt.missing_tile_index().await {
            Ok(Some(table)) => warn!(
                source.id = %id,
                mbtiles.file = %path.display(),
                "Table {table} has no index on (zoom_level, tile_column, tile_row), so every tile lookup scans it. \
                 Create one with: CREATE UNIQUE INDEX {table}_index ON {table} (zoom_level, tile_column, tile_row)"
            ),
            // an index exists, but it may not be unique
            Ok(None) => match mbt.detect_type().await {
                Ok((_, warnings)) => {
                    for warning in warnings {
                        warn!(source.id = %id, "{warning}");
                    }
                }
                Err(e) => debug!(source.id = %id, error = %e, "Could not detect the MBTiles type"),
            },
            Err(e) => debug!(source.id = %id, error = %e, "Could not check the tile index"),
        }

        let tile_info = mbt
            .detect_format(&meta.tilejson)
            .await
            .and_then(|v| v.ok_or(MbtError::NoTilesFound))
            .map_err(|e| MbtilesError::InvalidMetadata(e.to_string(), path))?;

        let mut tilejson = meta.tilejson;
        cap_zoom_range(&id, &mut tilejson);
        Ok(Self {
            id,
            mbtiles: Arc::new(mbt),
            tilejson,
            tile_info,
            cache_zoom,
        })
    }
}

impl Source for MbtSource {
    fn get_id(&self) -> &str {
        &self.id
    }

    fn get_tilejson(&self) -> &TileJSON {
        &self.tilejson
    }

    fn get_tile_info(&self) -> TileInfo {
        self.tile_info
    }

    fn get_version(&self) -> Option<String> {
        self.tilejson.version.clone()
    }

    fn benefits_from_concurrent_scraping(&self) -> bool {
        // If we copy from one local file to another, we are likely not bottlenecked by CPU
        false
    }

    fn cache_zoom(&self) -> CacheZoomRange {
        self.cache_zoom
    }

    async fn get_tile(&self, xyz: TileCoord, _url_query: Option<&UrlQuery>) -> MartinCoreResult<TileData> {
        if let Some(tile) = self
            .mbtiles
            .get_tile(xyz.z(), xyz.x(), xyz.y())
            .await
            .map_err(|e| MbtilesError::AcquireConnError(self.id.clone(), Box::new(e)))?
        {
            Ok(tile.into())
        } else {
            trace!(source.id = %self.id, tile.coord = %xyz, "Couldn't find tile data");
            Ok(TileData::new())
        }
    }
}