martin-core 0.16.0

Basic building blocks of MapLibre's Martin tile server.
Documentation
//! Style processing and serving for map tile rendering.
//!
//! Manages `MapLibre` style JSON files for map rendering clients.
//!
//! # Usage
//!
//! ```rust,no_run
//! use martin_core::styles::StyleSources;
//! use std::path::PathBuf;
//!
//! let mut sources = StyleSources::default();
//! sources.add_style("basic".to_string(), PathBuf::from("/path/to/style.json"));
//! let path = sources.style_json_path("basic").unwrap();
//! ```

use std::collections::BTreeMap;
use std::fmt::Debug;
#[cfg(all(feature = "rendering", target_os = "linux"))]
use std::num::{NonZeroU8, NonZeroUsize};
use std::path::PathBuf;

use chrono::{DateTime, Utc};
use dashmap::{DashMap, Entry};
#[cfg(all(feature = "rendering", target_os = "linux"))]
pub use maplibre_native::Image as StaticImage;
#[cfg(all(feature = "rendering", target_os = "linux"))]
use maplibre_native::Image;
use serde::{Deserialize, Serialize};
use serde_with::skip_serializing_none;
use tracing::{info, warn};

#[cfg(all(feature = "rendering", target_os = "linux"))]
mod error;
#[cfg(all(feature = "rendering", target_os = "linux"))]
pub use error::StyleError;

/// Worker pool for map image rendering.
#[cfg(all(feature = "rendering", target_os = "linux"))]
pub mod render_pool;
#[cfg(all(feature = "rendering", target_os = "linux"))]
use render_pool::RenderPools;
#[cfg(all(feature = "rendering", target_os = "linux"))]
pub use render_pool::{DEFAULT_RENDERERS_PER_WORKER, RenderParams, RenderStyle};

#[cfg(feature = "rendering")]
pub use crate::image_quality::{ImageQuality, LossyQuality};
#[cfg(feature = "rendering")]
mod pixel_ratio;
#[cfg(feature = "rendering")]
pub use pixel_ratio::{InvalidPixelRatios, PixelRatioNotServed, PixelRatios};
#[cfg(feature = "rendering")]
mod tile_size;
#[cfg(feature = "rendering")]
pub use tile_size::{InvalidTileSize, TileSize};

/// Quality rendered images are encoded at, per format.
#[cfg(feature = "rendering")]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct ImageQualities {
    /// Quality of WebP images.
    pub webp: ImageQuality,
    /// Quality of JPEG images, which have no lossless mode.
    pub jpeg: LossyQuality,
}

/// What kind of layers a `MapLibre` style draws.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
#[cfg_attr(feature = "unstable-schemas", derive(schemars::JsonSchema, utoipa::ToSchema))]
pub enum StyleKind {
    /// Style only references vector tile sources.
    Vector,
    /// Style only references raster tile sources.
    Raster,
    /// Style references both vector and raster tile sources.
    Hybrid,
}

/// Style metadata.
#[skip_serializing_none]
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "unstable-schemas", derive(schemars::JsonSchema, utoipa::ToSchema))]
pub struct CatalogStyleEntry {
    /// Path to the style JSON file.
    // utoipa 5.4 has no native `PathBuf` support - present it as a `String`
    // (the on-the-wire form) for both schema generators.
    #[cfg_attr(feature = "unstable-schemas", schemars(with = "String"))]
    #[cfg_attr(feature = "unstable-schemas", schema(value_type = String))]
    pub path: PathBuf,
    /// What kind of layers the style draws.
    #[serde(rename = "type")]
    pub kind: Option<StyleKind>,
    /// Hash identifying the current style revision.
    pub version_hash: Option<String>,
    /// Number of layers declared in the style JSON.
    pub layer_count: Option<u32>,
    /// Distinct colors referenced by the style, for preview swatches.
    pub colors: Option<Vec<String>>,
    /// Timestamp of the style file's last modification.
    pub last_modified_at: Option<DateTime<Utc>>,
}

/// Catalog mapping style names to metadata (e.g., "basic" -> `CatalogStyleEntry`).
pub type StyleCatalog = BTreeMap<String, CatalogStyleEntry>;

/// Thread-safe style source manager.
#[derive(Debug, Clone, Default)]
pub struct StyleSources {
    sources: DashMap<String, StyleSource>,
    #[cfg(all(feature = "rendering", target_os = "linux"))]
    pools: Option<RenderPools>,
    /// Pixel ratios served by the tile and static endpoints.
    #[cfg(feature = "rendering")]
    pixel_ratios: PixelRatios,
    /// Encode rendered PNGs with a palette of at most this many colours. `None` keeps RGBA.
    #[cfg(all(feature = "rendering", target_os = "linux"))]
    png_max_colors: Option<u16>,
    /// Quality rendered WebP and JPEG images are encoded at.
    #[cfg(all(feature = "rendering", target_os = "linux"))]
    image_quality: ImageQualities,
}

