martin-core 0.18.0

Basic building blocks of MapLibre's Martin tile server.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! 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 dashmap::{DashMap, Entry};
use jiff::Timestamp;
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;
/// One `MapLibre` map rendering still images.
#[cfg(all(feature = "rendering", target_os = "linux"))]
pub(crate) mod renderer;

/// A rendered tile or static image, in straight (not premultiplied) RGBA.
#[cfg(all(feature = "rendering", target_os = "linux"))]
pub type StaticImage = image::RgbaImage;
#[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, DEFAULT_STATIC_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.
    #[cfg_attr(feature = "unstable-schemas", schemars(with = "Option<String>", extend("format" = "date-time")))]
    pub last_modified_at: Option<Timestamp>,
}

/// 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<StaticImage, 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<StaticImage, 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<StaticImage, 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<StaticImage, 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 [`StyleError`] from [`RenderPools::new`] if the pools cannot start.
    #[cfg(all(feature = "rendering", target_os = "linux"))]
    pub fn enable_rendering(
        &mut self,
        workers: Option<NonZeroUsize>,
        tile_size: TileSize,
        renderers_per_worker: NonZeroUsize,
        static_renderers_per_worker: NonZeroUsize,
        ambient_cache_bytes: Option<u64>,
    ) -> Result<(), StyleError> {
        self.pools = Some(RenderPools::new(
            workers,
            tile_size,
            renderers_per_worker,
            static_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"))
        );
    }
}