martin 1.5.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
use std::path::PathBuf;

use clap::Parser;
use clap::builder::Styles;
use clap::builder::styling::AnsiColor;

use super::connections::Arguments;
use super::srv::SrvArgs;
use crate::MartinError::ConfigAndConnectionsError;
use crate::MartinResult;
#[cfg(feature = "postgres")]
use crate::config::args::PostgresArgs;
use crate::config::file::Config;
#[cfg(any(
    feature = "unstable-cog",
    feature = "mbtiles",
    feature = "pmtiles",
    feature = "sprites",
    feature = "styles",
))]
use crate::config::file::FileConfigEnum;
#[cfg(feature = "fonts")]
use crate::config::file::fonts::FontConfig;
#[cfg(feature = "postgres")]
use crate::config::primitives::env::Env;

/// Defines the styles used for the CLI help output.
const HELP_STYLES: Styles = Styles::styled()
    .header(AnsiColor::Blue.on_default().bold())
    .usage(AnsiColor::Blue.on_default().bold())
    .literal(AnsiColor::White.on_default())
    .placeholder(AnsiColor::Green.on_default());

#[derive(Parser, Debug, PartialEq, Default)]
#[command(
    about,
    version,
    after_help = "Use RUST_LOG environment variable to control logging level, e.g. RUST_LOG=debug or RUST_LOG=martin=debug.\nUse RUST_LOG_FORMAT environment variable to control output format: json, full, compact (default), bare or pretty.\nSee https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html for more information.",
    styles = HELP_STYLES
)]
pub struct Args {
    #[command(flatten)]
    pub meta: MetaArgs,
    #[command(flatten)]
    pub extras: ExtraArgs,
    #[command(flatten)]
    pub srv: SrvArgs,
    #[cfg(feature = "postgres")]
    #[command(flatten)]
    pub pg: Option<PostgresArgs>,
}

// None of these params will be transferred to the config
#[derive(Parser, Debug, Clone, PartialEq, Default)]
#[command(about, version)]
pub struct MetaArgs {
    // config may need a   conflicts_with = "SourcesArgs"
    // see https://github.com/clap-rs/clap/discussions/4562
    /// Path to config file. If set, no tile source-related parameters are allowed.
    #[arg(short, long)]
    pub config: Option<PathBuf>,
    /// Save resulting config to a file or use "-" to print to stdout.
    /// By default, only print if sources are auto-detected.
    #[arg(long)]
    pub save_config: Option<PathBuf>,
    /// Connection strings, e.g. `postgres://...` or `/path/to/files`
    pub connection: Vec<String>,
}

#[derive(Parser, Debug, Clone, PartialEq, Default)]
#[command()]
pub struct ExtraArgs {
    /// Export a directory with SVG files as a sprite source. Can be specified multiple times.
    #[arg(short = 's', long)]
    #[cfg(feature = "sprites")]
    pub sprite: Vec<PathBuf>,
    /// Export a font file or a directory with font files as a font source (recursive). Can be specified multiple times.
    #[arg(short, long)]
    #[cfg(feature = "fonts")]
    pub font: Vec<PathBuf>,
    /// Export a style file or a directory with style files as a style source (recursive). Can be specified multiple times.
    #[arg(short = 'S', long)]
    #[cfg(feature = "styles")]
    pub style: Vec<PathBuf>,
}

impl Args {
    pub fn merge_into_config<'a>(
        self,
        config: &mut Config,
        #[cfg(feature = "postgres")] env: &impl Env<'a>,
    ) -> MartinResult<()> {
        if self.meta.config.is_some() && !self.meta.connection.is_empty() {
            return Err(ConfigAndConnectionsError(self.meta.connection));
        }

        if self.srv.cache_size.is_some() {
            config.cache_size_mb = self.srv.cache_size;
        }

        self.srv.merge_into_config(&mut config.srv);

        #[cfg_attr(
            not(feature = "_tiles"),
            expect(
                unused_mut,
                reason = "postgres may modify the cli strings to process input params"
            )
        )]
        let mut cli_strings = Arguments::new(self.meta.connection);

        #[cfg(feature = "postgres")]
        {
            let pg_args = self.pg.unwrap_or_default();
            if config.postgres.is_none() {
                config.postgres = pg_args.into_config(&mut cli_strings, env);
            } else {
                // config was loaded from a file, we can only apply a few CLI overrides to it
                pg_args.override_config(&mut config.postgres, env);
            }
        }

        #[cfg(feature = "pmtiles")]
        if !cli_strings.is_empty() {
            config.pmtiles = parse_file_args(&mut cli_strings, &["pmtiles"], true);
        }

        #[cfg(feature = "mbtiles")]
        if !cli_strings.is_empty() {
            config.mbtiles = parse_file_args(&mut cli_strings, &["mbtiles"], false);
        }

        #[cfg(feature = "unstable-cog")]
        if !cli_strings.is_empty() {
            config.cog = parse_file_args(&mut cli_strings, &["tif", "tiff"], false);
        }

        #[cfg(feature = "styles")]
        if !self.extras.style.is_empty() {
            config.styles = FileConfigEnum::new(self.extras.style);
        }

        #[cfg(feature = "sprites")]
        if !self.extras.sprite.is_empty() {
            config.sprites = FileConfigEnum::new(self.extras.sprite);
        }

        #[cfg(feature = "fonts")]
        if !self.extras.font.is_empty() {
            config.fonts = FontConfig::new(self.extras.font);
        }

        cli_strings.check()
    }
}

