martin 1.6.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
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
use std::collections::{BTreeMap, HashMap, HashSet};
use std::fmt::Debug;
use std::mem;
#[cfg(feature = "_tiles")]
use std::path::Path;
use std::path::PathBuf;
use std::time::Duration;

use martin_core::CacheZoomRange;
#[cfg(feature = "_tiles")]
use martin_core::tiles::BoxedSource;
use serde::{Deserialize, Serialize};
#[cfg(feature = "_tiles")]
use tracing::{info, warn};
#[cfg(feature = "_tiles")]
use url::Url;

#[cfg(feature = "_tiles")]
use crate::config::file::TileSourceWarning;
use crate::config::file::{ConfigFileError, ConfigFileResult};
#[cfg(feature = "_tiles")]
use crate::config::primitives::IdResolver;
use crate::config::primitives::OptOneMany;
#[cfg(feature = "_tiles")]
use crate::{MartinError, MartinResult};

/// Lifecycle hooks for configuring the application
///
/// The hooks are guaranteed called in the following order:
/// 1. `finalize`
/// 2. `get_unrecognized_keys`
pub trait ConfigurationLivecycleHooks: Clone + Debug + Default + PartialEq + Send {
    /// Finalize configuration discovery and patch old values
    ///
    /// In practice, this method is only implemented on a path of the config if a value or a value in the path below it needs to be finalized
    fn finalize(&mut self) -> ConfigFileResult<()> {
        Ok(())
    }

    /// Iterates over all unrecognized (present, but not expected) keys in the configuration
    fn get_unrecognized_keys(&self) -> UnrecognizedKeys;

    /// Returns all results of the [`Self::get_unrecognized_keys`], but with a given prefix
    fn get_unrecognized_keys_with_prefix(&self, prefix: &str) -> UnrecognizedKeys {
        self.get_unrecognized_keys()
            .into_iter()
            .map(|key| format!("{prefix}{key}"))
            .collect()
    }
}

/// Configuration which all of our tile sources implement to make configuring them easier
#[cfg(feature = "_tiles")]
pub trait TileSourceConfiguration: ConfigurationLivecycleHooks {
    /// Indicates whether path strings for this configuration should be parsed as URLs.
    ///
    /// - `true` means any source path starting with `http://`, `https://`, or `s3://` will be treated as a remote URL.
    /// - `false` means all paths are treated as local file system paths.
    #[must_use]
    fn parse_urls() -> bool;

    /// Asynchronously creates a new `BoxedSource` from a **local** file `path` using the given `id`.
    ///
    /// This function is called for each discovered file path that is not a URL.
    /// `cache` contains per-source zoom bounds, already merged with defaults.
    fn new_sources(
        &self,
        id: String,
        path: PathBuf,
        cache: CachePolicy,
    ) -> impl Future<Output = MartinResult<BoxedSource>> + Send;

    /// Asynchronously creates a new `BoxedSource` from a **remote** `url` using the given `id`.
    ///
    /// This function is called for each discovered source path that is a valid URL.
    /// `cache` contains per-source zoom bounds, already merged with defaults.
    fn new_sources_url(
        &self,
        id: String,
        url: Url,
        cache: CachePolicy,
    ) -> impl Future<Output = MartinResult<BoxedSource>> + Send;
}

#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum FileConfigEnum<T> {
    #[default]
    None,
    Path(PathBuf),
    Paths(Vec<PathBuf>),
    Config(FileConfig<T>),
}

impl<T: ConfigurationLivecycleHooks> FileConfigEnum<T> {
    #[must_use]
    pub fn new(paths: Vec<PathBuf>) -> Self {
        Self::new_extended(paths, BTreeMap::new(), T::default())
    }

    #[must_use]
    pub fn new_extended(
        paths: Vec<PathBuf>,
        configs: BTreeMap<String, FileConfigSrc>,
        custom: T,
    ) -> Self {
        if configs.is_empty() {
            match paths.len() {
                0 => Self::None,
                1 => Self::Path(paths.into_iter().next().expect("one path exists")),
                _ => Self::Paths(paths),
            }
        } else {
            Self::Config(FileConfig {
                paths: OptOneMany::new(paths),
                sources: if configs.is_empty() {
                    None
                } else {
                    Some(configs)
                },
                custom,
            })
        }
    }

