use std::fmt;
use std::path::PathBuf;
use std::sync::Arc;
use martin_tile_utils::{Encoding, Format, TileCoord, TileData, TileInfo};
use object_store::ObjectStore;
use pmtiles::{AsyncPmTilesReader, Compression, ObjectStoreBackend, PmtError, TileType};
use tilejson::TileJSON;
use tracing::{instrument, trace, warn};
use crate::CacheZoomRange;
use crate::tiles::pmtiles::PmtCacheInstance;
use crate::tiles::pmtiles::PmtilesError::{self, InvalidMetadata};
use crate::tiles::pmtiles::backend::{PmtBackend, PmtFileBackend};
use crate::tiles::source::cap_zoom_range;
use crate::tiles::{MartinCoreError, MartinCoreResult, Source, UrlQuery};
#[derive(Clone)]
enum PmtLocation {
File(PathBuf),
ObjectStore {
store: Arc<dyn ObjectStore>,
path: object_store::path::Path,
},
}
#[derive(Clone)]
pub struct PmtilesSource {
id: String,
pmtiles: Arc<AsyncPmTilesReader<PmtBackend, PmtCacheInstance>>,
tilejson: TileJSON,
tile_info: TileInfo,
cache_zoom: CacheZoomRange,
location: PmtLocation,
pmt_cache: PmtCacheInstance,
}
impl fmt::Debug for PmtilesSource {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Self {
id,
pmtiles: _,
tilejson: _,
tile_info: _,
cache_zoom: _,
location: _,
pmt_cache: _,
} = self;
f.debug_struct("PmtilesSource").field("id", id).finish_non_exhaustive()
}
}
impl PmtilesSource {
pub async fn new(
cache: PmtCacheInstance,
id: String,
store: Box<dyn ObjectStore>,
path: impl Into<object_store::path::Path>,
cache_zoom: CacheZoomRange,
) -> Result<Self, PmtilesError> {
let path = path.into();
let store: Arc<dyn ObjectStore> = Arc::from(store);
let backend = ObjectStoreBackend::new(Box::new(Arc::clone(&store)), path.clone());
let location = PmtLocation::ObjectStore { store, path };
Self::from_backend(cache, id, PmtBackend::ObjectStore(backend), location, cache_zoom).await
}
pub async fn new_local(
cache: PmtCacheInstance,
id: String,
path: impl Into<PathBuf>,
cache_zoom: CacheZoomRange,
) -> Result<Self, PmtilesError> {
let path = path.into();
let backend = PmtFileBackend::open(&path)
.await
.map_err(|e| PmtilesError::PmtErrorWithCtx(e, path.display().to_string()))?;
let location = PmtLocation::File(path);
Self::from_backend(cache, id, PmtBackend::File(backend), location, cache_zoom).await
}
#[instrument(name = "pmtiles", skip_all, fields(source = %id))]
async fn from_backend(
cache: PmtCacheInstance,
id: String,
backend: PmtBackend,
location: PmtLocation,
cache_zoom: CacheZoomRange,
) -> Result<Self, PmtilesError> {
let (store_name, path) = match &location {
PmtLocation::File(file) => (
file.display().to_string(),
object_store::path::Path::from(file.to_string_lossy().as_ref()),
),
PmtLocation::ObjectStore { store, path } => (store.to_string(), path.clone()),
};
let reader = AsyncPmTilesReader::try_from_cached_source(backend, cache.clone())
.await
.map_err(|e| PmtilesError::PmtErrorWithCtx(e, store_name.clone()))?;
let hdr = &reader.get_header();
if hdr.tile_type != TileType::Mvt && hdr.tile_compression != Compression::None {
return Err(InvalidMetadata(
format!(
"Format {:?} and compression {:?} are not yet supported",
hdr.tile_type, hdr.tile_compression
),
path,
));
}
let format = match hdr.tile_type {
TileType::Mvt => TileInfo::new(
Format::Mvt,
match hdr.tile_compression {
Compression::None => Encoding::Uncompressed,
Compression::Unknown => {
warn!(
source.id = %id,
store = %store_name,
path = %path,
"MVT tiles have unknown compression"
);
Encoding::Uncompressed
}
Compression::Gzip => Encoding::Gzip,
Compression::Brotli => Encoding::Brotli,
Compression::Zstd => Encoding::Zstd,
},
),
TileType::Png => Format::Png.into(),
TileType::Jpeg => Format::Jpeg.into(),
TileType::Webp => Format::Webp.into(),
TileType::Avif => Format::Avif.into(),
TileType::Mlt => Format::Mlt.into(),
TileType::Unknown => {
return Err(PmtilesError::UnknownTileType {
source_id: id,
store: store_name,
path: path.to_string(),
});
}
};
let mut tilejson = reader.parse_tilejson(Vec::new()).await.unwrap_or_else(|e| {
warn!(path = %path, error = ?e, "Unable to parse metadata");
hdr.get_tilejson(Vec::new())
});
cap_zoom_range(&id, &mut tilejson);
Ok(Self {
id,
pmtiles: Arc::new(reader),
tilejson,
tile_info: format,
cache_zoom,
location,
pmt_cache: cache,
})
}
}
impl Source for PmtilesSource {
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 {
true
}
async fn try_reload(&self) -> MartinCoreResult<Self> {
let cache = self.pmt_cache.fork();
let id = self.id.clone();
let reloaded = match &self.location {
PmtLocation::File(path) => Self::new_local(cache, id, path.clone(), self.cache_zoom).await,
PmtLocation::ObjectStore { store, path } => {
Self::new(cache, id, Box::new(Arc::clone(store)), path.clone(), self.cache_zoom).await
}
};
reloaded.map_err(MartinCoreError::from)
}
fn cache_zoom(&self) -> CacheZoomRange {
self.cache_zoom
}
#[instrument(name = "pmtiles", skip_all, fields(source = %self.id))]
async fn get_tile(&self, xyz: TileCoord, _url_query: Option<&UrlQuery>) -> MartinCoreResult<TileData> {
let coord = pmtiles::TileCoord::new(xyz.z(), xyz.x(), xyz.y()).map_err(PmtilesError::PmtError)?;
let result = self.pmtiles.get_tile(coord).await;
if let Some(t) = match result {
Err(PmtError::SourceModified) => {
return Err(MartinCoreError::SourceNeedsReload);
}
Err(e) => return Err(PmtilesError::PmtError(e).into()),
Ok(t) => t,
} {
Ok(t)
} else {
trace!(
source.id = %self.id,
tile.z = xyz.z(),
tile.x = xyz.x(),
tile.y = xyz.y(),
"Couldn't find tile data"
);
Ok(TileData::new())
}
}
}