martin-core 0.11.1

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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
//! Sprite processing and serving for map tile rendering.
//!
//! Generates spritesheets from SVG files with support for high-DPI (@2x) and
//! SDF (Signed Distance Field) sprites for dynamic styling.
//!
//! # Usage
//!
//! ```rust,no_run
//! # async fn foo() {
//! use martin_core::sprites::SpriteSources;
//! use std::path::PathBuf;
//!
//! let mut sources = SpriteSources::default();
//! sources.add_source("icons".to_string(), PathBuf::from("/path/to/svg/directory"));
//! let spritesheet = sources.get_sprites("icons@2x", false).await.unwrap();
//! # }
//! ```

use std::collections::BTreeMap;
use std::fmt::Debug;
use std::num::NonZeroUsize;
use std::path::{Path, PathBuf};

use chrono::{DateTime, Utc};
use dashmap::{DashMap, Entry};
use futures::stream::{self, StreamExt as _, TryStreamExt as _};
use serde::{Deserialize, Serialize};
use serde_with::skip_serializing_none;
pub use spreet::Spritesheet;
use spreet::resvg::usvg::{Options, Tree};
use spreet::{Sprite, SpritesheetBuilder, sprite_name as spreet_sprite_name};
use tokio::io::AsyncReadExt as _;
use tracing::{info, instrument, warn};

use self::SpriteError::{IoError, SpriteInstError, SpriteParsingError, SpriteProcessingError};
use crate::walk_files;

const SVG_EXTENSIONS: &[&str] = &["svg"];

/// Maximum number of distinct sprite source ids accepted in a single request.
///
/// Bounds the amount of per-request work (file reads, SVG parses, rasterization)
/// an attacker can trigger by stuffing a request path with many ids.
const MAX_SPRITE_IDS_PER_REQUEST: usize = 128;

/// Maximum number of SVGs parsed and rasterized concurrently while building one spritesheet.
const MAX_CONCURRENT_SPRITE_PARSES: usize = 16;

fn discover_svgs(path: &Path) -> Result<Vec<PathBuf>, SpriteError> {
    walk_files(path, SVG_EXTENSIONS).map_err(|e| IoError(e.into(), path.to_path_buf()))
}

/// `spreet::sprite_name` joins a nested sprite's directory onto its file stem with the
/// platform separator; the name is a URL path segment, so keep it `/`-joined everywhere.
fn sprite_name(path: &Path, base_path: &Path) -> spreet::SpreetResult<String> {
    spreet_sprite_name(path, base_path).map(|name| name.replace(std::path::MAIN_SEPARATOR, "/"))
}

/// Splits a comma-separated, optionally `@2x`-suffixed sprite id list from a
/// request path into the requested pixel ratio and a deduplicated, sorted
/// list of source ids.
///
/// Sorting and deduplicating here (rather than only at spritesheet-build
/// time) means equivalent requests - regardless of id order or repeat count
/// - do the same amount of work and can share one cache entry.
fn split_and_dedup_ids(ids: &str) -> (Vec<&str>, u8) {
    let (ids, dpi) = if let Some(ids) = ids.strip_suffix("@2x") {
        (ids, 2)
    } else {
        (ids, 1)
    };

    let mut unique_ids: Vec<&str> = ids.split(',').collect();
    unique_ids.sort_unstable();
    unique_ids.dedup();

    (unique_ids, dpi)
}

/// Normalizes a request-path sprite id list so that equivalent requests
/// (different id order, repeated ids) share one cache entry instead of
/// each producing a distinct cache miss.
#[must_use]
pub fn normalize_sprite_ids(ids: &str) -> String {
    let (unique_ids, dpi) = split_and_dedup_ids(ids);
    let joined = unique_ids.join(",");
    if dpi == 2 {
        format!("{joined}@2x")
    } else {
        joined
    }
}

mod error;
pub use error::SpriteError;

mod cache;
pub use cache::{NO_SPRITE_CACHE, OptSpriteCache, SpriteCache, SpriteCacheKey};

/// Sprite source metadata.
#[skip_serializing_none]
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(
    feature = "unstable-schemas",
    derive(schemars::JsonSchema, utoipa::ToSchema)
)]
pub struct CatalogSpriteEntry {
    /// Available sprite image names.
    pub images: Vec<String>,
    /// Total size of the spritesheet in bytes.
    // utoipa 5.4 has no `PartialSchema` impl for `NonZeroUsize`, so describe
    // the field as a positive integer for the OpenAPI side; serde still
    // serializes the inner usize.
    #[cfg_attr(feature = "unstable-schemas", schema(value_type = u64, minimum = 1))]
    pub size_in_bytes: Option<NonZeroUsize>,
    /// Timestamp of the spritesheet's last modification.
    pub last_modified_at: Option<DateTime<Utc>>,
}