    #[must_use]
    pub fn is_none(&self) -> bool {
        matches!(self, Self::None)
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        match self {
            Self::None => true,
            Self::Path(_) => false,
            Self::Paths(v) => v.is_empty(),
            Self::Config(c) => c.is_empty(),
        }
    }

    pub fn extract_file_config(&mut self) -> Option<FileConfig<T>> {
        match self {
            Self::None => None,
            Self::Path(path) => Some(FileConfig {
                paths: OptOneMany::One(mem::take(path)),
                ..FileConfig::default()
            }),
            Self::Paths(paths) => Some(FileConfig {
                paths: OptOneMany::Many(mem::take(paths)),
                ..Default::default()
            }),
            Self::Config(cfg) => Some(mem::take(cfg)),
        }
    }

    /// convert path/paths and the config enums
    #[must_use]
    pub fn into_config(self) -> Self {
        match self {
            Self::Path(path) => Self::Config(FileConfig {
                paths: OptOneMany::One(path),
                sources: None,
                custom: T::default(),
            }),
            Self::Paths(paths) => Self::Config(FileConfig {
                paths: OptOneMany::Many(paths),
                sources: None,
                custom: T::default(),
            }),
            c => c,
        }
    }
}

impl<T: ConfigurationLivecycleHooks> ConfigurationLivecycleHooks for FileConfigEnum<T> {
    fn finalize(&mut self) -> ConfigFileResult<()> {
        if let Self::Config(cfg) = self {
            cfg.finalize()
        } else {
            Ok(())
        }
    }

    fn get_unrecognized_keys(&self) -> UnrecognizedKeys {
        if let Self::Config(cfg) = self {
            cfg.get_unrecognized_keys()
        } else {
            UnrecognizedKeys::new()
        }
    }
}

#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct FileConfig<T> {
    /// A list of file paths
    #[serde(default, skip_serializing_if = "OptOneMany::is_none")]
    pub paths: OptOneMany<PathBuf>,
    /// A map of source IDs to file paths or config objects
    pub sources: Option<BTreeMap<String, FileConfigSrc>>,
    /// Any customizations related to the specifics of the configuration section
    #[serde(flatten)]
    pub custom: T,
}

impl<T: ConfigurationLivecycleHooks> FileConfig<T> {
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.paths.is_none() && self.sources.is_none() && self.get_unrecognized_keys().is_empty()
    }
}

impl<T: ConfigurationLivecycleHooks> ConfigurationLivecycleHooks for FileConfig<T> {
    fn finalize(&mut self) -> ConfigFileResult<()> {
        self.custom.finalize()
    }
    fn get_unrecognized_keys(&self) -> UnrecognizedKeys {
        self.custom.get_unrecognized_keys()
    }
}

/// A serde helper to store a boolean as an object.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum FileConfigSrc {
    Path(PathBuf),
    Obj(FileConfigSource),
}

impl FileConfigSrc {
    #[must_use]
    pub fn into_path(self) -> PathBuf {
        match self {
            Self::Path(p) => p,
            Self::Obj(o) => o.path,
        }
    }

    #[must_use]
    pub fn get_path(&self) -> &PathBuf {
        match self {
            Self::Path(p) => p,
            Self::Obj(o) => &o.path,
        }
    }

    #[must_use]
    pub fn cache_zoom(&self) -> CachePolicy {
        match self {
            Self::Path(_) => CachePolicy::default(),
            Self::Obj(o) => o.cache,
        }
    }

    pub fn abs_path(&self) -> ConfigFileResult<PathBuf> {
        let path = self.get_path();

        #[cfg(feature = "mbtiles")]
        if is_sqlite_memory_uri(path) {
            // Skip canonicalization for in-memory DB URIs
            return Ok(path.clone());
        }

        path.canonicalize()
            .map_err(|e| ConfigFileError::IoError(e, path.clone()))
    }
}

