martin 1.10.1

Blazing fast and lightweight tile server with PostGIS, MBTiles, and PMTiles support
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
495
496
497
498
499
500
501
#[cfg(all(feature = "mlt", feature = "_tiles"))]
use mlt_core::encoder::EncoderConfig;
#[cfg(all(feature = "mlt", feature = "_tiles"))]
use serde::{Deserialize, Serialize};

#[cfg(all(feature = "mlt", feature = "_tiles"))]
use crate::config::file::UnrecognizedValues;
#[cfg(all(feature = "mlt", feature = "_tiles"))]
use crate::config::primitives::AutoOption;

/// Internal carrier for resolved per-source processing settings.
///
/// Not serialized directly - config files use `convert_to_mlt` / `convert_to_mvt`.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ProcessConfig {
    #[cfg(all(feature = "mlt", feature = "_tiles"))]
    pub convert_to_mlt: Option<MltProcessConfig>,
    #[cfg(all(feature = "mlt", feature = "_tiles"))]
    pub convert_to_mvt: Option<MvtProcessConfig>,
}

/// Configuration for MVT-to-MLT format conversion.
///
/// Three-state value parsed from YAML:
/// - `"auto"` / `"default"` / `true` - use `mlt-core`'s default `EncoderConfig`
/// - `"disabled"` / `"off"` / `"no"` / `false` - explicitly skip conversion
/// - An object with explicit fields - override specific encoder settings
#[cfg(all(feature = "mlt", feature = "_tiles"))]
pub type MltProcessConfig = AutoOption<MltEncoderConfig>;

/// Configuration for MLT-to-MVT format conversion.
#[cfg(all(feature = "mlt", feature = "_tiles"))]
pub type MvtProcessConfig = AutoOption<MvtEncoderConfig>;

/// Explicit encoder configuration for MVT conversion.
///
/// The MVT encoder currently has no tunable knobs, so any keys provided are
/// captured here verbatim and surfaced through the established unrecognized-key
/// warning path so users get a typo hint instead of silent acceptance.
#[cfg(all(feature = "mlt", feature = "_tiles"))]
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "unstable-schemas", derive(schemars::JsonSchema))]
#[serde(transparent)]
pub struct MvtEncoderConfig(pub serde_json::Map<String, serde_json::Value>);

#[cfg(all(feature = "mlt", feature = "_tiles"))]
impl MvtEncoderConfig {
    /// Keys that were present in the config but not recognized as encoder settings.
    pub(crate) fn unrecognized_keys(&self) -> impl Iterator<Item = &str> {
        self.0.keys().map(String::as_str)
    }
}

/// Explicit encoder configuration for MLT conversion.
/// All fields are optional; unset fields use `mlt-core`'s defaults.
#[cfg(all(feature = "mlt", feature = "_tiles"))]
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "unstable-schemas", derive(schemars::JsonSchema))]
pub struct MltEncoderConfig {
    /// Generate tessellation data for polygons and multi-polygons.
    pub tessellate: Option<bool>,
    /// Try sorting features by Z-order (Morton) curve index of their first vertex.
    pub try_spatial_morton_sort: Option<bool>,
    /// Try sorting features by Hilbert curve index of their first vertex.
    pub try_spatial_hilbert_sort: Option<bool>,
    /// Try sorting features by their feature ID in ascending order.
    pub try_id_sort: Option<bool>,
    /// Allow FSST string compression.
    pub allow_fsst: Option<bool>,
    /// Allow `FastPFOR` integer compression.
    pub allow_fpf: Option<bool>,
    /// Allow string grouping into shared dictionaries.
    pub allow_shared_dict: Option<bool>,

    #[serde(flatten, skip_serializing)]
    #[cfg_attr(feature = "unstable-schemas", schemars(skip))]
    pub unrecognized: UnrecognizedValues,
}

#[cfg(all(feature = "mlt", feature = "_tiles"))]
impl MltEncoderConfig {
    /// Keys that were present in the config but not recognized as encoder settings.
    pub(crate) fn unrecognized_keys(&self) -> impl Iterator<Item = &str> {
        self.unrecognized.keys().map(String::as_str)
    }
}

