geolith-tiles-builder 0.4.2

Builds tiles from OpenStreetMap and Overture Maps: protomaps-schema vector PMTiles, Terrain-RGB, raster archives and 3D Tiles from Gaussian splats
Documentation
//! Markers that say whether the sort runs of a folder can be resumed from.
//!
//! `--resume` merges the runs it finds in `--tmpdir`. That is right only when
//! every run of phase 1 is there and none was consumed. A run missing from
//! the merge leaves its tiles out of the archive without any error, so the
//! build writes two markers and refuses to resume without them:
//!
//! - [`PHASE1_MARKER`] is written when phase 1 ends. It holds the number of
//!   runs. A folder from a phase 1 that stopped early has no marker, and a
//!   folder that lost a run does not match its count.
//! - [`RECLAIM_MARKER`] is written before a `--reclaim-chunks` merge touches
//!   the first run. From then on the runs are consumed (holes, deleted
//!   files), and no resume is possible.

use std::fs::File;
use std::io::Write;
use std::path::Path;

use crate::sort::chunk::RUN_EXTENSION;
use crate::sort::error::SortRunError;
use crate::tiles_error::{Result, TilesError};

/// The file that says phase 1 finished, and how many runs it wrote.
pub const PHASE1_MARKER: &str = "phase1.complete";

/// The file that says a `--reclaim-chunks` merge started consuming the runs.
pub const RECLAIM_MARKER: &str = "merge.reclaiming";

fn write_marker(dir: &Path, name: &str, text: &str) -> Result<()> {
    let path = dir.join(name);
    let io = |op: &'static str| {
        let path = path.clone();
        move |source| TilesError::from(SortRunError::Io { op, path, source })
    };
    let mut file = File::create(&path).map_err(io("create"))?;
    file.write_all(text.as_bytes()).map_err(io("write"))?;
    file.sync_all().map_err(io("sync"))?;
    Ok(())
}

/// Remove what a build wrote into its sort folder, and nothing else.
///
/// That is the sort runs (`chunk_NNNNNN.run`) and the two markers. The folder
/// itself goes only when it is empty afterwards. `--tmpdir` is the user's
/// folder: a file the build did not write, or a sub-folder, stays.
///
/// # Errors
///
/// The first file that cannot be removed (the others are still tried).
pub fn clean_up(dir: &Path) -> std::io::Result<()> {
    let mut first_error = None;
    for entry in std::fs::read_dir(dir)? {
        let path = match entry {
            Ok(entry) => entry.path(),
            Err(e) => {
                first_error.get_or_insert(e);
                continue;
            }
        };
        let name = path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or_default();
        let ours = name == PHASE1_MARKER
            || name == RECLAIM_MARKER
            || (name.starts_with("chunk_") && path.extension().is_some_and(|e| e == RUN_EXTENSION));
        if ours
            && path.is_file()
            && let Err(e) = std::fs::remove_file(&path)
        {
            first_error.get_or_insert(e);
        }
    }
    if let Some(e) = first_error {
        return Err(e);
    }
    match std::fs::remove_dir(dir) {
        Err(e) if e.kind() != std::io::ErrorKind::DirectoryNotEmpty => Err(e),
        _ => Ok(()),
    }
}

/// Record that phase 1 wrote `runs` runs into `dir`.
///
/// # Errors
///
/// [`SortRunError::Io`] when the marker cannot be written and synced.
pub fn mark_phase1_complete(dir: &Path, runs: usize) -> Result<()> {
    write_marker(dir, PHASE1_MARKER, &format!("runs {runs}\n"))
}

/// Record that a merge is about to consume the runs of `dir`.
///
/// # Errors
///
/// [`SortRunError::Io`] when the marker cannot be written and synced. The
/// merge must not start then: it could not say afterwards that it consumed.
pub fn mark_reclaiming(dir: &Path) -> Result<()> {
    write_marker(
        dir,
        RECLAIM_MARKER,
        "the runs of this folder are being consumed\n",
    )
}