#[cfg(feature = "mbtiles")]
fn is_sqlite_memory_uri(path: &Path) -> bool {
    if let Some(s) = path.to_str() {
        s.starts_with("file:") && s.contains("mode=memory") && s.contains("cache=shared")
    } else {
        false
    }
}

#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct FileConfigSource {
    pub path: PathBuf,
    /// Zoom-level bounds for tile caching.
    #[serde(default, skip_serializing_if = "CachePolicy::is_empty")]
    pub cache: CachePolicy,
}

#[cfg(feature = "_tiles")]
pub async fn resolve_files<T: TileSourceConfiguration>(
    config: &mut FileConfigEnum<T>,
    idr: &IdResolver,
    extension: &[&str],
    default_cache: CachePolicy,
) -> MartinResult<(Vec<BoxedSource>, Vec<TileSourceWarning>)> {
    resolve_int(config, idr, extension, default_cache).await
}

#[cfg(feature = "_tiles")]
async fn resolve_int<T: TileSourceConfiguration>(
    config: &mut FileConfigEnum<T>,
    idr: &IdResolver,
    extension: &[&str],
    default_cache: CachePolicy,
) -> MartinResult<(Vec<BoxedSource>, Vec<TileSourceWarning>)> {
    let Some(cfg) = config.extract_file_config() else {
        return Ok((vec![], vec![]));
    };

    let mut results = Vec::new();
    let mut warnings = Vec::new();
    let mut configs = BTreeMap::new();
    let mut files = HashSet::new();
    let mut directories = Vec::new();

    if let Some(sources) = cfg.sources {
        for (id, source) in sources {
            match resolve_one_source_int(
                &cfg.custom,
                idr,
                &id,
                source,
                &mut files,
                &mut configs,
                default_cache,
            )
            .await
            {
                Ok(src) => results.push(src),
                Err(err) => {
                    warnings.push(TileSourceWarning::SourceError {
                        source_id: id,
                        error: err.to_string(),
                    });
                }
            }
        }
    }

    for path in cfg.paths {
        match resolve_one_path_int(
            &cfg.custom,
            idr,
            extension,
            path.clone(),
            &mut files,
            &mut directories,
            &mut configs,
            default_cache,
        )
        .await
        {
            Ok(sources) => results.extend(sources),
            Err(err) => {
                warnings.push(TileSourceWarning::PathError {
                    path: path.display().to_string(),
                    error: err.to_string(),
                });
            }
        }
    }

    *config = FileConfigEnum::new_extended(directories, configs, cfg.custom);

    Ok((results, warnings))
}

/// Resolves a single tile source configuration and returns a boxed source for further processing.
///
/// This function processes a tile source configuration using a given custom implementation of
/// `TileSourceConfiguration` and resolves its ID using `IdResolver`.
/// It determines if the source is a URL or a file path, configures the source accordingly.
#[cfg(feature = "_tiles")]
async fn resolve_one_source_int<T: TileSourceConfiguration>(
    custom: &T,
    idr: &IdResolver,
    id: &str,
    source: FileConfigSrc,
    files: &mut HashSet<PathBuf>,
    configs: &mut BTreeMap<String, FileConfigSrc>,
    default_cache: CachePolicy,
) -> MartinResult<BoxedSource> {
    let cache = source.cache_zoom().or(default_cache);
    let result;
    if let Some(url) = parse_url(T::parse_urls(), source.get_path())? {
        let dup = !files.insert(source.get_path().clone());
        let dup = if dup { "duplicate " } else { "" };
        let id = idr.resolve(id, url.to_string());
        configs.insert(id.clone(), source);
        result = custom
            .new_sources_url(id.clone(), url.clone(), cache)
            .await?;
        info!("Configured {dup}source {id} from {}", sanitize_url(&url));
    } else {
        let can = source.abs_path()?;
        let dup = !files.insert(can.clone());
        let dup = if dup { "duplicate " } else { "" };
        let id = idr.resolve(id, can.to_string_lossy().to_string());
        info!("Configured {dup}source {id} from {}", can.display());
        configs.insert(id.clone(), source.clone());
        result = custom.new_sources(id, source.into_path(), cache).await?;
    }
    Ok(result)
}

