geolith-cli 0.3.6

Rust vector tile generator — OSM + Overture Maps → protomaps PMTiles
Documentation
#![allow(clippy::unwrap_used)] // tests and benches may unwrap (AGENTS.md).

//! A write that fails must fail the build: never an archive with fewer tiles.
//!
//! The binary runs under a file size limit (`ulimit -f`), which makes any
//! write past the limit fail with an OS error, as a full disk does. The limit
//! sweeps from far too small to enough: every run either fails loudly, naming
//! a path and the OS error, with no archive left behind, or produces the same
//! archive as an unlimited run.

use std::path::{Path, PathBuf};
use std::process::{Command, Output};

const GEOLITH: &str = env!("CARGO_BIN_EXE_geolith");

fn tiles_args(dir: &Path) -> Vec<String> {
    let inputs = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/golden/tiles");
    let path = |p: &Path| p.to_str().unwrap().to_string();
    vec![
        "--data".into(),
        path(&inputs.join("overture")),
        "--natural-earth".into(),
        path(&inputs.join("ne.sqlite")),
        "--land-polygons".into(),
        path(&inputs.join("land")),
        "--water-polygons".into(),
        path(&inputs.join("water")),
        "--output".into(),
        path(&dir.join("out.pmtiles")),
        "--tmpdir".into(),
        path(&dir.join("tmp")),
        "--roads-source".into(),
        "overture".into(),
        "--no-conflate".into(),
        "--bbox".into(),
        "-0.3,51.4,0.3,51.6".into(),
        "--max-zoom".into(),
        "10".into(),
    ]
}

/// Run the binary with writes limited to `blocks` blocks per file (when set).
/// The limit signal is ignored so the failed write returns an error instead
/// of killing the process.
fn run_limited(blocks: Option<u64>, args: &[String]) -> Output {
    let script = blocks.map_or_else(
        || "exec \"$0\" \"$@\"".to_string(),
        |n| format!("ulimit -f {n}; trap '' XFSZ; exec \"$0\" \"$@\""),
    );
    Command::new("sh")
        .arg("-c")
        .arg(script)
        .arg(GEOLITH)
        .args(args)
        .env("RAYON_NUM_THREADS", "2")
        .output()
        .unwrap()
}

#[test]
fn a_write_limit_never_gives_an_archive_with_fewer_tiles() {
    let reference_dir = tempfile::tempdir().unwrap();
    let reference = run_limited(None, &tiles_args(reference_dir.path()));
    assert!(
        reference.status.success(),
        "{}",
        String::from_utf8_lossy(&reference.stderr)
    );
    let expected = std::fs::read(reference_dir.path().join("out.pmtiles")).unwrap();
    assert!(expected.len() > 1000);

    let mut failures = 0;
    let mut successes = 0;
    for blocks in [0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 8192] {
        let dir = tempfile::tempdir().unwrap();
        let args = tiles_args(dir.path());
        let output = run_limited(Some(blocks), &args);
        let out = dir.path().join("out.pmtiles");
        let stderr = String::from_utf8_lossy(&output.stderr);
        if output.status.success() {
            successes += 1;
            assert_eq!(
                std::fs::read(&out).unwrap(),
                expected,
                "limit {blocks}: the build succeeded with another archive"
            );
        } else {
            failures += 1;
            assert!(
                output.status.code().is_some_and(|c| c != 0),
                "limit {blocks}: ended by a signal, not an error: {stderr}"
            );
            assert!(stderr.contains("error:"), "limit {blocks}: {stderr}");
            assert!(
                stderr.contains("File too large") || stderr.contains("os error 27"),
                "limit {blocks}: no OS error in: {stderr}"
            );
            let dir_name = dir.path().to_str().unwrap();
            assert!(
                stderr.contains(dir_name),
                "limit {blocks}: no path in: {stderr}"
            );
            assert!(
                !out.exists(),
                "limit {blocks}: a failed build left an archive behind"
            );
            if blocks == 0 {
                // Nothing can be written: the first run is the first to fail.
                assert!(
                    stderr.contains("chunk_000000.run"),
                    "limit 0 must stop at the first sort run: {stderr}"
                );
            }
        }
    }
    assert!(failures >= 3, "the sweep must hit failures: {failures}");
    assert!(
        successes >= 1,
        "the sweep must also reach success: {successes}"
    );
}

#[test]
fn resume_after_a_reclaiming_merge_says_so_and_stops() {
    let dir = tempfile::tempdir().unwrap();
    let tmp = dir.path().join("tmp");
    std::fs::create_dir_all(&tmp).unwrap();
    std::fs::write(tmp.join("chunk_000000.run"), b"GLRN").unwrap();
    std::fs::write(tmp.join("phase1.complete"), "runs 1\n").unwrap();
    std::fs::write(tmp.join("merge.reclaiming"), "consumed\n").unwrap();
    let mut args = tiles_args(dir.path());
    args.push("--resume".into());
    let output = run_limited(None, &args);
    assert!(!output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("cannot be resumed"), "{stderr}");
    assert!(stderr.contains("--reclaim-chunks"), "{stderr}");
    assert!(stderr.contains(tmp.to_str().unwrap()), "{stderr}");
    assert!(!dir.path().join("out.pmtiles").exists());
    assert!(tmp.join("chunk_000000.run").exists(), "nothing was touched");
}

/// A sort folder that cannot be written (read-only) stops the build at the
/// first run, naming the folder and the OS error; no archive appears.
#[cfg(unix)]
#[test]
fn a_sort_folder_that_cannot_be_written_fails_the_build() {
    use std::os::unix::fs::PermissionsExt;
    let dir = tempfile::tempdir().unwrap();
    let tmp = dir.path().join("tmp");
    std::fs::create_dir_all(&tmp).unwrap();
    std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o555)).unwrap();
    if std::fs::File::create(tmp.join("probe")).is_ok() {
        // Running as root: permissions do not stop the write, so the test
        // cannot make the folder unwritable.
        std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o755)).unwrap();
        return;
    }
    let output = run_limited(None, &tiles_args(dir.path()));
    std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o755)).unwrap();
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(!output.status.success(), "the build must fail: {stderr}");
    assert!(stderr.contains(tmp.to_str().unwrap()), "{stderr}");
    assert!(stderr.contains("Permission denied"), "{stderr}");
    assert!(!dir.path().join("out.pmtiles").exists());
}