/// Applying `MltEncoderConfig` overrides on top of `EncoderConfig` defaults.
///
/// Uses exhaustive destructuring of both structs so that adding a field
/// to either `MltEncoderConfig` or `EncoderConfig` causes a compile error
/// until this conversion is updated.
#[cfg(all(feature = "mlt", feature = "_tiles"))]
impl From<MltEncoderConfig> for EncoderConfig {
    fn from(src: MltEncoderConfig) -> Self {
        // Destructure both so new fields cause a compile error.
        let MltEncoderConfig {
            tessellate,
            try_spatial_morton_sort,
            try_spatial_hilbert_sort,
            try_id_sort,
            allow_fsst,
            allow_fpf,
            allow_shared_dict,
            // Unrecognized keys are reported via the warning path during finalize();
            // they intentionally don't influence the resulting EncoderConfig.
            unrecognized: _,
        } = src;

        Self {
            tessellate: tessellate.unwrap_or(Self::default().tessellate),
            try_spatial_morton_sort: try_spatial_morton_sort
                .unwrap_or(Self::default().try_spatial_morton_sort),
            try_spatial_hilbert_sort: try_spatial_hilbert_sort
                .unwrap_or(Self::default().try_spatial_hilbert_sort),
            try_id_sort: try_id_sort.unwrap_or(Self::default().try_id_sort),
            allow_fsst: allow_fsst.unwrap_or(Self::default().allow_fsst),
            allow_fpf: allow_fpf.unwrap_or(Self::default().allow_fpf),
            allow_shared_dict: allow_shared_dict.unwrap_or(Self::default().allow_shared_dict),
        }
    }
}

/// Resolve effective process config using full-override semantics:
/// per-source > source-type > global > default.
#[must_use]
pub fn resolve_process_config(
    global: &ProcessConfig,
    source_type: &ProcessConfig,
    per_source: &ProcessConfig,
) -> ProcessConfig {
    let default = ProcessConfig::default();
    if *per_source != default {
        per_source.clone()
    } else if *source_type != default {
        source_type.clone()
    } else {
        global.clone()
    }
}

#[cfg(test)]
mod tests {
    #[cfg(all(feature = "mlt", feature = "_tiles"))]
    use indoc::indoc;

    use super::*;

    #[cfg(all(feature = "mlt", feature = "_tiles"))]
    #[test]
    fn parse_mlt_auto_string() {
        let cfg: MltProcessConfig = serde_yaml::from_str("auto").unwrap();
        assert_eq!(cfg, MltProcessConfig::Auto);
    }

    #[cfg(all(feature = "mlt", feature = "_tiles"))]
    #[test]
    fn parse_mlt_explicit_empty() {
        let cfg: MltProcessConfig = serde_yaml::from_str("{}").unwrap();
        assert_eq!(cfg, MltProcessConfig::Explicit(MltEncoderConfig::default()));
    }

