martin 1.15.0

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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
#[cfg(feature = "_tiles")]
use std::collections::HashMap;
use std::ffi::OsStr;
use std::fs::File;
use std::io::prelude::*;
#[cfg(any(feature = "_tiles", feature = "sprites", feature = "fonts"))]
use std::num::NonZeroU64;
use std::path::Path;
#[cfg(any(feature = "_tiles", feature = "sprites", feature = "fonts"))]
use std::time::Duration;

#[cfg(feature = "_tiles")]
use futures::future::{BoxFuture, try_join_all};
#[cfg(feature = "_tiles")]
use martin_core::tiles::BoxedSource;
#[cfg(feature = "pmtiles")]
use martin_core::tiles::pmtiles::PmtCache;
use tracing::{info, instrument, warn};

use super::{Config, ServerState, init_aws_lc_tls, parse_base_path};
#[cfg(feature = "_tiles")]
use super::{ResolutionResult, TileSourceWarning};
use crate::StartupResult;
#[cfg(any(
    feature = "postgres",
    feature = "pmtiles",
    feature = "mbtiles",
    feature = "passthrough",
    feature = "unstable-cog",
    feature = "unstable-duckdb",
    feature = "geojson",
    feature = "sprites",
    feature = "styles",
    feature = "fonts"
))]
use crate::config::file::ConfigurationLivecycleHooks;
#[cfg(any(
    feature = "pmtiles",
    feature = "mbtiles",
    feature = "unstable-cog",
    feature = "geojson",
    feature = "sprites",
    feature = "fonts",
))]
use crate::config::file::FileConfigEnum;
#[cfg(any(
    feature = "pmtiles",
    feature = "mbtiles",
    feature = "unstable-cog",
    feature = "geojson"
))]
use crate::config::file::FileConfigSrc;
#[cfg(any(feature = "_tiles", feature = "sprites", feature = "fonts"))]
use crate::config::file::cache::{CacheConfig, SubCacheSetting};
#[cfg(feature = "_tiles")]
#[cfg(any(
    feature = "pmtiles",
    feature = "mbtiles",
    feature = "passthrough",
    feature = "unstable-cog",
    feature = "geojson"
))]
use crate::config::file::process::ProcessConfig;
#[cfg(feature = "_tiles")]
use crate::config::file::process::ResolvedProcess;
#[cfg(any(
    feature = "pmtiles",
    feature = "mbtiles",
    feature = "unstable-cog",
    feature = "geojson"
))]
use crate::config::file::resolve_files;
use crate::config::file::{CollectUnrecognizedKeys as _, ConfigFileError, ConfigFileResult};
#[cfg(feature = "_tiles")]
use crate::config::primitives::IdResolver;
#[cfg(feature = "_tiles")]
use crate::tile_source_manager::TileSourceManager;

impl Config {
    /// Apply defaults to the config, and validate if there is a connection string
    pub async fn finalize(&mut self) -> StartupResult<()> {
        if let Some(path) = &self.srv.route_prefix {
            let normalized = parse_base_path(path)?;
            // For route_prefix, an empty normalized path (from "/") means no prefix
            self.srv.route_prefix = if normalized.is_empty() {
                None
            } else {
                Some(normalized)
            };
        }
        if let Some(path) = &self.srv.base_path {
            self.srv.base_path = Some(parse_base_path(path)?);
        }
        #[cfg(feature = "postgres")]
        for pg in self.postgres.iter_mut() {
            pg.finalize().await?;
        }

        #[cfg(feature = "pmtiles")]
        {
            // if a pmtiles source were to keep being configured like this,
            // we would not be able to migrate defaults/deprecate settings
            //
            // pmiles initialisation after this in resolve_tile_sources depends on this behaviour and will panic otherwise
            self.pmtiles = self.pmtiles.clone().into_config();
            self.pmtiles.finalize().await?;
        }

        #[cfg(feature = "mbtiles")]
        self.mbtiles.finalize().await?;

        #[cfg(feature = "passthrough")]
        self.passthrough.finalize().await?;

        #[cfg(feature = "unstable-cog")]
        self.cog.finalize().await?;

        #[cfg(feature = "unstable-duckdb")]
        self.duckdb.finalize().await?;

        #[cfg(feature = "geojson")]
        self.geojson.finalize().await?;

        #[cfg(feature = "sprites")]
        self.sprites.finalize().await?;

        #[cfg(feature = "styles")]
        self.styles.finalize().await?;

        #[cfg(feature = "fonts")]
        self.fonts.finalize().await?;

        // Resolving every source's process settings range-checks them; the map itself is
        // rebuilt by `resolve()`.
        #[cfg(feature = "_tiles")]
        self.resolved_process_map()?;

        if self.has_no_sources() {
            Err(ConfigFileError::NoSources.into())
        } else {
            Ok(())
        }
    }