/// Resolves a single path, configuring sources based on the given tile source configuration.
///
/// This function processes a given `PathBuf`, checking if it represents a file, directory,
/// or a URL, and then it performs the necessary steps to configure tile sources.
#[cfg(feature = "_tiles")]
#[expect(clippy::too_many_arguments)]
async fn resolve_one_path_int<T: TileSourceConfiguration>(
    custom: &T,
    idr: &IdResolver,
    extension: &[&str],
    path: PathBuf,
    files: &mut HashSet<PathBuf>,
    directories: &mut Vec<PathBuf>,
    configs: &mut BTreeMap<String, FileConfigSrc>,
    default_cache: CachePolicy,
) -> MartinResult<Vec<BoxedSource>> {
    let mut results = Vec::new();

    if let Some(url) = parse_url(T::parse_urls(), &path)? {
        let target_ext = extension.iter().find(|&e| url.to_string().ends_with(e));
        let id = if let Some(ext) = target_ext {
            url.path_segments()
                .and_then(Iterator::last)
                .and_then(|s| {
                    // Strip extension and trailing dot, or keep the original string
                    s.strip_suffix(ext)
                        .and_then(|s| s.strip_suffix('.'))
                        .or(Some(s))
                })
                .unwrap_or("web_source")
        } else {
            "web_source"
        };

        let id = idr.resolve(id, url.to_string());
        configs.insert(id.clone(), FileConfigSrc::Path(path));
        results.push(
            custom
                .new_sources_url(id.clone(), url.clone(), default_cache)
                .await?,
        );
        info!("Configured source {id} from URL {}", sanitize_url(&url));
    } else {
        let is_dir = path.is_dir();
        let dir_files = if is_dir {
            // directories will be kept in the config just in case there are new files
            directories.push(path.clone());
            collect_files_with_extension(&path, extension)?
        } else if path.is_file() {
            vec![path]
        } else {
            return Err(MartinError::from(ConfigFileError::InvalidFilePath(
                path.canonicalize().unwrap_or(path),
            )));
        };
        for path in dir_files {
            let can = path
                .canonicalize()
                .map_err(|e| ConfigFileError::IoError(e, path.clone()))?;
            if files.contains(&can) {
                if !is_dir {
                    warn!("Ignoring duplicate MBTiles path: {}", can.display());
                }
                continue;
            }
            let id = path.file_stem().map_or_else(
                || "_unknown".to_string(),
                |s| s.to_string_lossy().to_string(),
            );
            let id = idr.resolve(&id, can.to_string_lossy().to_string());
            info!("Configured source {id} from {}", can.display());
            files.insert(can);
            configs.insert(id.clone(), FileConfigSrc::Path(path.clone()));
            results.push(custom.new_sources(id, path, default_cache).await?);
        }
    }
    Ok(results)
}

/// Returns a vector of file paths matching any `allowed_extension` within the given directory.
///
/// # Errors
///
/// Returns an error if Rust's underlying [`read_dir`](std::fs::read_dir) returns an error.
#[cfg(feature = "_tiles")]
fn collect_files_with_extension(
    base_path: &Path,
    allowed_extension: &[&str],
) -> Result<Vec<PathBuf>, ConfigFileError> {
    Ok(base_path
        .read_dir()
        .map_err(|e| ConfigFileError::IoError(e, base_path.to_path_buf()))?
        .filter_map(Result::ok)
        .filter(|f| {
            f.path().extension().is_some_and(|actual_ext| {
                allowed_extension
                    .iter()
                    .any(|expected_ext| *expected_ext == actual_ext)
            }) && f.path().is_file()
        })
        .map(|f| f.path())
        .collect())
}