    #[cfg(all(feature = "mlt", feature = "_tiles"))]
    #[test]
    fn parse_mlt_explicit_with_overrides() {
        let cfg: MltProcessConfig = serde_yaml::from_str(indoc! {"
            tessellate: true
            allow_fsst: false
        "})
        .unwrap();
        assert_eq!(
            cfg,
            MltProcessConfig::Explicit(MltEncoderConfig {
                tessellate: Some(true),
                allow_fsst: Some(false),
                ..Default::default()
            })
        );
    }

    #[cfg(all(feature = "mlt", feature = "_tiles"))]
    #[test]
    fn serde_round_trip_auto() {
        let cfg = MltProcessConfig::Auto;
        let yaml = serde_yaml::to_string(&cfg).unwrap();
        insta::assert_snapshot!(yaml, @"auto");
        let parsed: MltProcessConfig = serde_yaml::from_str(&yaml).unwrap();
        assert_eq!(cfg, parsed);
    }

    #[cfg(all(feature = "mlt", feature = "_tiles"))]
    #[test]
    fn serde_round_trip_disabled() {
        let cfg = MltProcessConfig::Disabled;
        let yaml = serde_yaml::to_string(&cfg).unwrap();
        insta::assert_snapshot!(yaml, @"disabled");
        let parsed: MltProcessConfig = serde_yaml::from_str(&yaml).unwrap();
        assert_eq!(cfg, parsed);
    }

    #[cfg(all(feature = "mlt", feature = "_tiles"))]
    #[test]
    fn serde_round_trip_explicit() {
        let cfg = MltProcessConfig::Explicit(MltEncoderConfig {
            tessellate: Some(true),
            ..Default::default()
        });
        let yaml = serde_yaml::to_string(&cfg).unwrap();
        let parsed: MltProcessConfig = serde_yaml::from_str(&yaml).unwrap();
        assert_eq!(cfg, parsed);
    }

    #[cfg(all(feature = "mlt", feature = "_tiles"))]
    #[test]
    fn parse_mlt_invalid_string() {
        let result = serde_yaml::from_str::<MltProcessConfig>("invalid");
        result.unwrap_err();
    }

    #[cfg(all(feature = "mlt", feature = "_tiles"))]
    #[test]
    fn parse_mlt_invalid_type() {
        let result = serde_yaml::from_str::<MltProcessConfig>("123");
        result.unwrap_err();
    }

    #[cfg(all(feature = "mlt", feature = "_tiles"))]
    #[test]
    fn render_failure_mlt_unknown_string() {
        use crate::config::test_helpers::render_failure;
        insta::assert_snapshot!(render_failure(indoc! {"
                convert_to_mlt: atuo
            "}), @r#"
          × invalid value: string "atuo", expected a string ("auto", "enabled",
          │ "disabled"), a boolean, or a map of settings
           ╭─[config.yaml:1:1]
         1 │ convert_to_mlt: atuo
           · ───────┬──────
           ·        ╰── invalid value: string "atuo", expected a string ("auto", "enabled", "disabled"), a boolean, or a map of settings
           ╰────
        "#);
    }

    #[cfg(all(feature = "mlt", feature = "_tiles"))]
    #[test]
    fn render_failure_mlt_integer() {
        use crate::config::test_helpers::render_failure;
        insta::assert_snapshot!(render_failure(indoc! {"
                convert_to_mlt: 42
            "}), @r#"
          × invalid type: integer `42`, expected a string ("auto", "enabled",
          │ "disabled"), a boolean, or a map of settings
           ╭─[config.yaml:1:1]
         1 │ convert_to_mlt: 42
           · ───────┬──────
           ·        ╰── invalid type: integer `42`, expected a string ("auto", "enabled", "disabled"), a boolean, or a map of settings
           ╰────
        "#);
    }

    /// Inner-field errors must point at the *value*, not the outer `convert_to_mlt:` line -
    /// proves the explicit branch hands the saphyr deserializer to `MltEncoderConfig`
    /// instead of routing through a `serde_yaml::Value`.
    #[cfg(all(feature = "mlt", feature = "_tiles"))]
    #[test]
    fn render_failure_mlt_nested_field_bad_type() {
        use crate::config::test_helpers::render_failure;
        insta::assert_snapshot!(render_failure(indoc! {"
                convert_to_mlt:
                  tessellate: yes-please
            "}), @r"
          × invalid boolean
           ╭─[config.yaml:2:15]
         1 │ convert_to_mlt:
         2 │   tessellate: yes-please
           ·               ─────┬────
           ·                    ╰── invalid boolean
           ╰────
        ");
    }

    #[cfg(all(feature = "mlt", feature = "_tiles"))]
    #[test]
    fn resolve_per_source_disabled_overrides_global_auto() {
        let global = ProcessConfig {
            convert_to_mlt: Some(MltProcessConfig::Auto),
            convert_to_mvt: None,
        };
        let per_source = ProcessConfig {
            convert_to_mlt: Some(MltProcessConfig::Disabled),
            convert_to_mvt: None,
        };
        let resolved = resolve_process_config(&global, &ProcessConfig::default(), &per_source);
        assert_eq!(resolved.convert_to_mlt, Some(MltProcessConfig::Disabled));
    }

    #[cfg(all(feature = "mlt", feature = "_tiles"))]
    #[test]
    fn resolve_per_source_overrides_all() {
        let global = ProcessConfig {
            convert_to_mlt: Some(MltProcessConfig::Auto),
            convert_to_mvt: None,
        };
        let source_type = ProcessConfig {
            convert_to_mlt: None,
            convert_to_mvt: Some(MvtProcessConfig::Auto),
        };
        let per_source = ProcessConfig {
            convert_to_mlt: Some(MltProcessConfig::Explicit(MltEncoderConfig {
                tessellate: Some(true),
                ..Default::default()
            })),
            convert_to_mvt: None,
        };

        let resolved = resolve_process_config(&global, &source_type, &per_source);
        assert_eq!(resolved, per_source);
    }

    #[cfg(all(feature = "mlt", feature = "_tiles"))]
    #[test]
    fn resolve_source_type_overrides_global() {
        let global = ProcessConfig {
            convert_to_mlt: Some(MltProcessConfig::Auto),
            convert_to_mvt: None,
        };
        let source_type = ProcessConfig {
            convert_to_mlt: None,
            convert_to_mvt: Some(MvtProcessConfig::Auto),
        };

        let resolved = resolve_process_config(&global, &source_type, &ProcessConfig::default());
        assert_eq!(resolved, source_type);
    }

    #[cfg(all(feature = "mlt", feature = "_tiles"))]
    #[test]
    fn resolve_global_used_as_fallback() {
        let global = ProcessConfig {
            convert_to_mlt: Some(MltProcessConfig::Auto),
            convert_to_mvt: None,
        };

        let resolved = resolve_process_config(
            &global,
            &ProcessConfig::default(),
            &ProcessConfig::default(),
        );
        assert_eq!(resolved, global);
    }

    #[test]
    fn resolve_default_when_all_none() {
        let resolved = resolve_process_config(
            &ProcessConfig::default(),
            &ProcessConfig::default(),
            &ProcessConfig::default(),
        );
        assert_eq!(resolved, ProcessConfig::default());
    }

    #[cfg(all(feature = "mlt", feature = "_tiles"))]
    #[test]
    fn mlt_encoder_captures_unrecognized_keys() {
        let cfg: MltProcessConfig = serde_yaml::from_str(indoc! {"
            tessellate: true
            unknown_knob: 42
            another_typo: hi
        "})
        .unwrap();
        let MltProcessConfig::Explicit(inner) = cfg else {
            panic!("expected explicit MltEncoderConfig");
        };
        assert_eq!(inner.tessellate, Some(true));
        let mut keys: Vec<&str> = inner.unrecognized_keys().collect();
        keys.sort_unstable();
        assert_eq!(keys, vec!["another_typo", "unknown_knob"]);
    }

    #[cfg(all(feature = "mlt", feature = "_tiles"))]
    #[test]
    fn mvt_encoder_captures_all_keys_as_unrecognized() {
        // MVT has no encoder knobs yet; every supplied key is unrecognized.
        let cfg: MvtProcessConfig = serde_yaml::from_str(indoc! {"
            anything: 1
            else: yes
        "})
        .unwrap();
        let MvtProcessConfig::Explicit(inner) = cfg else {
            panic!("expected explicit MvtEncoderConfig");
        };
        let mut keys: Vec<&str> = inner.unrecognized_keys().collect();
        keys.sort_unstable();
        assert_eq!(keys, vec!["anything", "else"]);
    }

    /// Even an empty map should produce `Explicit(MvtEncoderConfig::default())`,
    /// matching the existing behavior for the MLT side.
    #[cfg(all(feature = "mlt", feature = "_tiles"))]
    #[test]
    fn parse_mvt_explicit_empty() {
        let cfg: MvtProcessConfig = serde_yaml::from_str("{}").unwrap();
        assert_eq!(cfg, MvtProcessConfig::Explicit(MvtEncoderConfig::default()));
    }

    /// Unknown keys inside `convert_to_mlt` should bubble up through
    /// `PmtConfig::get_unrecognized_keys` with the proper prefix so the existing
    /// warning loop in `Config::finalize` flags them.
    #[cfg(all(feature = "mlt", feature = "pmtiles"))]
    #[test]
    fn pmt_config_propagates_mlt_unrecognized_keys() {
        use crate::config::file::ConfigurationLivecycleHooks as _;
        use crate::config::file::pmtiles::PmtConfig;

        let cfg: PmtConfig = serde_yaml::from_str(indoc! {"
            convert_to_mlt:
              tessellate: true
              bogus_option: 1
        "})
        .unwrap();
        let keys = cfg.get_unrecognized_keys();
        assert!(
            keys.contains("convert_to_mlt.bogus_option"),
            "expected convert_to_mlt.bogus_option in {keys:?}"
        );
    }

    /// Unknown keys inside `convert_to_mvt` (MVT has no real knobs) should bubble
    /// up through `MbtConfig::get_unrecognized_keys`.
    #[cfg(all(feature = "mlt", feature = "mbtiles"))]
    #[test]
    fn mbt_config_propagates_mvt_unrecognized_keys() {
        use crate::config::file::ConfigurationLivecycleHooks as _;
        use crate::config::file::mbtiles::MbtConfig;

        let cfg: MbtConfig = serde_yaml::from_str(indoc! {"
            convert_to_mvt:
              not_a_real_setting: yes
        "})
        .unwrap();
        let keys = cfg.get_unrecognized_keys();
        assert!(
            keys.contains("convert_to_mvt.not_a_real_setting"),
            "expected convert_to_mvt.not_a_real_setting in {keys:?}"
        );
    }

    /// End-to-end: an unrecognized key inside `convert_to_mlt` at the top of the
    /// config file makes it into the rendered warning aggregate produced by
    /// `Config::finalize`. Needs at least one tile source so `finalize` doesn't
    /// short-circuit with `NoSources`.
    #[cfg(all(feature = "mlt", feature = "pmtiles"))]
    #[test]
    fn finalize_collects_global_convert_to_mlt_unrecognized() {
        use crate::config::file::Config;

        let mut cfg: Config = serde_yaml::from_str(indoc! {"
            pmtiles:
              paths: /tmp/never-read.pmtiles
            convert_to_mlt:
              tessellate: true
              definitely_a_typo: 1
        "})
        .unwrap();
        let keys = cfg.finalize().expect("finalize should not error");
        assert!(
            keys.contains("convert_to_mlt.definitely_a_typo"),
            "expected convert_to_mlt.definitely_a_typo in {keys:?}"
        );
    }

    /// Pins the schema shape to the wire format. With the `AutoOption` migration the
    /// schema includes string aliases for `auto`/`default`/`true`,
    /// `disabled`/`off`/`no`/`false`, a boolean shorthand, and the explicit
    /// `MltEncoderConfig` branch - four `oneOf` entries in total.
    #[cfg(all(feature = "mlt", feature = "unstable-schemas"))]
    #[test]
    fn json_schema_matches_serde_format() {
        let schema = serde_json::to_value(schemars::schema_for!(MltProcessConfig)).unwrap();
        let one_of = schema
            .get("oneOf")
            .and_then(|v| v.as_array())
            .expect("MltProcessConfig schema should be a `oneOf`");
        assert_eq!(one_of.len(), 4, "schema: {schema}");

        // The explicit branch should still reference MltEncoderConfig.
        let mut saw_encoder_ref = false;
        for entry in one_of {
            if let Some(reference) = entry.get("$ref").and_then(|v| v.as_str())
                && reference.ends_with("/MltEncoderConfig")
            {
                saw_encoder_ref = true;
            }
        }
        assert!(
            saw_encoder_ref,
            "expected $ref to MltEncoderConfig: {schema}"
        );
    }
}