mln-rs-plugin 0.0.23

Safe Rust SDK for writing MapLibre layer, source, and expression plugins
Documentation
//! Safe, host-agnostic traits and async [`TileRequest`] handle for source plugins.

use crate::backend::TileRequestBackend;
use crate::error::Result;
use crate::types::{CanonicalTileId, LatLngBounds, RasterEncoding, TileNecessity, TileScheme, TileTimes};

// ---------------------------------------------------------------------------
// Options & callback info
// ---------------------------------------------------------------------------

/// GeoJSON tiling defaults for a [`SourceKindOptions::Geometry`] plugin source.
#[derive(Clone, Copy, Debug, Default)]
pub struct GeometrySourceOptions {
    pub buffer: Option<u32>,
    pub tolerance: Option<f64>,
    pub clip: Option<bool>,
    pub wrap: Option<bool>,
}

impl GeometrySourceOptions {
    #[must_use]
    pub const fn new() -> Self {
        Self { buffer: None, tolerance: None, clip: None, wrap: None }
    }

    #[must_use]
    pub const fn buffer(mut self, buffer: u32) -> Self {
        self.buffer = Some(buffer);
        self
    }

    #[must_use]
    pub const fn tolerance(mut self, tolerance: f64) -> Self {
        self.tolerance = Some(tolerance);
        self
    }

    #[must_use]
    pub const fn clip(mut self, clip: bool) -> Self {
        self.clip = Some(clip);
        self
    }

    #[must_use]
    pub const fn wrap(mut self, wrap: bool) -> Self {
        self.wrap = Some(wrap);
        self
    }
}

/// Elevation defaults for a [`SourceKindOptions::RasterDem`] plugin source.
#[derive(Clone, Copy, Debug, Default)]
pub struct RasterDemSourceOptions {
    pub encoding: Option<RasterEncoding>,
}

impl RasterDemSourceOptions {
    #[must_use]
    pub const fn new() -> Self {
        Self { encoding: None }
    }

    #[must_use]
    pub const fn encoding(mut self, encoding: RasterEncoding) -> Self {
        self.encoding = Some(encoding);
        self
    }
}

/// Kind of tiles a plugin source supplies together with its kind-specific defaults.
#[derive(Clone, Copy, Debug)]
pub enum SourceKindOptions {
    Geometry(GeometrySourceOptions),
    Raster,
    RasterDem(RasterDemSourceOptions),
}

/// Configuration and defaults for registering a [`SourcePlugin`].
///
/// When style JSON creates a source of this type, standard members (`minzoom`,
/// `maxzoom`, `tileSize`, `scheme`, `bounds`, `attribution`, and kind-specific
/// members such as `encoding`, `buffer`, `tolerance`, `clip`, and `wrap`)
/// override these defaults for that source instance, while the raw JSON object
/// is passed to [`SourcePlugin::fetch_tile`] and [`SourcePlugin::cancel_tile`].
#[derive(Clone, Copy, Debug)]
pub struct SourceTypeOptions<'a> {
    pub name: &'a str,
    pub kind: SourceKindOptions,
    pub min_zoom: Option<f64>,
    pub max_zoom: Option<f64>,
    pub tile_size: Option<u32>,
    pub scheme: Option<TileScheme>,
    pub bounds: Option<LatLngBounds>,
    pub attribution: Option<&'a str>,
    pub fetches_optional: Option<bool>,
}

impl<'a> SourceTypeOptions<'a> {
    #[must_use]
    pub const fn new(name: &'a str, kind: SourceKindOptions) -> Self {
        Self {
            name,
            kind,
            min_zoom: None,
            max_zoom: None,
            tile_size: None,
            scheme: None,
            bounds: None,
            attribution: None,
            fetches_optional: None,
        }
    }

    /// Creates options for a geometry (GeoJSON / MVT / MLT) plugin source with default tiling options.
    #[must_use]
    pub const fn geometry(name: &'a str) -> Self {
        Self::new(name, SourceKindOptions::Geometry(GeometrySourceOptions::new()))
    }

    /// Creates options for a raster image plugin source.
    #[must_use]
    pub const fn raster(name: &'a str) -> Self {
        Self::new(name, SourceKindOptions::Raster)
    }

    /// Creates options for a raster-DEM plugin source with default elevation options.
    #[must_use]
    pub const fn raster_dem(name: &'a str) -> Self {
        Self::new(name, SourceKindOptions::RasterDem(RasterDemSourceOptions::new()))
    }

    #[must_use]
    pub const fn min_zoom(mut self, min_zoom: f64) -> Self {
        self.min_zoom = Some(min_zoom);
        self
    }

    #[must_use]
    pub const fn max_zoom(mut self, max_zoom: f64) -> Self {
        self.max_zoom = Some(max_zoom);
        self
    }

    #[must_use]
    pub const fn tile_size(mut self, tile_size: u32) -> Self {
        self.tile_size = Some(tile_size);
        self
    }