/// Style source file.
#[derive(Clone, Debug)]
pub struct StyleSource {
    path: PathBuf,
}

impl StyleSources {
    /// Retrieve a style's path from the catalog.
    #[must_use]
    pub fn style_json_path(&self, style_id: &str) -> Option<PathBuf> {
        let style_id = style_id.trim_end_matches(".json").trim();
        let item = self.sources.get(style_id)?;
        Some(item.path.clone())
    }

    /// Returns a catalog of all style sources.
    #[must_use]
    pub fn get_catalog(&self) -> StyleCatalog {
        let mut entries = StyleCatalog::new();
        for source in &self.sources {
            entries.insert(
                source.key().clone(),
                CatalogStyleEntry {
                    path: source.path.clone(),
                    // FIXME: parse the style JSON and surface its `type` field.
                    kind: None,
                    // FIXME: hash the style JSON contents.
                    version_hash: None,
                    // FIXME: parse the style JSON and count its `layers` array.
                    layer_count: None,
                    // FIXME: walk the style JSON and collect referenced colors.
                    colors: None,
                    // FIXME: stat the style file and surface its mtime.
                    last_modified_at: None,
                },
            );
        }
        entries
    }

    /// Whether server-side style rendering is currently enabled.
    #[cfg(all(feature = "rendering", target_os = "linux"))]
    #[must_use]
    pub const fn is_rendering_enabled(&self) -> bool {
        self.pools.is_some()
    }

    /// Adds a style JSON file with an ID to the catalog.
    pub fn add_style(&self, id: String, path: PathBuf) {
        debug_assert!(path.is_file());
        debug_assert_ne!(id, "");
        match self.sources.entry(id) {
            Entry::Occupied(v) => {
                warn!(
                    source.id = %v.key(),
                    style.path.kept = %v.get().path.display(),
                    style.path.dropped = %path.display(),
                    "Ignoring duplicate style source: already configured for another path"
                );
            }
            Entry::Vacant(v) => {
                info!(
                    source.id = %v.key(),
                    style.path = %path.display(),
                    "Configured style source"
                );
                v.insert(StyleSource { path });
            }
        }
    }

    /// Returns the number of style sources.
    #[must_use]
    pub fn len(&self) -> usize {
        self.sources.len()
    }