    /// Returns `true` when no source of any enabled kind has been configured.
    fn has_no_sources(&self) -> bool {
        let is_empty = true;

        #[cfg(feature = "postgres")]
        let is_empty = is_empty && self.postgres.is_empty();

        #[cfg(feature = "pmtiles")]
        let is_empty = is_empty && self.pmtiles.is_empty();

        #[cfg(feature = "mbtiles")]
        let is_empty = is_empty && self.mbtiles.is_empty();

        #[cfg(feature = "passthrough")]
        let is_empty = is_empty && self.passthrough.is_empty();

        #[cfg(feature = "unstable-cog")]
        let is_empty = is_empty && self.cog.is_empty();

        #[cfg(feature = "unstable-duckdb")]
        let is_empty = is_empty && self.duckdb.is_empty();

        #[cfg(feature = "geojson")]
        let is_empty = is_empty && self.geojson.is_empty();

        #[cfg(feature = "sprites")]
        let is_empty = is_empty && self.sprites.is_empty();

        #[cfg(feature = "styles")]
        let is_empty = is_empty && self.styles.is_empty();

        #[cfg(feature = "fonts")]
        let is_empty = is_empty && self.fonts.is_empty();

        is_empty
    }

    /// Warn about configuration keys that were not recognized while parsing the config file.
    ///
    /// Call after [`Config::finalize`], which consumes and migrates the keys it recognizes.
    pub fn warn_unrecognized_keys(&self) {
        for key in &self.get_unrecognized_keys() {
            warn!(
                "Ignoring unrecognized configuration key '{key}'. Please check your configuration file for typos."
            );
        }
    }

    #[instrument(skip_all, err(Debug))]
    pub async fn resolve(
        &mut self,
        #[cfg(feature = "_tiles")] idr: &IdResolver,
    ) -> StartupResult<ServerState> {
        init_aws_lc_tls();

        #[cfg(any(feature = "_tiles", feature = "sprites", feature = "fonts"))]
        let cache_config = self.resolve_cache_config();

        #[cfg(feature = "pmtiles")]
        let pmtiles_cache = cache_config.create_pmtiles_cache();

        #[cfg(feature = "_tiles")]
        let (tile_sources, warnings) = self
            .resolve_tile_sources(
                idr,
                #[cfg(feature = "pmtiles")]
                pmtiles_cache,
            )
            .await?;

        #[cfg(feature = "_tiles")]
        self.on_invalid
            .unwrap_or_default()
            .handle_tile_warnings(&warnings)?;

        #[cfg(feature = "_tiles")]
        let tile_sources_with_process = {
            let process_map = self.resolved_process_map()?;
            tile_sources
                .into_iter()
                .map(|group| {
                    group
                        .into_iter()
                        .map(|src| {
                            let pc = process_map.get(src.get_id()).cloned().unwrap_or_default();
                            (src, pc)
                        })
                        .collect::<Vec<_>>()
                })
                .collect::<Vec<_>>()
        };

        Ok(ServerState {
            #[cfg(feature = "_tiles")]
            tile_manager: TileSourceManager::from_sources(
                cache_config.create_tile_cache(),
                self.on_invalid.unwrap_or_default(),
                tile_sources_with_process,
            ),

            #[cfg(feature = "sprites")]
            sprites: self.sprites.resolve()?,
            #[cfg(feature = "sprites")]
            sprite_cache: cache_config.create_sprite_cache(),

            #[cfg(feature = "fonts")]
            fonts: self.fonts.resolve()?,
            #[cfg(feature = "fonts")]
            font_cache: cache_config.create_font_cache(),

            #[cfg(feature = "styles")]
            styles: self.styles.resolve()?,
        })
    }