    #[must_use]
    pub const fn scheme(mut self, scheme: TileScheme) -> Self {
        self.scheme = Some(scheme);
        self
    }

    #[must_use]
    pub const fn bounds(mut self, bounds: LatLngBounds) -> Self {
        self.bounds = Some(bounds);
        self
    }

    #[must_use]
    pub const fn attribution(mut self, attribution: &'a str) -> Self {
        self.attribution = Some(attribution);
        self
    }

    #[must_use]
    pub const fn fetches_optional(mut self, fetches_optional: bool) -> Self {
        self.fetches_optional = Some(fetches_optional);
        self
    }
}

/// Answer passed to [`TileRequest::deliver`].
#[derive(Clone, Copy, Debug)]
pub enum TileResponse<'a> {
    /// UTF-8 GeoJSON payload for a geometry source.
    GeoJson { json: &'a str, times: TileTimes },
    /// Mapbox Vector Tile bytes for a geometry source; empty delivers an empty tile.
    Mvt { bytes: &'a [u8], times: TileTimes },
    /// MapLibre Tile bytes for a geometry source; empty delivers an empty tile.
    Mlt { bytes: &'a [u8], times: TileTimes },
    /// Encoded image bytes (PNG, JPEG, or WebP) for a raster or raster-dem source.
    EncodedImage { bytes: &'a [u8], times: TileTimes },
    /// Valid empty tile for any source kind.
    Empty { times: TileTimes },
    /// No tile at this ID; allows the map to fall back to ancestor tiles.
    Missing,
    /// Tile load failure with message and retry flag.
    Error { message: &'a str, retrying: bool },
}

impl<'a> TileResponse<'a> {
    #[must_use]
    pub const fn geojson(json: &'a str) -> Self {
        Self::GeoJson { json, times: TileTimes { modified_unix_ms: None, expires_unix_ms: None } }
    }

    #[must_use]
    pub const fn mvt(bytes: &'a [u8]) -> Self {
        Self::Mvt { bytes, times: TileTimes { modified_unix_ms: None, expires_unix_ms: None } }
    }

    #[must_use]
    pub const fn mlt(bytes: &'a [u8]) -> Self {
        Self::Mlt { bytes, times: TileTimes { modified_unix_ms: None, expires_unix_ms: None } }
    }

    #[must_use]
    pub const fn encoded_image(bytes: &'a [u8]) -> Self {
        Self::EncodedImage { bytes, times: TileTimes { modified_unix_ms: None, expires_unix_ms: None } }
    }

    #[must_use]
    pub const fn empty() -> Self {
        Self::Empty { times: TileTimes { modified_unix_ms: None, expires_unix_ms: None } }
    }

    #[must_use]
    pub const fn error(message: &'a str, retrying: bool) -> Self {
        Self::Error { message, retrying }
    }
}

/// Borrowed metadata passed to [`SourcePlugin::fetch_tile`].
#[derive(Clone, Copy, Debug)]
pub struct TileFetchInfo<'a> {
    pub source_id: &'a str,
    pub options_json: &'a str,
    pub tile_id: CanonicalTileId,
    pub necessity: TileNecessity,
}

/// Borrowed metadata passed to [`SourcePlugin::cancel_tile`].
#[derive(Clone, Copy, Debug)]
pub struct TileCancelInfo<'a> {
    pub source_id: &'a str,
    pub options_json: &'a str,
    pub tile_id: CanonicalTileId,
}

// ---------------------------------------------------------------------------
// Async TileRequest RAII handle
// ---------------------------------------------------------------------------

/// Owned async tile delivery handle passed to [`SourcePlugin::fetch_tile`].
///
/// May be sent to any thread and answered asynchronously via [`Self::deliver`].
/// Dropping without answering releases the request cleanly (treated by the
/// renderer as missing/cancelled).
#[derive(Debug)]
pub struct TileRequest {
    backend: Box<dyn TileRequestBackend>,
}

impl TileRequest {
    #[doc(hidden)]
    #[must_use]
    pub fn from_backend(backend: Box<dyn TileRequestBackend>) -> Self {
        Self { backend }
    }

    /// Delivers `response` to the renderer and consumes this request.
    pub fn deliver(self, response: TileResponse<'_>) -> Result<()> {
        self.backend.deliver(response)
    }
}

// ---------------------------------------------------------------------------
// SourcePlugin trait
// ---------------------------------------------------------------------------

/// Custom tile source type implemented against the MapLibre Plugin SDK.
pub trait SourcePlugin: Send + Sync + 'static {
    /// Returns the source type's name, data kind, and default tiling options.
    fn options(&self) -> SourceTypeOptions<'_>;

    /// Called when the renderer needs a tile.
    ///
    /// Answer synchronously or move `request` to another thread/task and call
    /// [`TileRequest::deliver`].
    fn fetch_tile(&self, info: TileFetchInfo<'_>, request: TileRequest);

    /// Called when the renderer no longer needs a previously requested tile.
    fn cancel_tile(&self, _info: TileCancelInfo<'_>) {}
}