    /// Returns true if the catalog is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.sources.is_empty()
    }

    /// Renders a slippy tile of the configured [`TileSize`] via the dedicated tile renderer.
    #[cfg(all(feature = "rendering", target_os = "linux"))]
    pub async fn render(&self, style: impl Into<RenderStyle>, z: u8, x: u32, y: u32) -> Result<Image, StyleError> {
        self.render_with_pixel_ratio(style, z, x, y, NonZeroU8::MIN).await
    }

    /// Renders a slippy tile at `pixel_ratio` times the pixels of [`Self::render`].
    #[cfg(all(feature = "rendering", target_os = "linux"))]
    pub async fn render_with_pixel_ratio(
        &self,
        style: impl Into<RenderStyle>,
        z: u8,
        x: u32,
        y: u32,
        pixel_ratio: NonZeroU8,
    ) -> Result<Image, StyleError> {
        self.pools
            .as_ref()
            .ok_or(StyleError::RenderingIsDisabled)?
            .render_tile_with_pixel_ratio(style, z, x, y, pixel_ratio)
            .await
    }

    /// Renders a slippy tile of `tile_size` instead of the configured [`TileSize`], at `pixel_ratio` times its pixels.
    #[cfg(all(feature = "rendering", target_os = "linux"))]
    pub async fn render_of_size(
        &self,
        style: impl Into<RenderStyle>,
        z: u8,
        x: u32,
        y: u32,
        tile_size: TileSize,
        pixel_ratio: NonZeroU8,
    ) -> Result<Image, StyleError> {
        self.pools
            .as_ref()
            .ok_or(StyleError::RenderingIsDisabled)?
            .render_tile_of_size(style, z, x, y, tile_size, pixel_ratio)
            .await
    }

    /// Render a map image with free camera control.
    #[cfg(all(feature = "rendering", target_os = "linux"))]
    pub async fn render_static(&self, params: RenderParams) -> Result<Image, StyleError> {
        self.pools
            .as_ref()
            .ok_or(StyleError::RenderingIsDisabled)?
            .render_static(params)
            .await
    }

    /// Enable rendering by spawning the tile and static [`RenderPools`]. Replaces any existing pools.
    ///
    /// See [`RenderPools::new`] for the meaning of the arguments.
    ///
    /// # Errors
    ///
    /// Returns the OS error from [`std::thread::Builder::spawn`] if a worker
    /// thread cannot be started.
    #[cfg(all(feature = "rendering", target_os = "linux"))]
    pub fn enable_rendering(
        &mut self,
        workers: Option<NonZeroUsize>,
        tile_size: TileSize,
        renderers_per_worker: NonZeroUsize,
        ambient_cache_bytes: Option<u64>,
    ) -> Result<(), std::io::Error> {
        self.pools = Some(RenderPools::new(
            workers,
            tile_size,
            renderers_per_worker,
            ambient_cache_bytes,
        )?);
        Ok(())
    }

    /// Serve only `ratios` from the tile and static endpoints.
    #[cfg(feature = "rendering")]
    pub fn set_pixel_ratios(&mut self, ratios: PixelRatios) {
        self.pixel_ratios = ratios;
    }

    /// Pixel ratios the tile and static endpoints serve.
    #[cfg(feature = "rendering")]
    #[must_use]
    pub fn pixel_ratios(&self) -> PixelRatios {
        self.pixel_ratios
    }

    /// Disable rendering. Subsequent render calls return [`StyleError::RenderingIsDisabled`].
    #[cfg(all(feature = "rendering", target_os = "linux"))]
    pub fn disable_rendering(&mut self) {
        self.pools = None;
    }

    /// Encode rendered PNGs with a palette of at most `max_colors` colours (`None` keeps RGBA).
    #[cfg(all(feature = "rendering", target_os = "linux"))]
    pub fn set_png_max_colors(&mut self, max_colors: Option<u16>) {
        self.png_max_colors = max_colors;
    }

    /// Palette size for rendered PNGs, if palette encoding is enabled.
    #[cfg(all(feature = "rendering", target_os = "linux"))]
    #[must_use]
    pub fn png_max_colors(&self) -> Option<u16> {
        self.png_max_colors
    }

    /// Encode rendered WebP and JPEG images at `quality`.
    #[cfg(all(feature = "rendering", target_os = "linux"))]
    pub fn set_image_quality(&mut self, quality: ImageQualities) {
        self.image_quality = quality;
    }

    /// Quality rendered WebP and JPEG images are encoded at.
    #[cfg(all(feature = "rendering", target_os = "linux"))]
    #[must_use]
    pub fn image_quality(&self) -> ImageQualities {
        self.image_quality
    }
}

#[cfg(test)]
mod tests {
    use std::path::Path;

    use super::*;

    #[test]
    fn style_external() {
        let style_dir = Path::new("../tests/fixtures/styles/");

        let styles = StyleSources::default();
        styles.add_style("maplibre_demo".to_owned(), style_dir.join("maplibre_demo.json"));
        styles.add_style(
            "maptiler_basic".to_owned(),
            style_dir.join("src2").join("maptiler_basic.json"),
        );
        styles.add_style(
            "osm-liberty-lite".to_owned(),
            style_dir.join("src2").join("osm-liberty-lite.json"),
        );
        assert_eq!(styles.sources.len(), 3);

        let mut catalog = styles.get_catalog();
        // The catalog keeps the paths as joined, so on Windows they hold backslashes.
        for entry in catalog.values_mut() {
            entry.path = entry
                .path
                .to_string_lossy()
                .replace(std::path::MAIN_SEPARATOR, "/")
                .into();
        }

        insta::with_settings!({sort_maps => true}, {
        insta::assert_json_snapshot!(catalog, @r#"
        {
          "maplibre_demo": {
            "path": "../tests/fixtures/styles/maplibre_demo.json"
          },
          "maptiler_basic": {
            "path": "../tests/fixtures/styles/src2/maptiler_basic.json"
          },
          "osm-liberty-lite": {
            "path": "../tests/fixtures/styles/src2/osm-liberty-lite.json"
          }
        }
        "#);
        });

        assert_eq!(styles.style_json_path("NON_EXISTENT"), None);
        assert_eq!(
            styles.style_json_path("maplibre_demo.json"),
            Some(style_dir.join("maplibre_demo.json"))
        );
        assert_eq!(styles.style_json_path("src2"), None);
        let src2_dir = style_dir.join("src2");
        assert_eq!(
            styles.style_json_path("maptiler_basic"),
            Some(src2_dir.join("maptiler_basic.json"))
        );
        assert_eq!(
            styles.style_json_path("maptiler_basic.json"),
            Some(src2_dir.join("maptiler_basic.json"))
        );
        assert_eq!(
            styles.style_json_path("osm-liberty-lite.json"),
            Some(src2_dir.join("osm-liberty-lite.json"))
        );
    }
}