use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use std::{fmt, io};
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};
#[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()
}
}
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 {
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()))?;
let start_delay = Duration::from_millis(50);
let max_attempts = 10; 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)"
),
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 {
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())
}
}
}