#[cfg(feature = "_tiles")]
fn sanitize_url(url: &Url) -> String {
    let mut result = format!("{}://", url.scheme());
    if let Some(host) = url.host_str() {
        result.push_str(host);
    }
    if let Some(port) = url.port() {
        result.push(':');
        result.push_str(&port.to_string());
    }
    result.push_str(url.path());
    result
}

#[cfg(feature = "_tiles")]
fn parse_url(is_enabled: bool, path: &Path) -> Result<Option<Url>, ConfigFileError> {
    if !is_enabled {
        return Ok(None);
    }
    let url_schemes = [
        "s3://", "s3a://", "gs://", "az://", "adl://", "azure://", "abfs://", "abfss://",
        "http://", "https://", "file://",
    ];
    path.to_str()
        .filter(|v| url_schemes.iter().any(|scheme| v.starts_with(scheme)))
        .map(|v| Url::parse(v).map_err(|e| ConfigFileError::InvalidSourceUrl(e, v.to_string())))
        .transpose()
}

/// Cache configuration for a tile source. Currently holds zoom-level bounds;
/// may be extended with additional cache settings in the future.
///
/// Accepts either a struct with zoom bounds or the string `"disable"` to disable caching:
/// ```yaml
/// cache: disable
/// ```
///
/// ```yaml
/// cache:
///   minzoom: 0
///   maxzoom: 10
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)]
pub struct CachePolicy {
    #[serde(flatten)]
    zoom: CacheZoomRange,
}

impl CachePolicy {
    /// Creates a new `CachePolicy` with the given zoom range.
    #[must_use]
    pub fn new(zoom: CacheZoomRange) -> Self {
        Self { zoom }
    }

    /// Creates a disabled `CachePolicy` where caching is turned off.
    #[must_use]
    pub fn disabled() -> Self {
        Self {
            zoom: CacheZoomRange::disabled(),
        }
    }

    /// Returns the zoom-level bounds for caching.
    #[must_use]
    pub fn zoom(self) -> CacheZoomRange {
        self.zoom
    }

    /// Returns `true` if no cache bounds are configured.
    #[must_use]
    #[expect(
        clippy::trivially_copy_pass_by_ref,
        reason = "serde skip_serializing_if requires &self"
    )]
    pub fn is_empty(&self) -> bool {
        self.zoom.is_empty()
    }

    /// Fills in any `None` fields from `other`.
    /// A disabled cache policy (with both bounds set) is not overridden by defaults.
    #[must_use]
    pub fn or(self, other: Self) -> Self {
        Self {
            zoom: self.zoom.or(other.zoom),
        }
    }
}

impl<'de> Deserialize<'de> for CachePolicy {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum CachePolicyHelper {
            String(String),
            Struct {
                #[serde(flatten, default)]
                zoom: CacheZoomRange,
            },
        }

        match CachePolicyHelper::deserialize(deserializer)? {
            CachePolicyHelper::String(s) if s == "disable" => Ok(Self::disabled()),
            CachePolicyHelper::String(s) => Err(serde::de::Error::custom(format!(
                "invalid cache policy string: {s:?}, expected \"disable\""
            ))),
            CachePolicyHelper::Struct { zoom } => Ok(Self { zoom }),
        }
    }
}

/// Global-level cache configuration with both size limits and zoom-level bounds.
///
/// Used at the root of the config file:
/// ```yaml
/// cache:
///   size_mb: 512
///   tile_size_mb: 256
///   expiry: 1h
///   idle_timeout: 15m
///   tile_expiry: 30m
///   tile_idle_timeout: 5m
///   minzoom: 0
///   maxzoom: 20
/// ```
///
/// Or disabled entirely:
/// ```yaml
/// cache: disable
/// ```
#[serde_with::skip_serializing_none]
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)]
pub struct GlobalCacheConfig {
    /// Total cache budget in megabytes (0 to disable).
    /// Split across tile, pmtiles, sprite, and font caches by default.
    pub size_mb: Option<u64>,
    /// Tile cache size override in megabytes.
    /// Defaults to `size_mb / 2`.
    pub tile_size_mb: Option<u64>,
    /// Maximum lifetime for all cache entries (time-to-live from creation).
    /// Supports human-readable formats: "1h", "30m", "1d".
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        with = "humantime_serde"
    )]
    pub expiry: Option<Duration>,
    /// Maximum idle time for all cache entries (time-to-idle since last access).
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        with = "humantime_serde"
    )]
    pub idle_timeout: Option<Duration>,
    /// Tile-specific TTL override. Takes precedence over `expiry` for tiles.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        with = "humantime_serde"
    )]
    pub tile_expiry: Option<Duration>,
    /// Tile-specific idle timeout override. Takes precedence over `idle_timeout` for tiles.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        with = "humantime_serde"
    )]
    pub tile_idle_timeout: Option<Duration>,
    #[serde(flatten)]
    zoom: CacheZoomRange,
}