/// Catalog mapping sprite names to metadata (e.g., "icons" -> [`CatalogSpriteEntry`]).
pub type SpriteCatalog = BTreeMap<String, CatalogSpriteEntry>;

/// Thread-safe sprite source manager for serving sprites as `.png` or `.json`.
#[derive(Debug, Clone, Default)]
pub struct SpriteSources(DashMap<String, SpriteSource>);

impl SpriteSources {
    /// Returns a catalog of all sprite sources.
    pub fn get_catalog(&self) -> Result<SpriteCatalog, SpriteError> {
        // TODO: all sprite generation should be pre-cached
        let mut entries = SpriteCatalog::new();
        for source in &self.0 {
            let paths = discover_svgs(&source.path)?;
            let mut images = Vec::with_capacity(paths.len());
            for path in paths {
                images.push(
                    sprite_name(&path, &source.path)
                        .map_err(|e| SpriteProcessingError(e, source.path.clone()))?,
                );
            }
            images.sort();
            entries.insert(
                source.key().clone(),
                CatalogSpriteEntry {
                    images,
                    // FIXME: render once and report the encoded PNG byte count.
                    size_in_bytes: None,
                    // FIXME: stat the SVG inputs and surface their newest mtime.
                    last_modified_at: None,
                },
            );
        }
        Ok(entries)
    }

    /// Adds a sprite source directory containing SVG files.
    /// Files are ignored - only directories accepted. Duplicates ignored with warning.
    pub fn add_source(&self, id: String, path: PathBuf) {
        let disp_path = path.display();
        if path.is_file() {
            warn!(
                source.id = %id,
                sprite.path = %disp_path,
                "Ignoring non-directory sprite source"
            );
        } else {
            match self.0.entry(id) {
                Entry::Occupied(v) => {
                    warn!(
                        source.id = %v.key(),
                        sprite.path.kept = %v.get().path.display(),
                        sprite.path.dropped = %disp_path,
                        "Ignoring duplicate sprite source: already configured for another path"
                    );
                }
                Entry::Vacant(v) => {
                    info!(
                        source.id = %v.key(),
                        sprite.path = %disp_path,
                        "Configured sprite source"
                    );
                    if let Ok(paths) = discover_svgs(&path)
                        && paths.is_empty()
                    {
                        warn!(
                            source.id = %v.key(),
                            sprite.path = %disp_path,
                            "No sprite SVG files found in directory to generate spritesheets from. \
                             Sprite requests for this source will fail, until at least one svg is present."
                        );
                    }
                    v.insert(SpriteSource { path });
                }
            }
        }
    }

    /// Generates a spritesheet from comma-separated sprite source IDs.
    ///
    /// Append "@2x" for high-DPI sprites.
    /// Set `as_sdf` for SDF sprites.
    #[instrument(
        level = "debug",
        skip(self),
        fields(source.ids = %ids, sprite.sdf = as_sdf),
        err(Debug),
    )]
    pub async fn get_sprites(&self, ids: &str, as_sdf: bool) -> Result<Spritesheet, SpriteError> {
        let (unique_ids, dpi) = split_and_dedup_ids(ids);

        if unique_ids.len() > MAX_SPRITE_IDS_PER_REQUEST {
            return Err(SpriteError::TooManySpriteIds {
                requested: unique_ids.len(),
                max: MAX_SPRITE_IDS_PER_REQUEST,
            });
        }

        let sprite_ids = unique_ids
            .into_iter()
            .map(|id| self.get(id))
            .collect::<Result<Vec<_>, SpriteError>>()?;

        get_spritesheet(sprite_ids.iter(), dpi, as_sdf).await
    }

    fn get(&self, id: &str) -> Result<SpriteSource, SpriteError> {
        match self.0.get(id) {
            Some(v) => Ok(v.clone()),
            None => Err(SpriteError::SpriteNotFound(id.to_owned())),
        }
    }
}

/// Sprite source directory.
#[derive(Clone, Debug)]
pub struct SpriteSource {
    path: PathBuf,
}