/// Check that the `found` runs in `dir` are all the runs of a finished phase 1
/// and that no merge consumed them.
///
/// # Errors
///
/// - [`TilesError::ChunksConsumed`] when a `--reclaim-chunks` merge started,
/// - [`TilesError::Phase1Incomplete`] when phase 1 left no marker,
/// - [`TilesError::RunCountMismatch`] when the runs are not the counted ones.
pub fn check_resumable(dir: &Path, found: usize) -> Result<()> {
    if dir.join(RECLAIM_MARKER).exists() {
        return Err(TilesError::ChunksConsumed {
            path: dir.to_path_buf(),
        });
    }
    let marker = dir.join(PHASE1_MARKER);
    let text = std::fs::read_to_string(&marker).map_err(|source| {
        if source.kind() == std::io::ErrorKind::NotFound {
            TilesError::Phase1Incomplete {
                path: dir.to_path_buf(),
            }
        } else {
            // A marker that is there and cannot be read (permissions, a
            // directory) is not a phase 1 that did not finish.
            TilesError::from(SortRunError::Io {
                op: "read",
                path: marker.clone(),
                source,
            })
        }
    })?;
    let expected: usize = text
        .strip_prefix("runs ")
        .and_then(|rest| rest.trim().parse().ok())
        .ok_or_else(|| TilesError::Phase1Incomplete {
            path: dir.to_path_buf(),
        })?;
    if expected != found {
        return Err(TilesError::RunCountMismatch {
            path: dir.to_path_buf(),
            expected,
            found,
        });
    }
    Ok(())
}

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

    #[test]
    fn a_folder_without_the_marker_is_not_resumable() {
        let dir = tempfile::tempdir().expect("tmpdir");
        assert!(matches!(
            check_resumable(dir.path(), 3),
            Err(TilesError::Phase1Incomplete { .. })
        ));
    }

    #[test]
    fn the_count_must_match() {
        let dir = tempfile::tempdir().expect("tmpdir");
        mark_phase1_complete(dir.path(), 3).expect("mark");
        assert!(check_resumable(dir.path(), 3).is_ok());
        assert!(matches!(
            check_resumable(dir.path(), 2),
            Err(TilesError::RunCountMismatch {
                expected: 3,
                found: 2,
                ..
            })
        ));
    }

    #[test]
    fn a_reclaiming_merge_makes_the_folder_unresumable_whatever_the_count() {
        let dir = tempfile::tempdir().expect("tmpdir");
        mark_phase1_complete(dir.path(), 3).expect("mark");
        mark_reclaiming(dir.path()).expect("mark");
        assert!(matches!(
            check_resumable(dir.path(), 3),
            Err(TilesError::ChunksConsumed { .. })
        ));
    }

    #[test]
    fn a_marker_with_junk_is_refused() {
        let dir = tempfile::tempdir().expect("tmpdir");
        std::fs::write(dir.path().join(PHASE1_MARKER), "garbage").expect("write");
        assert!(matches!(
            check_resumable(dir.path(), 1),
            Err(TilesError::Phase1Incomplete { .. })
        ));
    }

    #[test]
    fn clean_up_removes_the_runs_and_markers_and_keeps_foreign_files() {
        let dir = tempfile::tempdir().expect("tmpdir");
        let p = dir.path();
        std::fs::write(p.join("chunk_000000.run"), b"run").expect("write");
        std::fs::write(p.join("chunk_000001.run"), b"run").expect("write");
        mark_phase1_complete(p, 2).expect("mark");
        mark_reclaiming(p).expect("mark");
        std::fs::write(p.join("notes.txt"), b"mine").expect("write");
        std::fs::write(p.join("other.run"), b"not a chunk").expect("write");
        std::fs::create_dir(p.join("sub")).expect("dir");
        std::fs::write(p.join("sub/chunk_000009.run"), b"nested").expect("write");

        clean_up(p).expect("clean up");

        let mut left: Vec<String> = std::fs::read_dir(p)
            .expect("read")
            .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned())
            .collect();
        left.sort();
        assert_eq!(left, ["notes.txt", "other.run", "sub"]);
        assert!(p.join("sub/chunk_000009.run").exists(), "no descent");
    }

    #[test]
    fn clean_up_removes_a_folder_that_holds_only_the_build_files() {
        let dir = tempfile::tempdir().expect("tmpdir");
        let sort = dir.path().join("sort");
        std::fs::create_dir(&sort).expect("dir");
        std::fs::write(sort.join("chunk_000000.run"), b"run").expect("write");
        mark_phase1_complete(&sort, 1).expect("mark");
        clean_up(&sort).expect("clean up");
        assert!(!sort.exists());
    }
}