geolith-cli 0.4.2

Rust vector tile generator — OSM + Overture Maps → protomaps PMTiles
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
#![warn(missing_docs)]

//! geolith — core pipeline for generating protomaps-schema `PMTiles`
//! from Overture Maps Parquet data.
//!
//! The pipeline runs in four phases:
//! 1. **Read + Process** — discover Parquet files, read features, route to
//!    layer processors, project to world coordinates, clip to tiles, snap to
//!    tile-local integers, encode MVT geometry commands.
//! 2. **External Sort** — buffer `SortEntry` items, flush sorted chunks to
//!    disk when buffer exceeds threshold.
//! 3. **K-Way Merge** — merge all sorted chunks into globally-sorted order.
//! 4. **`PMTiles` Write** — group entries by tile, encode MVT tiles, gzip
//!    compress, write to `PMTiles` archive in Hilbert order.

pub mod cli;
mod cli_error;
pub mod config;

pub use cli_error::CliError;
pub use geolith::error;
pub use geolith::output;
pub use geolith::{conflation, progress, source};
pub use geolith_dataset_builder as dataset;
pub use geolith_search_builder as geocoding;
pub use geolith_tiles_builder::{
    geometry, layers, raster, reconstruct, sort, splat, terrain, tile, timing,
};

/// Pipeline action selected from the configured output format.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PipelineAction {
    /// Run the geocoding pipeline.
    Geocoding,
    /// Build the routing graph from the OSM PBF and write it to a `.glx` file.
    Routing(std::path::PathBuf),
    /// Run the tile pipeline (protomaps basemap schema).
    Tiles,
    /// Output format is recognised but not yet wired (no-op).
    UnsupportedFormat(String),
}

/// Decide which pipeline action a config selects without executing it.
///
/// Pure function: no I/O, no logging. Returns the action that
/// [`run`] would dispatch to. Useful for unit testing the dispatch
/// logic without actually running the planet-scale pipeline.
#[must_use]
pub fn select_action(config: &config::Config) -> PipelineAction {
    match config.output_format.as_str() {
        "geocoding" => PipelineAction::Geocoding,
        "routing" => {
            let out = config
                .routing_output
                .clone()
                .unwrap_or_else(|| std::path::PathBuf::from("planet-routing.glx"));
            PipelineAction::Routing(out)
        }
        "tiles" => PipelineAction::Tiles,
        other => PipelineAction::UnsupportedFormat(other.to_owned()),
    }
}

/// Initialise tracing with the elapsed-time formatter.
///
/// Safe to call once per process. Subsequent calls are no-ops because
/// `tracing_subscriber::fmt` panics on second registration.
fn init_tracing() {
    timing::init();
    // Logs go to stderr: stdout belongs to the command's own output, which
    // scripts read line by line (`VERIFY OK`, the stage dir, the JSON of
    // `dataset downloads check`).
    tracing_subscriber::fmt()
        .with_timer(timing::ElapsedTimer)
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
        )
        .with_writer(std::io::stderr)
        .init();
}

/// Run the command selected by the process arguments.
///
/// # Errors
///
/// Propagates any error produced by the selected pipeline.
pub fn run() -> Result<(), CliError> {
    let command = cli::parse_args();
    init_tracing();
    run_command(command)
}

/// Dispatch an already-parsed [`cli::Command`] to its pipeline.
///
/// Split from [`run`] so the dispatch can be exercised without reading the
/// process arguments, mirroring [`select_action`].
///
/// # Errors
///
/// Propagates any error produced by the selected pipeline.
pub fn run_command(command: cli::Command) -> Result<(), CliError> {
    tracing::info!("geolith v{}", env!("CARGO_PKG_VERSION"));

    match command {
        cli::Command::Terrain(args) => run_terrain(&args),
        cli::Command::SplatTiles(args) => run_splat_tiles(&args),
        cli::Command::Raster(args) => run_raster(&args),
        cli::Command::Reconstruct(args) => run_reconstruct(&args),
        cli::Command::Dataset(args) => dataset::run(&args).map_err(CliError::from),
        cli::Command::Notices => {
            print!("{}", cli::NOTICE);
            Ok(())
        }
        cli::Command::Tiles(config) => {
            tracing::debug!("config: {:?}", config);
            run_with_config(&config)
        }
    }
}