/// Parses SVG file into sprite.
async fn parse_sprite(
    name: String,
    path: PathBuf,
    pixel_ratio: u8,
    as_sdf: bool,
) -> Result<(String, Sprite), SpriteError> {
    let on_err = |e| IoError(e, path.clone());

    let mut file = tokio::fs::File::open(&path).await.map_err(on_err)?;

    let mut buffer = Vec::new();
    file.read_to_end(&mut buffer).await.map_err(on_err)?;

    let tree = Tree::from_data(&buffer, &Options::default())
        .map_err(|e| SpriteParsingError(e, path.clone()))?;

    let sprite = if as_sdf {
        Sprite::new_sdf(tree, pixel_ratio)
    } else {
        Sprite::new(tree, pixel_ratio)
    };
    let sprite = sprite.ok_or_else(|| SpriteInstError(path.clone()))?;

    Ok((name, sprite))
}

/// Generates spritesheet from sprite sources.
#[instrument(
    level = "debug",
    skip_all,
    fields(sprite.pixel_ratio = pixel_ratio, sprite.sdf = as_sdf),
    err(Debug),
)]
pub async fn get_spritesheet(
    sources: impl Iterator<Item = &SpriteSource>,
    pixel_ratio: u8,
    as_sdf: bool,
) -> Result<Spritesheet, SpriteError> {
    // Asynchronously load all SVG files from the given sources
    let mut futures = Vec::new();
    for source in sources {
        let paths = discover_svgs(&source.path)?;
        // SpritesheetBuilder::generate will return None if the folder does not contain any SVGs
        if paths.is_empty() {
            return Err(SpriteError::NoSpriteFilesFound(source.path.clone()));
        }
        for path in paths {
            let name = sprite_name(&path, &source.path)
                .map_err(|e| SpriteProcessingError(e, source.path.clone()))?;
            futures.push(parse_sprite(name, path, pixel_ratio, as_sdf));
        }
    }
    let sprites: Vec<(String, Sprite)> = stream::iter(futures)
        .buffer_unordered(MAX_CONCURRENT_SPRITE_PARSES)
        .try_collect()
        .await?;
    let mut builder = SpritesheetBuilder::new();
    if as_sdf {
        builder.make_sdf();
    }
    builder.sprites(sprites.into_iter().collect());

    // TODO: decide if this is needed and/or configurable
    // builder.make_unique();

    builder
        .generate()
        .ok_or(SpriteError::UnableToGenerateSpritesheet)
}

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

    use super::*;

    #[test]
    fn normalize_sprite_ids_collapses_order_and_duplicates() {
        assert_eq!(normalize_sprite_ids("b,a,b"), "a,b");
        assert_eq!(normalize_sprite_ids("b,a@2x"), "a,b@2x");
        assert_eq!(normalize_sprite_ids("a"), "a");
    }

    #[tokio::test]
    async fn duplicate_ids_are_deduplicated_before_rendering() {
        let sprites = SpriteSources::default();
        sprites.add_source(
            "src1".to_owned(),
            PathBuf::from("../tests/fixtures/sprites/src1"),
        );

        let single = sprites.get_sprites("src1", false).await.unwrap();
        let repeated_ids = vec!["src1"; 50].join(",");
        let repeated = sprites.get_sprites(&repeated_ids, false).await.unwrap();

        assert_eq!(
            serde_json::to_value(single.get_index()).unwrap(),
            serde_json::to_value(repeated.get_index()).unwrap()
        );
        assert_eq!(single.encode_png().unwrap(), repeated.encode_png().unwrap());
    }

    #[tokio::test]
    async fn too_many_ids_are_rejected_before_any_work() {
        let sprites = SpriteSources::default();
        sprites.add_source(
            "src1".to_owned(),
            PathBuf::from("../tests/fixtures/sprites/src1"),
        );

        let ids = (0..=MAX_SPRITE_IDS_PER_REQUEST)
            .map(|i| format!("nonexistent{i}"))
            .collect::<Vec<_>>()
            .join(",");

        let Err(err) = sprites.get_sprites(&ids, false).await else {
            panic!("expected TooManySpriteIds, got Ok");
        };
        assert_matches!(err, SpriteError::TooManySpriteIds { .. });
    }

    #[tokio::test]
    async fn exactly_max_ids_is_not_rejected_by_the_count_check() {
        let sprites = SpriteSources::default();

        let ids = (0..MAX_SPRITE_IDS_PER_REQUEST)
            .map(|i| format!("nonexistent{i}"))
            .collect::<Vec<_>>()
            .join(",");

        let Err(err) = sprites.get_sprites(&ids, false).await else {
            panic!("expected SpriteNotFound, got Ok");
        };
        assert_matches!(err, SpriteError::SpriteNotFound(_));
    }

    #[tokio::test]
    async fn sprites() {
        let sprites = SpriteSources::default();
        sprites.add_source(
            "src1".to_owned(),
            PathBuf::from("../tests/fixtures/sprites/src1"),
        );
        sprites.add_source(
            "src2".to_owned(),
            PathBuf::from("../tests/fixtures/sprites/src2"),
        );

        assert_eq!(sprites.0.len(), 2);

        for generate_sdf in [true, false] {
            let paths = sprites
                .0
                .iter()
                .map(|v| v.value().clone())
                .collect::<Vec<_>>();
            test_src(paths.iter(), 1, "all_1", generate_sdf).await;
            test_src(paths.iter(), 2, "all_2", generate_sdf).await;

            let src1_path = sprites.get("src1").into_iter().collect::<Vec<_>>();
            test_src(src1_path.iter(), 1, "src1_1", generate_sdf).await;
            test_src(src1_path.iter(), 2, "src1_2", generate_sdf).await;

            let src2_path = sprites.get("src2").into_iter().collect::<Vec<_>>();
            test_src(src2_path.iter(), 1, "src2_1", generate_sdf).await;
            test_src(src2_path.iter(), 2, "src2_2", generate_sdf).await;
        }
    }

    #[cfg(unix)]
    #[test]
    fn k8s_configmap_symlinks_yield_clean_sprite_names() {
        use std::fs::{create_dir_all, write};
        use std::os::unix::fs::symlink;

        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path();
        let real_dir = root.join("..2024_05_17_17_57_51.390489675");
        create_dir_all(&real_dir).unwrap();
        let svg = b"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"1\" height=\"1\"/>";
        write(real_dir.join("foo.svg"), svg).unwrap();
        write(real_dir.join("bar.svg"), svg).unwrap();
        symlink("..2024_05_17_17_57_51.390489675", root.join("..data")).unwrap();
        symlink("..data/foo.svg", root.join("foo.svg")).unwrap();
        symlink("..data/bar.svg", root.join("bar.svg")).unwrap();

        let sprites = SpriteSources::default();
        sprites.add_source("foobar".to_owned(), root.to_path_buf());

        let catalog = sprites.get_catalog().expect("catalog");
        let entry = catalog.get("foobar").expect("foobar source registered");
        assert_eq!(
            entry.images,
            vec!["bar".to_owned(), "foo".to_owned()],
            "expected plain sprite names without dotfile directory prefixes"
        );
    }

    #[test]
    fn a_nested_sprite_name_is_forward_slash_joined_on_every_platform() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let sub = tmp.path().join("sub");
        std::fs::create_dir_all(&sub).unwrap();
        let svg = b"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"1\" height=\"1\"/>";
        std::fs::write(sub.join("circle.svg"), svg).unwrap();

        let sprites = SpriteSources::default();
        sprites.add_source("nested".to_owned(), tmp.path().to_path_buf());

        let catalog = sprites.get_catalog().expect("catalog");
        let entry = catalog.get("nested").expect("nested source registered");
        assert_eq!(
            entry.images,
            vec!["sub/circle".to_owned()],
            "nested sprite names must use `/` even on windows, since they are URL path segments"
        );
    }

    #[tokio::test]
    async fn directory_without_svgs_yields_helpful_error() {
        let tmp = tempfile::tempdir().expect("tempdir");
        std::fs::write(tmp.path().join("sprite.json"), b"{}").unwrap();
        std::fs::write(tmp.path().join("sprite.png"), b"\x89PNG\r\n").unwrap();

        let sprites = SpriteSources::default();
        sprites.add_source("bad".to_owned(), tmp.path().to_path_buf());

        let source = sprites.get("bad").expect("source registered");
        let Err(err) = get_spritesheet([source].iter(), 1, false).await else {
            panic!("expected NoSpriteFilesFound, got Ok");
        };

        assert_matches!(err, SpriteError::NoSpriteFilesFound(_));
    }

    async fn test_src(
        sources: impl Iterator<Item = &SpriteSource>,
        pixel_ratio: u8,
        filename: &str,
        generate_sdf: bool,
    ) {
        let sprites = get_spritesheet(sources, pixel_ratio, generate_sdf)
            .await
            .unwrap();
        let filename = if generate_sdf {
            format!("{filename}_sdf")
        } else {
            filename.to_owned()
        };
        insta::assert_json_snapshot!(format!("{filename}.json"), sprites.get_index());
        let png = sprites.encode_png().unwrap();
        insta::assert_binary_snapshot!(&format!("{filename}.png"), png);
    }
}