    // cache.size_mb is still respected, but can be overridden by individual cache sizes
    //
    // `cache.size_mb: 0` disables caching, unless overridden by individual cache sizes
    #[cfg(any(feature = "_tiles", feature = "sprites", feature = "fonts"))]
    fn resolve_cache_config(&self) -> CacheConfig {
        let global_expiry = self.cache.expiry;
        let global_idle = self.cache.idle_timeout;

        if let Some(cache_size_mb) = self.cache.size_mb {
            #[cfg(feature = "_tiles")]
            let tiles = Self::make_sub_cache(
                self.cache.tile_size_mb.unwrap_or(cache_size_mb / 2),
                self.cache.tile_expiry.or(global_expiry),
                self.cache.tile_idle_timeout.or(global_idle),
            );

            #[cfg(feature = "pmtiles")]
            let pmtiles = {
                let (size, expiry, idle) = if let FileConfigEnum::Config(cfg) = &self.pmtiles {
                    (
                        cfg.custom
                            .directory_cache
                            .size_mb
                            .unwrap_or(cache_size_mb / 4),
                        cfg.custom.directory_cache.expiry.or(global_expiry),
                        cfg.custom.directory_cache.idle_timeout.or(global_idle),
                    )
                } else {
                    (cache_size_mb / 4, global_expiry, global_idle)
                };
                Self::make_sub_cache(size, expiry, idle)
            };

            #[cfg(feature = "sprites")]
            let sprites = {
                let (size, expiry, idle) = if let FileConfigEnum::Config(cfg) = &self.sprites {
                    (
                        cfg.custom.cache.size_mb.unwrap_or(cache_size_mb / 8),
                        cfg.custom.cache.expiry.or(global_expiry),
                        cfg.custom.cache.idle_timeout.or(global_idle),
                    )
                } else {
                    (cache_size_mb / 8, global_expiry, global_idle)
                };
                Self::make_sub_cache(size, expiry, idle)
            };

            #[cfg(feature = "fonts")]
            let fonts = {
                let (size, expiry, idle) = if let FileConfigEnum::Config(cfg) = &self.fonts {
                    (
                        cfg.custom.cache.size_mb.unwrap_or(cache_size_mb / 8),
                        cfg.custom.cache.expiry.or(global_expiry),
                        cfg.custom.cache.idle_timeout.or(global_idle),
                    )
                } else {
                    (cache_size_mb / 8, global_expiry, global_idle)
                };
                Self::make_sub_cache(size, expiry, idle)
            };

            CacheConfig {
                #[cfg(feature = "_tiles")]
                tiles,
                #[cfg(feature = "pmtiles")]
                pmtiles,
                #[cfg(feature = "sprites")]
                sprites,
                #[cfg(feature = "fonts")]
                fonts,
            }
        } else {
            // TODO: the defaults could be smarter. If I don't have pmtiles sources, don't reserve cache for it
            CacheConfig {
                #[cfg(feature = "_tiles")]
                tiles: Self::make_sub_cache(
                    256,
                    self.cache.tile_expiry.or(global_expiry),
                    self.cache.tile_idle_timeout.or(global_idle),
                ),
                #[cfg(feature = "pmtiles")]
                pmtiles: Self::make_sub_cache(128, global_expiry, global_idle),
                #[cfg(feature = "sprites")]
                sprites: Self::make_sub_cache(64, global_expiry, global_idle),
                #[cfg(feature = "fonts")]
                fonts: Self::make_sub_cache(64, global_expiry, global_idle),
            }
        }
    }

    /// Helper to create a `SubCacheSetting` from size in MB. Returns `None` if size is 0.
    #[cfg(any(feature = "_tiles", feature = "sprites", feature = "fonts"))]
    fn make_sub_cache(
        size_mb: u64,
        expiry: Option<Duration>,
        idle_timeout: Option<Duration>,
    ) -> Option<SubCacheSetting> {
        NonZeroU64::new(size_mb).map(|size_mb| SubCacheSetting {
            size_mb,
            expiry,
            idle_timeout,
        })
    }