impl GlobalCacheConfig {
    /// Creates a disabled `GlobalCacheConfig` with size 0 and minzoom > maxzoom.
    #[must_use]
    pub fn disabled() -> Self {
        Self {
            size_mb: Some(0),
            tile_size_mb: Some(0),
            expiry: None,
            idle_timeout: None,
            tile_expiry: None,
            tile_idle_timeout: None,
            zoom: CacheZoomRange::disabled(),
        }
    }

    /// Returns the zoom-level bounds as a [`CachePolicy`].
    #[must_use]
    pub fn policy(self) -> CachePolicy {
        CachePolicy::new(self.zoom)
    }

    /// Returns `true` if no cache settings are configured.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.size_mb.is_none()
            && self.tile_size_mb.is_none()
            && self.expiry.is_none()
            && self.idle_timeout.is_none()
            && self.tile_expiry.is_none()
            && self.tile_idle_timeout.is_none()
            && self.zoom.is_empty()
    }
}

impl<'de> Deserialize<'de> for GlobalCacheConfig {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Helper {
            String(String),
            Struct {
                size_mb: Option<u64>,
                tile_size_mb: Option<u64>,
                #[serde(
                    default,
                    skip_serializing_if = "Option::is_none",
                    with = "humantime_serde"
                )]
                expiry: Option<Duration>,
                #[serde(
                    default,
                    skip_serializing_if = "Option::is_none",
                    with = "humantime_serde"
                )]
                idle_timeout: Option<Duration>,
                #[serde(
                    default,
                    skip_serializing_if = "Option::is_none",
                    with = "humantime_serde"
                )]
                tile_expiry: Option<Duration>,
                #[serde(
                    default,
                    skip_serializing_if = "Option::is_none",
                    with = "humantime_serde"
                )]
                tile_idle_timeout: Option<Duration>,
                #[serde(flatten, default)]
                zoom: CacheZoomRange,
            },
        }

        match Helper::deserialize(deserializer)? {
            Helper::String(s) if s == "disable" => Ok(Self::disabled()),
            Helper::String(s) => Err(serde::de::Error::custom(format!(
                "invalid cache config string: {s:?}, expected \"disable\""
            ))),
            Helper::Struct {
                size_mb,
                tile_size_mb,
                expiry,
                idle_timeout,
                tile_expiry,
                tile_idle_timeout,
                zoom,
            } => Ok(Self {
                size_mb,
                tile_size_mb,
                expiry,
                idle_timeout,
                tile_expiry,
                tile_idle_timeout,
                zoom,
            }),
        }
    }
}

/// Cache size configuration for a source type (sprites, fonts, pmtiles).
///
/// Used at the source-type level:
/// ```yaml
/// sprites:
///   cache:
///     size_mb: 64
/// ```
///
/// Or disabled entirely:
/// ```yaml
/// sprites:
///   cache: disable
/// ```
#[serde_with::skip_serializing_none]
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)]
pub struct CacheSizeConfig {
    /// Cache size in megabytes for this source type (0 to disable).
    pub size_mb: Option<u64>,
    /// Maximum lifetime of cache entries (time-to-live from creation).
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        with = "humantime_serde"
    )]
    pub expiry: Option<Duration>,
    /// Maximum idle time before cache entries are evicted (time-to-idle since last access).
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        with = "humantime_serde"
    )]
    pub idle_timeout: Option<Duration>,
}