/// Check if a string is a valid [`url::Url`] with a specified extension.
#[cfg(any(feature = "unstable-cog", feature = "mbtiles", feature = "pmtiles"))]
fn is_url(s: &str, extension: &[&str]) -> bool {
    let Ok(url) = url::Url::parse(s) else {
        return false;
    };
    match url.scheme() {
        "s3" | "s3a" | "gs" | "az" | "adl" | "azure" | "abfs" | "abfss" => {
            url.path().split('/').any(|segment| {
                segment
                    .rsplit('.')
                    .next()
                    .is_some_and(|ext| extension.contains(&ext))
            })
        }
        "http" | "https" | "file" => url
            .path()
            .rsplit('.')
            .next()
            .is_some_and(|ext| extension.contains(&ext)),
        _ => false,
    }
}

/// Check if a string is a `file:` scheme URI with a specified extension.
///
/// This is used for `SQLite` connection strings like `file:name.mbtiles?mode=memory&cache=shared`
#[cfg(any(feature = "unstable-cog", feature = "mbtiles", feature = "pmtiles"))]
fn is_file_scheme_uri(s: &str, extensions: &[&str]) -> bool {
    let Ok(url) = url::Url::parse(s) else {
        return false;
    };
    if url.scheme() != "file" {
        return false;
    }
    url.path()
        .rsplit('.')
        .next()
        .is_some_and(|ext| extensions.contains(&ext))
}