    #[cfg(feature = "_tiles")]
    #[instrument(skip_all, err(Debug))]
    #[cfg_attr(
        not(any(
            feature = "pmtiles",
            feature = "mbtiles",
            feature = "passthrough",
            feature = "unstable-cog",
            feature = "unstable-duckdb",
            feature = "geojson"
        )),
        expect(
            unused_variables,
            reason = "idr is only consumed by file tile backends"
        )
    )]
    async fn resolve_tile_sources(
        &mut self,
        idr: &IdResolver,
        #[cfg(feature = "pmtiles")] pmtiles_cache: PmtCache,
    ) -> StartupResult<(Vec<Vec<BoxedSource>>, Vec<TileSourceWarning>)> {
        #[cfg_attr(
            not(any(
                feature = "pmtiles",
                feature = "mbtiles",
                feature = "passthrough",
                feature = "unstable-cog",
                feature = "unstable-duckdb",
                feature = "geojson"
            )),
            expect(unused_mut, reason = "file tile backends push resolved sources here")
        )]
        let mut sources_and_warnings: Vec<BoxFuture<ResolutionResult>> = Vec::new();

        #[cfg(feature = "pmtiles")]
        if !self.pmtiles.is_empty() {
            let cfg = &mut self.pmtiles;
            match cfg {
                FileConfigEnum::None => {}
                FileConfigEnum::Paths(_) | FileConfigEnum::Path(_) => unreachable!(
                    "pmtiles was transformed to FileConfigEnum::Config in the previous step via `into_config`",
                ),
                FileConfigEnum::Config(file_config) => {
                    file_config.custom.pmtiles_directory_cache = pmtiles_cache;
                }
            }
            let val = resolve_files(cfg, idr, &["pmtiles"], self.cache.policy());
            sources_and_warnings.push(Box::pin(val));
        }

        #[cfg(feature = "mbtiles")]
        if !self.mbtiles.is_empty() {
            let cfg = &mut self.mbtiles;
            let val = resolve_files(cfg, idr, &["mbtiles"], self.cache.policy());
            sources_and_warnings.push(Box::pin(val));
        }

        #[cfg(feature = "passthrough")]
        if !self.passthrough.is_empty() {
            let val = self.passthrough.resolve(idr, self.cache.policy());
            sources_and_warnings.push(Box::pin(val));
        }

        #[cfg(feature = "unstable-cog")]
        if !self.cog.is_empty() {
            let cfg = &mut self.cog;
            let val = resolve_files(cfg, idr, &["tif", "tiff"], self.cache.policy());
            sources_and_warnings.push(Box::pin(val));
        }

        #[cfg(feature = "unstable-duckdb")]
        if !self.duckdb.is_empty() {
            let val = self.duckdb.resolve(idr.clone(), self.cache.policy());
            sources_and_warnings.push(Box::pin(val));
        }

        #[cfg(feature = "geojson")]
        if !self.geojson.is_empty() {
            let cfg = &mut self.geojson;
            let val = resolve_files(cfg, idr, &["json", "geojson"], self.cache.policy());
            sources_and_warnings.push(Box::pin(val));
        }

        let all_results = try_join_all(sources_and_warnings).await?;
        let (all_tile_sources, all_tile_warnings): (Vec<_>, Vec<_>) =
            all_results.into_iter().unzip();

        Ok((
            all_tile_sources,
            all_tile_warnings.into_iter().flatten().collect(),
        ))
    }

    /// The processing settings configured at the top level of the config file, which every source inherits unless it overrides them.
    #[cfg(any(
        feature = "pmtiles",
        feature = "mbtiles",
        feature = "passthrough",
        feature = "unstable-cog",
        feature = "geojson"
    ))]
    fn global_process_config(&self) -> ProcessConfig {
        ProcessConfig {
            #[cfg(feature = "mlt")]
            convert_to_mlt: self.convert_to_mlt.clone(),
            #[cfg(feature = "mlt")]
            convert_to_mvt: self.convert_to_mvt.clone(),
            // applied by middleware from the server-level default, not carried here
            cache_control: None,
            // `None` since deliberately does not exist at top level
            #[cfg(feature = "hillshade")]
            convert_to_hillshade: None,
            #[cfg(feature = "contour")]
            convert_to_contour: None,
        }
    }

    /// Source ID -> what it is served with, every level folded and range-checked.
    ///
    /// Uses full-override semantics: per-source > source-type > global > default.
    #[cfg(feature = "_tiles")]
    fn resolved_process_map(&self) -> StartupResult<HashMap<String, ResolvedProcess>> {
        #[allow(unused_mut)]
        let mut map = HashMap::new();

        #[cfg(any(
            feature = "pmtiles",
            feature = "mbtiles",
            feature = "passthrough",
            feature = "unstable-cog",
            feature = "geojson"
        ))]
        {
            let global = self.global_process_config();

            #[cfg(all(feature = "pmtiles", feature = "mlt"))]
            Self::insert_file_source_configs(&mut map, &global, &self.pmtiles, |c| {
                ProcessConfig {
                    convert_to_mlt: c.convert_to_mlt.clone(),
                    convert_to_mvt: c.convert_to_mvt.clone(),
                    cache_control: None,
                    #[cfg(feature = "hillshade")]
                    convert_to_hillshade: None,
                    #[cfg(feature = "contour")]
                    convert_to_contour: None,
                }
            })?;
            #[cfg(all(feature = "pmtiles", not(feature = "mlt")))]
            Self::insert_file_source_configs(&mut map, &global, &self.pmtiles, |_| {
                ProcessConfig::default()
            })?;

            #[cfg(all(feature = "mbtiles", feature = "mlt"))]
            Self::insert_file_source_configs(&mut map, &global, &self.mbtiles, |c| {
                ProcessConfig {
                    convert_to_mlt: c.convert_to_mlt.clone(),
                    convert_to_mvt: c.convert_to_mvt.clone(),
                    cache_control: None,
                    #[cfg(feature = "hillshade")]
                    convert_to_hillshade: None,
                    #[cfg(feature = "contour")]
                    convert_to_contour: None,
                }
            })?;
            #[cfg(all(feature = "mbtiles", not(feature = "mlt")))]
            Self::insert_file_source_configs(&mut map, &global, &self.mbtiles, |_| {
                ProcessConfig::default()
            })?;

            // COG and GeoJSON have no kind-level conversion settings.
            // COG cannot be hillshaded either: shading reads Mapzen *normal* tiles, whose surface
            // gradients are already per-pixel, whereas a COG holds elevation - which would need
            // metres-per-pixel scaling and its own quantisation handling, a separate feature.
            #[cfg(feature = "unstable-cog")]
            Self::insert_file_source_configs(&mut map, &global, &self.cog, |_| {
                ProcessConfig::default()
            })?;

            #[cfg(feature = "geojson")]
            Self::insert_file_source_configs(&mut map, &global, &self.geojson, |_| {
                ProcessConfig::default()
            })?;

            #[cfg(feature = "passthrough")]
            if let Some(sources) = &self.passthrough.sources {
                use crate::config::file::passthrough::PassthroughSrc;

                let source_type = ProcessConfig {
                    #[cfg(feature = "mlt")]
                    convert_to_mlt: self.passthrough.convert_to_mlt.clone(),
                    #[cfg(feature = "mlt")]
                    convert_to_mvt: self.passthrough.convert_to_mvt.clone(),
                    cache_control: None,
                    #[cfg(feature = "hillshade")]
                    convert_to_hillshade: None,
                    #[cfg(feature = "contour")]
                    convert_to_contour: None,
                };
                Self::insert_source_configs(&mut map, &global, &source_type, sources, |src| {
                    match src {
                        PassthroughSrc::Detailed(obj) => ProcessConfig {
                            #[cfg(feature = "mlt")]
                            convert_to_mlt: obj.convert_to_mlt.clone(),
                            #[cfg(feature = "mlt")]
                            convert_to_mvt: obj.convert_to_mvt.clone(),
                            cache_control: obj.cache_control.clone(),
                            #[cfg(feature = "hillshade")]
                            convert_to_hillshade: obj.convert_to_hillshade.clone(),
                            #[cfg(all(feature = "contour", feature = "_tiles"))]
                            convert_to_contour: obj.convert_to_contour.clone(),
                        },
                        PassthroughSrc::Shorthand(_) => ProcessConfig::default(),
                    }
                })?;
            }
        }

        Ok(map)
    }

    /// Resolve and insert the effective [`ResolvedProcess`] for each source in a map, layering
    /// per-source settings over the source-type and global defaults.
    #[cfg(any(
        feature = "pmtiles",
        feature = "mbtiles",
        feature = "passthrough",
        feature = "unstable-cog",
        feature = "geojson"
    ))]
    fn insert_source_configs<'a, S: 'a>(
        map: &mut HashMap<String, ResolvedProcess>,
        global: &ProcessConfig,
        source_type: &ProcessConfig,
        sources: impl IntoIterator<Item = (&'a String, &'a S)>,
        get_per_source_pc: impl Fn(&S) -> ProcessConfig,
    ) -> StartupResult<()> {
        for (id, src) in sources {
            let resolved = ProcessConfig::layered(global, source_type, &get_per_source_pc(src))
                .resolve()
                .map_err(|e| e.for_source(id.clone()))?;
            map.insert(id.clone(), resolved);
        }
        Ok(())
    }

    /// Helper to resolve process configs for file-based source types.
    #[cfg(any(
        feature = "pmtiles",
        feature = "mbtiles",
        feature = "unstable-cog",
        feature = "geojson"
    ))]
    fn insert_file_source_configs<T: ConfigurationLivecycleHooks>(
        map: &mut HashMap<String, ResolvedProcess>,
        global: &ProcessConfig,
        file_cfg: &FileConfigEnum<T>,
        get_source_type_pc: impl Fn(&T) -> ProcessConfig,
    ) -> StartupResult<()> {
        if let FileConfigEnum::Config(cfg) = file_cfg {
            let source_type = get_source_type_pc(&cfg.custom);
            if let Some(sources) = &cfg.sources {
                Self::insert_source_configs(map, global, &source_type, sources, |src| match src {
                    FileConfigSrc::Obj(obj) => ProcessConfig {
                        #[cfg(feature = "mlt")]
                        convert_to_mlt: obj.convert_to_mlt.clone(),
                        #[cfg(feature = "mlt")]
                        convert_to_mvt: obj.convert_to_mvt.clone(),
                        cache_control: obj.cache_control.clone(),
                        #[cfg(feature = "hillshade")]
                        convert_to_hillshade: obj.convert_to_hillshade.clone(),
                        #[cfg(all(feature = "contour", feature = "_tiles"))]
                        convert_to_contour: obj.convert_to_contour.clone(),
                    },
                    FileConfigSrc::Path(_) => ProcessConfig::default(),
                })?;
            }
        }
        Ok(())
    }

    /// A copy of this config whose sections carry the sources currently in the catalog:
    /// `postgres` entries get their `tables`/`functions` matched by `connection_string`, and
    /// file-backed sections get an entry per discovered file.
    #[cfg(any(feature = "postgres", feature = "_file_kinds"))]
    #[must_use]
    pub fn with_catalog(&self, catalog: &TileSourceManager) -> Self {
        let mut config = self.clone();
        #[cfg(not(any(feature = "postgres", feature = "_file_kinds")))]
        let _ = catalog;

        #[cfg(feature = "postgres")]
        for pg in config.postgres.iter_mut() {
            use crate::config::file::postgres::{FuncInfoSources, SourceSpec, TableInfoSources};
            use crate::reload::SourceProvenance;

            let mut tables = TableInfoSources::new();
            let mut functions = FuncInfoSources::new();
            for (id, provenance) in catalog.provenance() {
                match provenance {
                    SourceProvenance::Postgres {
                        connection_string,
                        spec,
                    } => {
                        if Some(&connection_string) != pg.connection_string.as_ref() {
                            continue;
                        }
                        match *spec {
                            SourceSpec::Table(info) => {
                                tables.insert(id, info);
                            }
                            SourceSpec::Function(info, _) => {
                                functions.insert(id, info);
                            }
                        }
                    }
                    #[cfg(feature = "_file_kinds")]
                    SourceProvenance::File { .. } => {}
                }
            }
            pg.tables = Some(tables);
            pg.functions = Some(functions);
        }

        #[cfg(feature = "_file_kinds")]
        for (id, provenance) in catalog.provenance() {
            use crate::reload::{FileKind, SourceProvenance};

            match provenance {
                SourceProvenance::File { kind, src } => match kind {
                    #[cfg(feature = "mbtiles")]
                    FileKind::Mbtiles => config.mbtiles.insert_source(id, src),
                    #[cfg(feature = "pmtiles")]
                    FileKind::Pmtiles => config.pmtiles.insert_source(id, src),
                    #[cfg(feature = "unstable-cog")]
                    FileKind::Cog => config.cog.insert_source(id, src),
                    #[cfg(feature = "geojson")]
                    FileKind::GeoJson => config.geojson.insert_source(id, src),
                },
                #[cfg(feature = "postgres")]
                SourceProvenance::Postgres { .. } => {}
            }
        }

        config
    }

    /// Writes the running configuration, with the tile sources materialized from the catalog so
    /// the file describes what is actually served.
    pub fn save_to_file(
        &self,
        file_name: &Path,
        #[cfg(feature = "_tiles")] catalog: &TileSourceManager,
    ) -> ConfigFileResult<()> {
        #[cfg(any(feature = "postgres", feature = "_file_kinds"))]
        let config = self.with_catalog(catalog);
        #[cfg(all(
            feature = "_tiles",
            not(any(feature = "postgres", feature = "_file_kinds"))
        ))]
        let _ = catalog;
        #[cfg(not(any(feature = "postgres", feature = "_file_kinds")))]
        let config = self;
        let yaml = serde_saphyr::to_string(&config).expect("Unable to serialize config");
        if file_name.as_os_str() == OsStr::new("-") {
            info!("Current system configuration:");
            #[expect(
                clippy::print_stdout,
                reason = "`--save -` writes the config to stdout"
            )]
            {
                println!("\n\n{yaml}\n");
            }
            Ok(())
        } else {
            info!(
                "Saving config to {}, use --config to load it",
                file_name.display()
            );
            File::create(file_name)
                .map_err(|e| ConfigFileError::ConfigWriteError(e, file_name.to_path_buf()))?
                .write_all(yaml.as_bytes())
                .map_err(|e| ConfigFileError::ConfigWriteError(e, file_name.to_path_buf()))?;
            Ok(())
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::config::test_helpers::render_finalize_failure;

    #[cfg(all(feature = "hillshade", feature = "passthrough"))]
    #[tokio::test]
    async fn finalize_rejects_an_out_of_range_hillshade() {
        insta::assert_snapshot!(
            render_finalize_failure(indoc::indoc! {"
                passthrough:
                  sources:
                    terrain:
                      url: https://example.org/normal/{z}/{x}/{y}.png
                      convert_to_hillshade:
                        azimuth: 400
            "})
            .await,
            @"Source terrain has an invalid hillshade configuration: Hillshade parameter azimuth must be between `0` and `360`, but was `400`"
        );
    }

    #[cfg(all(feature = "hillshade", feature = "passthrough"))]
    #[tokio::test]
    async fn hillshade_cannot_be_configured_globally() {
        use crate::config::file::CollectUnrecognizedKeys as _;

        let config: super::Config = serde_saphyr::from_str(indoc::indoc! {"
            convert_to_hillshade: auto
            passthrough:
              sources:
                terrain: https://example.org/normal/{z}/{x}/{y}.png
        "})
        .expect("parses, with the stray key collected rather than rejected");

        let keys = config.get_unrecognized_keys();
        let keys = keys.iter().collect::<Vec<_>>();
        assert_eq!(keys.as_slice(), ["convert_to_hillshade"]);
    }

    #[cfg(all(feature = "hillshade", feature = "passthrough"))]
    #[tokio::test]
    async fn finalize_accepts_a_valid_hillshade() {
        let mut config: super::Config = serde_saphyr::from_str(indoc::indoc! {"
            passthrough:
              sources:
                terrain:
                  url: https://example.org/normal/{z}/{x}/{y}.png
                  convert_to_hillshade:
                    azimuth: 315
                    format: webp
        "})
        .expect("parses");
        config
            .finalize()
            .await
            .expect("valid hillshade must start up");
    }

    #[tokio::test]
    async fn finalize_no_sources() {
        insta::assert_snapshot!(
            render_finalize_failure("keep_alive: 75\n").await,
            @"No tile sources found. Set sources by giving a database connection string on command line, env variable, or a config file."
        );
    }
}