/// The process exit code of an error: the code of a
/// [`dataset::exit::Exit`], else `1`.
#[must_use]
pub fn exit_code(error: &CliError) -> i32 {
    match error {
        CliError::Dataset(error) => error.exit_code(),
        _ => 1,
    }
}

/// Run the raster basemap archiver for a parsed [`cli::RasterArgs`].
///
/// # Errors
///
/// Propagates template/bbox validation errors, download failures that
/// survive retry, and archive write errors.
pub fn run_raster(args: &cli::RasterArgs) -> Result<(), CliError> {
    let options = args.build_options()?;
    raster::run(&options, &args.output).map_err(CliError::from)
}

/// Build Terrain-RGB `PMTiles` from a `GeoTIFF` DEM.
///
/// # Errors
///
/// Returns an error when the DEM cannot be read or the archive cannot be written.
pub fn run_terrain(args: &cli::TerrainArgs) -> Result<(), CliError> {
    let options = args.tiler_options()?;
    terrain::run(&args.dem, args.dem_crs, &args.output, &args.name, &options)
        .map_err(CliError::from)
}

/// Build an OGC 3D Tiles tileset from a trained Gaussian splat PLY.
///
/// # Errors
///
/// Returns an error when the PLY cannot be read or the tileset cannot be written.
pub fn run_splat_tiles(args: &cli::SplatTilesArgs) -> Result<(), CliError> {
    splat::run(&args.job()).map_err(CliError::from)
}

/// Run the drone-video photogrammetry pipeline for a parsed
/// [`cli::ReconstructArgs`].
///
/// # Errors
///
/// Propagates frame-extraction, COLMAP, brush-training, or tile-writing
/// errors.
pub fn run_reconstruct(args: &cli::ReconstructArgs) -> Result<(), CliError> {
    reconstruct::run_reconstruct(&args.video, &args.output, &args.options()).map_err(CliError::from)
}

/// Execute the pipeline with a pre-built [`Config`](config::Config).
///
/// This is the entry point used by tests and embedders that already
/// have a `Config`. Logging must be initialised separately (e.g. via
/// `init_tracing`) when calling from a binary entry point.
///
/// # Errors
///
/// Propagates any error produced by the underlying pipeline.
pub fn run_with_config(config: &config::Config) -> Result<(), CliError> {
    for warning in config.deprecation_warnings() {
        tracing::warn!("{warning}");
    }
    match select_action(config) {
        PipelineAction::Geocoding => run_search(config),
        PipelineAction::Routing(out) => run_routing(config, &out),
        PipelineAction::UnsupportedFormat(format) => Err(CliError::UnsupportedFormat { format }),
        PipelineAction::Tiles => {
            geolith_tiles_builder::run(&config.tiles()?).map_err(CliError::from)
        }
    }
}

/// Build the geocoding index of the Overture data in `config`.
///
/// # Errors
///
/// Fails when `--data` or the output path is missing, or the build fails.
fn run_search(config: &config::Config) -> Result<(), CliError> {
    let data = config.required_path(config::PathFlag::Data)?;
    let output = match config.geocoding_output.clone() {
        Some(path) => path,
        None => geocoding::pipeline::default_geocoding_output(
            config.required_path(config::PathFlag::Output)?,
            &config.geocoding_format,
        ),
    };
    let mut options = geolith_search_builder::SearchOptions::new(data, output);
    options.format.clone_from(&config.geocoding_format);
    options.osm_pbf.clone_from(&config.osm_pbf);
    options.india_outline.clone_from(&config.india_outline);
    options.bbox.clone_from(&config.bbox);
    options.tmpdir.clone_from(&config.tmpdir);
    options.node_store.clone_from(&config.node_store);
    options.reuse_node_cache = config.reuse.node_cache;
    options
        .wikimedia_importance
        .clone_from(&config.wikimedia_importance);
    options.pg_index_flavor = config.pg_index_flavor;
    geolith_search_builder::run(&options).map_err(CliError::from)
}