#[cfg(any(feature = "unstable-cog", feature = "mbtiles", feature = "pmtiles"))]
pub fn parse_file_args<T: crate::config::file::ConfigurationLivecycleHooks>(
    cli_strings: &mut Arguments,
    extensions: &[&str],
    allow_url: bool,
) -> FileConfigEnum<T> {
    use super::State::{Ignore, Share, Take};

    let paths = cli_strings.process(|s| {
        let path = PathBuf::from(s);
        if allow_url && is_url(s, extensions) {
            Take(path)
        } else if is_file_scheme_uri(s, extensions) {
            // Handle file: scheme URIs (SQLite connection strings) as valid paths
            Take(path)
        } else if path.is_dir() {
            Share(path)
        } else if path.is_file()
            && extensions.iter().any(|&expected_ext| {
                path.extension()
                    .is_some_and(|actual_ext| actual_ext == expected_ext)
            })
        {
            Take(path)
        } else {
            Ignore
        }
    });

    FileConfigEnum::new(paths)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::MartinError::UnrecognizableConnections;
    use crate::config::args::PreferredEncoding;
    #[cfg(feature = "postgres")]
    use crate::config::primitives::env::FauxEnv;

    fn parse(args: &[&str]) -> MartinResult<(Config, MetaArgs)> {
        let args = Args::parse_from(args);
        let meta = args.meta.clone();
        let mut config = Config::default();
        args.merge_into_config(
            &mut config,
            #[cfg(feature = "postgres")]
            &FauxEnv::default(),
        )?;
        Ok((config, meta))
    }

    #[test]
    fn cli_no_args() {
        let args = parse(&["martin"]).unwrap();
        let expected = (Config::default(), MetaArgs::default());
        assert_eq!(args, expected);
    }

    #[cfg(feature = "postgres")]
    #[test]
    fn cli_with_config() {
        use crate::config::file::postgres::PostgresConfig;
        use crate::config::primitives::OptOneMany;

        let args = parse(&["martin", "--config", "c.toml"]).unwrap();
        let meta = MetaArgs {
            config: Some(PathBuf::from("c.toml")),
            ..Default::default()
        };
        assert_eq!(args, (Config::default(), meta));

        let args = parse(&["martin", "--config", "c.toml", "--save-config", "s.toml"]).unwrap();
        let meta = MetaArgs {
            config: Some(PathBuf::from("c.toml")),
            save_config: Some(PathBuf::from("s.toml")),
            ..Default::default()
        };
        assert_eq!(args, (Config::default(), meta));

        let args = parse(&["martin", "postgres://connection"]).unwrap();
        let cfg = Config {
            postgres: OptOneMany::One(PostgresConfig {
                connection_string: Some("postgres://connection".to_string()),
                ..Default::default()
            }),
            ..Default::default()
        };
        let meta = MetaArgs {
            connection: vec!["postgres://connection".to_string()],
            ..Default::default()
        };
        assert_eq!(args, (cfg, meta));
    }

    #[test]
    fn cli_encoding_arguments() {
        let config1 = parse(&["martin", "--preferred-encoding", "brotli"]);
        let config2 = parse(&["martin", "--preferred-encoding", "br"]);
        let config3 = parse(&["martin", "--preferred-encoding", "gzip"]);
        let config4 = parse(&["martin"]);

        assert_eq!(
            config1.unwrap().0.srv.preferred_encoding,
            Some(PreferredEncoding::Brotli)
        );
        assert_eq!(
            config2.unwrap().0.srv.preferred_encoding,
            Some(PreferredEncoding::Brotli)
        );
        assert_eq!(
            config3.unwrap().0.srv.preferred_encoding,
            Some(PreferredEncoding::Gzip)
        );
        assert_eq!(config4.unwrap().0.srv.preferred_encoding, None);
    }

    #[cfg(any(feature = "unstable-cog", feature = "mbtiles", feature = "pmtiles"))]
    #[test]
    fn test_is_file_scheme_uri() {
        // Valid file scheme URIs
        assert!(is_file_scheme_uri("file:test.mbtiles", &["mbtiles"]));
        assert!(is_file_scheme_uri(
            "file:test.mbtiles?mode=memory&cache=shared",
            &["mbtiles"]
        ));
        assert!(is_file_scheme_uri(
            "file:/path/to/test.mbtiles",
            &["mbtiles"]
        ));
        assert!(is_file_scheme_uri("file:data.pmtiles", &["pmtiles"]));
        assert!(is_file_scheme_uri("file:image.tiff", &["tiff", "tif"]));

        // Invalid cases
        assert!(!is_file_scheme_uri(
            "http://example.com/test.mbtiles",
            &["mbtiles"]
        ));
        assert!(!is_file_scheme_uri("test.mbtiles", &["mbtiles"]));
        assert!(!is_file_scheme_uri("file:test.txt", &["mbtiles"]));
        assert!(!is_file_scheme_uri("file:", &["mbtiles"]));
        assert!(!is_file_scheme_uri("", &["mbtiles"]));
    }

    #[test]
    fn cli_bad_arguments() {
        for params in [
            ["martin", "--config", "c.toml", "--tmp"].as_slice(),
            ["martin", "--config", "c.toml", "-c", "t.toml"].as_slice(),
        ] {
            let res = Args::try_parse_from(params);
            assert!(res.is_err(), "Expected error, got: {res:?} for {params:?}");
        }
    }

    #[test]
    #[cfg(feature = "postgres")]
    fn cli_bad_parsed_arguments() {
        let args = Args::parse_from(["martin", "--config", "c.toml", "postgres://a"]);

        let mut config = Config::default();
        let err = args
            .merge_into_config(&mut config, &FauxEnv::default())
            .unwrap_err();
        assert!(matches!(err, ConfigAndConnectionsError(..)));
    }

    #[test]
    fn cli_unknown_con_str() {
        let args = Args::parse_from(["martin", "foobar"]);

        let mut config = Config::default();
        let err = args
            .merge_into_config(
                &mut config,
                #[cfg(feature = "postgres")]
                &FauxEnv::default(),
            )
            .unwrap_err();
        let bad = vec!["foobar".to_string()];
        assert!(matches!(err, UnrecognizableConnections(v) if v == bad));
    }

    #[cfg(all(feature = "pmtiles", feature = "mbtiles", feature = "unstable-cog"))]
    #[tokio::test]
    async fn cli_multiple_extensions() {
        use std::ffi::OsString;

        let script = include_str!("../../../../tests/fixtures/mbtiles/json.sql");
        let (_mbt, _conn, file) = mbtiles::temp_named_mbtiles("json.mbtiles", script).await;
        let args = Args::parse_from([
            OsString::from("martin"),
            OsString::from("../tests/fixtures/pmtiles/png.pmtiles"),
            file.as_os_str().to_owned(),
            OsString::from("../tests/fixtures/cog/rgba_u8_nodata.tiff"),
            OsString::from("../tests/fixtures/cog/rgba_u8.tif"),
        ]);

        let mut config = Config::default();
        args.merge_into_config(
            &mut config,
            #[cfg(feature = "postgres")]
            &FauxEnv::default(),
        )
        .unwrap();
        insta::assert_yaml_snapshot!(config, @r#"
        pmtiles: "../tests/fixtures/pmtiles/png.pmtiles"
        mbtiles: "file:json.mbtiles?mode=memory&cache=shared"
        cog:
          - "../tests/fixtures/cog/rgba_u8_nodata.tiff"
          - "../tests/fixtures/cog/rgba_u8.tif"
        "#);
    }

    #[cfg(all(feature = "pmtiles", feature = "mbtiles", feature = "unstable-cog"))]
    #[test]
    fn cli_directories_propagate() {
        let args = Args::parse_from(["martin", "../tests/fixtures/"]);

        let mut config = Config::default();
        let err = args.merge_into_config(
            &mut config,
            #[cfg(feature = "postgres")]
            &FauxEnv::default(),
        );
        assert!(err.is_ok());
        insta::assert_yaml_snapshot!(config, @r#"
        pmtiles: "../tests/fixtures/"
        mbtiles: "../tests/fixtures/"
        cog: "../tests/fixtures/"
        "#);
    }
}