impl CacheSizeConfig {
    /// Returns `true` if no cache settings are configured.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.size_mb.is_none() && self.expiry.is_none() && self.idle_timeout.is_none()
    }
}

impl<'de> Deserialize<'de> for CacheSizeConfig {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Helper {
            String(String),
            Struct {
                size_mb: Option<u64>,
                #[serde(
                    default,
                    skip_serializing_if = "Option::is_none",
                    with = "humantime_serde"
                )]
                expiry: Option<Duration>,
                #[serde(
                    default,
                    skip_serializing_if = "Option::is_none",
                    with = "humantime_serde"
                )]
                idle_timeout: Option<Duration>,
            },
        }

        match Helper::deserialize(deserializer)? {
            Helper::String(s) if s == "disable" => Ok(Self {
                size_mb: Some(0),
                expiry: None,
                idle_timeout: None,
            }),
            Helper::String(s) => Err(serde::de::Error::custom(format!(
                "invalid cache config string: {s:?}, expected \"disable\""
            ))),
            Helper::Struct {
                size_mb,
                expiry,
                idle_timeout,
            } => Ok(Self {
                size_mb,
                expiry,
                idle_timeout,
            }),
        }
    }
}

pub type UnrecognizedValues = HashMap<String, serde_yaml::Value>;
pub type UnrecognizedKeys = HashSet<String>;

pub fn copy_unrecognized_keys_from_config(
    result: &mut UnrecognizedKeys,
    prefix: &str,
    unrecognized: &UnrecognizedValues,
) {
    result.extend(unrecognized.keys().map(|k| format!("{prefix}{k}")));
}

#[cfg(all(test, feature = "mbtiles"))]
mod mbtiles_tests {
    use super::*;
    use crate::config::file::tiles::mbtiles::MbtConfig;
    use crate::config::primitives::IdResolver;

    #[tokio::test]
    #[tracing_test::traced_test]
    async fn test_invalid_path_warns_instead_of_failing() {
        let invalid_path = PathBuf::from("/nonexistent/path/");
        let invalid_source = PathBuf::from("/nonexistent/path/to/file.mbtiles");
        let mut file_sources = BTreeMap::new();
        file_sources.insert(
            "test_source".to_string(),
            FileConfigSrc::Path(invalid_source.clone()),
        );
        let mut config = FileConfigEnum::<MbtConfig>::Config(FileConfig {
            paths: OptOneMany::One(invalid_path.clone()),
            sources: Some(file_sources),
            custom: MbtConfig::default(),
        });

        let idr = IdResolver::new(&[]);
        let result = resolve_files(&mut config, &idr, &["mbtiles"], CachePolicy::default()).await;

        let (sources, warnings) = result.unwrap();
        assert_eq!(sources.len(), 0);
        assert_eq!(warnings.len(), 2);
    }
}

#[cfg(all(test, feature = "pmtiles"))]
mod pmtiles_tests {
    use super::*;
    use crate::config::file::tiles::pmtiles::PmtConfig;
    use crate::config::primitives::IdResolver;

    #[tokio::test]
    #[tracing_test::traced_test]
    async fn test_invalid_path_warns_instead_of_failing() {
        let invalid_path = PathBuf::from("/nonexistent/path/");
        let invalid_source = PathBuf::from("/nonexistent/path/to/file.pmtiles");
        let mut file_sources = BTreeMap::new();
        file_sources.insert(
            "test_source".to_string(),
            FileConfigSrc::Path(invalid_source.clone()),
        );
        let mut config = FileConfigEnum::<PmtConfig>::Config(FileConfig {
            paths: OptOneMany::One(invalid_path.clone()),
            sources: Some(file_sources),
            custom: PmtConfig::default(),
        });

        let idr = IdResolver::new(&[]);
        let result = resolve_files(&mut config, &idr, &["pmtiles"], CachePolicy::default()).await;

        let (sources, warnings) = result.unwrap();
        assert_eq!(sources.len(), 0);
        assert_eq!(warnings.len(), 2);
    }
}