/// Build the routing graph from `config.osm_pbf` and write it to `out`.
///
/// # Errors
///
/// Fails when no PBF is configured, the graph cannot be built, or the file
/// cannot be written.
fn run_routing(config: &config::Config, out: &std::path::Path) -> Result<(), CliError> {
    let Some(pbf) = config.osm_pbf.as_deref() else {
        return Err(CliError::RoutingNeedsOsmPbf);
    };
    let mut options = geolith_routing_builder::RoutingOptions::new(pbf, out);
    options.tmpdir.clone_from(&config.tmpdir);
    options
        .default_speeds
        .clone_from(&config.routing_default_speeds);
    options.admins.clone_from(&config.routing_admins);
    options.timezones.clone_from(&config.routing_timezones);
    options
        .predicted_speeds
        .clone_from(&config.routing_predicted_speeds);
    options.metric_out.clone_from(&config.routing_metric_out);
    options.cch.clone_from(&config.routing_cch);
    // The builder takes the Survey of India outline as polygons: the
    // readers that parse it stay out of the routing crate.
    if let (Some(_), Some(path)) = (
        config.routing_admins.as_deref(),
        config.india_outline.as_deref(),
    ) {
        options.india = Some(
            geocoding::india::IndiaOutline::load(path)?
                .polygons()
                .clone(),
        );
    }
    geolith_routing_builder::run(&options).map_err(CliError::from)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::Config;

    fn make_config(output_format: &str) -> Config {
        Config {
            data: Some(std::path::PathBuf::from("/dev/null")),
            osm_pbf: None,
            natural_earth: Some(std::path::PathBuf::from("/dev/null")),
            water_polygons: Some(std::path::PathBuf::from("/dev/null")),
            land_polygons: Some(std::path::PathBuf::from("/dev/null")),
            india_boundary: None,
            india_outline: None,
            output: Some(std::path::PathBuf::from("/dev/null")),
            output_format: output_format.to_string(),
            tile_format: "mvt".to_string(),
            geocoding_format: "pg-copy".to_string(),
            pg_index_flavor: crate::config::PgIndexFlavor::default(),
            geocoding_output: None,
            wikimedia_importance: None,
            routing_output: None,
            routing_predicted_speeds: None,
            routing_metric_out: None,
            routing_cch: Vec::new(),
            routing_default_speeds: None,
            routing_admins: None,
            routing_timezones: None,
            bbox: None,
            max_zoom: 15,
            threads: None,
            chunk_size_mb: 0,
            tmpdir: None,
            node_store: None,
            reuse: crate::config::RunReuse {
                node_cache: false,
                resume: false,
            },
            buildings_source: "both".to_string(),
            places_source: None,
            roads_source: "both".to_string(),
            pois_source: "both".to_string(),
            water_source: "both".to_string(),
            landuse_source: "both".to_string(),
            divisions_source: "overture".to_string(),
            landcover_source: "overture".to_string(),
            bathymetry_source: "overture".to_string(),
            bridge_dir: None,
            bridge_files: vec![],
            no_conflate: false,
            reclaim_source_after_read: false,
            allow_missing_type: false,
            reclaim_chunks: false,
            no_disk_check: false,
        }
    }

    #[test]
    fn select_action_geocoding() {
        let cfg = make_config("geocoding");
        assert_eq!(select_action(&cfg), PipelineAction::Geocoding);
    }

    #[test]
    fn select_action_routing_default_path() {
        let cfg = make_config("routing");
        assert_eq!(
            select_action(&cfg),
            PipelineAction::Routing(std::path::PathBuf::from("planet-routing.glx"))
        );
    }

    #[test]
    fn select_action_routing_explicit_path() {
        let mut cfg = make_config("routing");
        cfg.routing_output = Some(std::path::PathBuf::from("/tmp/custom.glx"));
        assert_eq!(
            select_action(&cfg),
            PipelineAction::Routing(std::path::PathBuf::from("/tmp/custom.glx"))
        );
    }

    #[test]
    fn select_action_tiles() {
        let cfg = make_config("tiles");
        assert_eq!(select_action(&cfg), PipelineAction::Tiles);
    }

    #[test]
    fn select_action_unsupported_format() {
        let cfg = make_config("osrm");
        assert_eq!(
            select_action(&cfg),
            PipelineAction::UnsupportedFormat("osrm".to_string())
        );
    }

    #[test]
    fn run_with_config_rejects_an_unsupported_format() {
        let cfg = make_config("unknown");
        let err = run_with_config(&cfg).expect_err("a typo must not exit 0");
        assert!(format!("{err}").contains("'unknown'"), "{err}");
    }

    #[test]
    fn run_with_config_routing_needs_an_osm_pbf() {
        let mut cfg = make_config("routing");
        cfg.routing_output = Some(std::path::PathBuf::from("/tmp/graph.glx"));
        let err = run_with_config(&cfg).expect_err("no graph without a PBF");
        assert!(format!("{err}").contains("--osm-pbf"), "{err}");
    }

    #[test]
    fn run_with_config_tiles_surfaces_an_unreadable_data_dir() {
        let cfg = make_config("tiles");
        let err = run_with_config(&cfg).expect_err("/dev/null is not a source directory");
        assert!(
            !format!("{err}").is_empty(),
            "the failure is reported rather than panicking"
        );
    }

    /// Run `body` with a real subscriber installed.
    ///
    /// `tracing` macros evaluate their field expressions only when a
    /// subscriber is interested in the event, so without one the
    /// instrumentation in `run_terrain` and `run_splat_tiles` never executes.
    fn with_tracing<T>(body: impl FnOnce() -> T) -> T {
        let subscriber = tracing_subscriber::fmt()
            .with_test_writer()
            .with_max_level(tracing::Level::TRACE)
            .finish();
        tracing::subscriber::with_default(subscriber, body)
    }

    /// A 4x4 UTM 32N `GeoTIFF` DEM.
    ///
    /// `geolith/tests/terrain.rs` exercises the full matrix of georeferencing
    /// tag combinations; this fixture only needs to be readable so the command
    /// wrappers here execute end-to-end.
    fn write_dem(values: Vec<f32>, nodata: Option<&str>) -> tempfile::NamedTempFile {
        use std::io::{Seek as _, Write as _};

        use tiff::encoder::{TiffEncoder, colortype};
        use tiff::tags::Tag;

        let mut buffer = std::io::Cursor::new(Vec::new());
        {
            let mut encoder = TiffEncoder::new(&mut buffer).expect("tiff encoder");
            let mut image = encoder
                .new_image::<colortype::Gray32Float>(4, 4)
                .expect("image encoder");
            let directory = image.encoder();
            directory
                .write_tag(Tag::Unknown(33_550), &[10.0_f64, 10.0, 0.0][..])
                .expect("pixel scale");
            directory
                .write_tag(
                    Tag::Unknown(33_922),
                    &[0.0_f64, 0.0, 0.0, 400_000.0, 5_100_000.0, 0.0][..],
                )
                .expect("tiepoint");
            directory
                .write_tag(
                    Tag::Unknown(34_735),
                    &[1_u32, 1, 0, 1, 3072, 0, 1, 32_632][..],
                )
                .expect("geokeys");
            if let Some(sentinel) = nodata {
                directory
                    .write_tag(Tag::Unknown(42_113), sentinel)
                    .expect("nodata");
            }
            image.write_data(&values).expect("write samples");
        }
        buffer.rewind().expect("rewind");

        let mut file = tempfile::Builder::new()
            .suffix(".tif")
            .tempfile()
            .expect("temp file");
        file.write_all(&buffer.into_inner()).expect("write tiff");
        file.flush().expect("flush");
        file
    }

    fn write_ply(vertex_count: usize) -> tempfile::NamedTempFile {
        use std::io::Write as _;

        const PROPERTIES: [&str; 14] = [
            "x", "y", "z", "f_dc_0", "f_dc_1", "f_dc_2", "opacity", "scale_0", "scale_1",
            "scale_2", "rot_0", "rot_1", "rot_2", "rot_3",
        ];

        let mut file = tempfile::NamedTempFile::new().expect("temp file");
        let mut header = String::from("ply\nformat binary_little_endian 1.0\n");
        header.push_str(&format!("element vertex {vertex_count}\n"));
        for property in PROPERTIES {
            header.push_str(&format!("property float {property}\n"));
        }
        header.push_str("end_header\n");
        file.write_all(header.as_bytes()).expect("header");

        for index in 0..vertex_count {
            let offset = index as f32;
            for value in [
                offset,
                offset * 0.5,
                offset * 0.25,
                0.4,
                0.5,
                0.6,
                1.1,
                -2.0,
                -2.1,
                -2.2,
                1.0,
                0.0,
                0.0,
                0.0,
            ] {
                file.write_all(&value.to_le_bytes()).expect("vertex");
            }
        }
        file.flush().expect("flush");
        file
    }

    fn terrain_args(dem: &std::path::Path, output: &std::path::Path) -> cli::TerrainArgs {
        cli::TerrainArgs {
            dem: vec![dem.to_path_buf()],
            clip: None,
            output: output.to_path_buf(),
            encoding: "mapbox".to_owned(),
            min_zoom: 12,
            max_zoom: 13,
            tile_size: 256,
            dem_crs: None,
            name: "terrain".to_owned(),
        }
    }

    fn splat_args(ply: &std::path::Path, output: &std::path::Path) -> cli::SplatTilesArgs {
        cli::SplatTilesArgs {
            ply: ply.to_path_buf(),
            output: output.to_path_buf(),
            longitude: 7.9797,
            latitude: 45.9756,
            altitude: 2250.0,
            max_splats_per_tile: 4,
            max_depth: 2,
            root_geometric_error: 64.0,
            antialiased: false,
            emit_scene_spz: true,
            crop_percentile: 0.0,
            scale: 1.0,
            coverage_boost_scale: 0.0,
        }
    }

    #[test]
    fn run_terrain_writes_an_archive() {
        let values: Vec<f32> = (0..16).map(|i| 1000.0 + i as f32).collect();
        let dem = write_dem(values, None);
        let dir = tempfile::tempdir().expect("tempdir");
        let output = dir.path().join("terrain.pmtiles");

        with_tracing(|| run_terrain(&terrain_args(dem.path(), &output)))
            .expect("terrain pipeline runs");

        let bytes = std::fs::read(&output).expect("archive exists");
        assert_eq!(&bytes[..7], b"PMTiles");
    }

    #[test]
    fn run_terrain_writes_an_archive_for_valid_and_all_nodata_dems() {
        let dir = tempfile::tempdir().expect("tempdir");

        let values: Vec<f32> = (0..16).map(|i| 1000.0 + i as f32).collect();
        let dem = write_dem(values, None);
        let with_samples = dir.path().join("a.pmtiles");
        with_tracing(|| run_terrain(&terrain_args(dem.path(), &with_samples)))
            .expect("a DEM with valid samples must tile");

        let dem = write_dem(vec![-9999.0; 16], Some("-9999"));
        let all_nodata = dir.path().join("b.pmtiles");
        with_tracing(|| run_terrain(&terrain_args(dem.path(), &all_nodata)))
            .expect("an all-nodata DEM must still tile");

        for path in [&with_samples, &all_nodata] {
            let bytes = std::fs::read(path).expect("archive must exist on disk");
            assert_eq!(
                &bytes[..7],
                b"PMTiles",
                "{path:?} must be a PMTiles archive"
            );
        }
    }

    #[test]
    fn run_terrain_propagates_failures() {
        let dir = tempfile::tempdir().expect("tempdir");
        let mut args = terrain_args(
            std::path::Path::new("/nonexistent/dem.tif"),
            &dir.path().join("out.pmtiles"),
        );

        args.encoding = "rainbow".to_owned();
        assert!(
            with_tracing(|| run_terrain(&args)).is_err(),
            "the encoding is validated before the DEM is opened"
        );

        args.encoding = "mapbox".to_owned();
        args.dem_crs = Some(27_700);
        assert!(
            with_tracing(|| run_terrain(&args)).is_err(),
            "an unsupported EPSG fails before the DEM is read"
        );

        args.dem_crs = None;
        assert!(
            with_tracing(|| run_terrain(&args)).is_err(),
            "a missing DEM surfaces as an error"
        );
    }

    #[test]
    fn run_splat_tiles_writes_a_tileset_and_scene() {
        let ply = write_ply(32);
        let dir = tempfile::tempdir().expect("tempdir");
        let output = dir.path().join("tileset");

        with_tracing(|| run_splat_tiles(&splat_args(ply.path(), &output)))
            .expect("splat pipeline runs");

        assert!(output.join("tileset.json").is_file());
        assert!(output.join("tiles/0.glb").is_file());
        assert!(
            output.join("scene.spz").is_file(),
            "--emit-scene-spz writes the standalone packet"
        );
    }

    #[test]
    fn run_splat_tiles_skips_the_scene_when_not_requested() {
        let ply = write_ply(8);
        let dir = tempfile::tempdir().expect("tempdir");
        let output = dir.path().join("tileset");

        let mut args = splat_args(ply.path(), &output);
        args.emit_scene_spz = false;
        with_tracing(|| run_splat_tiles(&args)).expect("splat pipeline runs");

        assert!(output.join("tileset.json").is_file());
        assert!(!output.join("scene.spz").exists());
    }

    #[test]
    fn run_splat_tiles_propagates_failures() {
        let dir = tempfile::tempdir().expect("tempdir");
        assert!(
            with_tracing(|| run_splat_tiles(&splat_args(
                std::path::Path::new("/nonexistent/scene.ply"),
                &dir.path().join("tileset"),
            )))
            .is_err(),
            "a missing PLY surfaces as an error"
        );

        let empty = write_ply(0);
        let err =
            with_tracing(|| run_splat_tiles(&splat_args(empty.path(), &dir.path().join("empty"))))
                .expect_err("an empty cloud cannot be tiled");
        assert!(format!("{err}").contains("empty splat cloud"), "{err}");
    }

    #[test]
    fn run_command_dispatches_every_verb() {
        let dir = tempfile::tempdir().expect("tempdir");

        let values: Vec<f32> = (0..16).map(|i| 1000.0 + i as f32).collect();
        let dem = write_dem(values, None);
        let terrain_out = dir.path().join("dispatched.pmtiles");
        with_tracing(|| {
            run_command(cli::Command::Terrain(Box::new(terrain_args(
                dem.path(),
                &terrain_out,
            ))))
        })
        .expect("the terrain verb reaches run_terrain");
        assert!(terrain_out.exists());

        let ply = write_ply(8);
        let splat_out = dir.path().join("dispatched-tileset");
        with_tracing(|| {
            run_command(cli::Command::SplatTiles(Box::new(splat_args(
                ply.path(),
                &splat_out,
            ))))
        })
        .expect("the splat verb reaches run_splat_tiles");
        assert!(splat_out.join("tileset.json").exists());

        let config = make_config("not-a-real-format");
        let err = with_tracing(|| run_command(cli::Command::Tiles(Box::new(config))))
            .expect_err("the flat invocation reaches run_with_config, which rejects the format");
        assert!(format!("{err}").contains("not-a-real-format"), "{err}");

        let raster_args = cli::RasterArgs {
            url_template: "http://127.0.0.1:1/{z}/{x}/{y}.jpg".into(),
            output: dir.path().join("dispatched-raster.pmtiles"),
            min_zoom: 0,
            max_zoom: 0,
            bbox: None,
            bbox_min_zoom: 0,
            format: "jpeg".into(),
            concurrency: 1,
            request_delay_ms: 0,
            attempts: 1,
            cache_dir: Some(dir.path().join("raster-cache")),
            name: "dispatch-test".into(),
            attribution: None,
        };
        let err = with_tracing(|| run_command(cli::Command::Raster(Box::new(raster_args))))
            .expect_err("port 1 refuses connections, proving dispatch reached run_raster");
        assert!(format!("{err}").contains("raster source error"));
    }
}