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
//! The open-file limit the merge needs.
//!
//! The k-way merge opens every sort run at once. A planet build writes
//! thousands of runs, and the default soft limit is 256 on macOS and 1024 on
//! Linux. Without a check the merge fails with `Too many open files` after
//! phase 1 has taken hours; with `--reclaim-chunks` the runs are then half
//! consumed and `--resume` is no longer possible. So the build raises the soft
//! limit towards what it needs before phase 2, and stops with a clear message
//! if the hard limit is lower.

use crate::tiles_error::{Result, TilesError};

/// Files the build needs besides the runs: the archive, the inputs still open,
/// the logs, the tile encoder's scratch.
const RESERVED_FILES: u64 = 128;

/// Make sure the process may open `runs` sort runs at once.
///
/// # Errors
///
/// [`TilesError::TooManyRuns`] when the limit cannot be raised enough.
pub(crate) fn ensure_open_files(runs: usize) -> Result<()> {
    let need = runs as u64 + RESERVED_FILES;
    let limit = raise_open_file_limit(need);
    check(runs, limit)
}

/// Whether `limit` open files are enough for `runs` runs.
fn check(runs: usize, limit: u64) -> Result<()> {
    let need = runs as u64 + RESERVED_FILES;
    if limit >= need {
        Ok(())
    } else {
        Err(TilesError::TooManyRuns { runs, limit, need })
    }
}

/// Raise the soft open-file limit towards `want` (never above the hard limit)
/// and return the limit now in force.
#[cfg(unix)]
#[allow(
    unsafe_code,
    reason = "libc getrlimit and setrlimit on local structs; each unsafe block has a SAFETY comment"
)]
fn raise_open_file_limit(want: u64) -> u64 {
    let mut limit = libc::rlimit {
        rlim_cur: 0,
        rlim_max: 0,
    };
    // SAFETY: `limit` is a valid, writable rlimit for the call to fill.
    if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &raw mut limit) } != 0 {
        return 256;
    }
    let target = want.min(limit.rlim_max);
    if limit.rlim_cur < target {
        let raised = libc::rlimit {
            rlim_cur: target,
            rlim_max: limit.rlim_max,
        };
        // SAFETY: `raised` is a valid rlimit no higher than the hard limit.
        if unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &raw const raised) } == 0 {
            return target;
        }
    }
    limit.rlim_cur
}

#[cfg(not(unix))]
fn raise_open_file_limit(_want: u64) -> u64 {
    u64::MAX
}

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

    #[test]
    fn a_limit_below_the_runs_stops_the_merge_with_the_numbers() {
        match check(5000, 1024).expect_err("5000 runs do not fit in 1024 files") {
            TilesError::TooManyRuns { runs, limit, need } => {
                assert_eq!((runs, limit, need), (5000, 1024, 5128));
            }
            other => panic!("wrong error: {other}"),
        }
    }

    #[test]
    fn a_limit_with_room_for_the_runs_and_the_reserve_passes() {
        assert!(check(100, 1024).is_ok());
        assert!(check(896, 1024).is_ok(), "896 + 128 = 1024 fits exactly");
        assert!(check(897, 1024).is_err());
    }

    #[cfg(unix)]
    #[test]
    fn the_soft_limit_is_raised_when_the_hard_limit_allows_it() {
        // 3000 files is within the hard limit of every system the build runs
        // on (macOS caps a raise at 10240).
        ensure_open_files(3000 - RESERVED_FILES as usize).expect("raised to 3000");
        let mut limit = libc::rlimit {
            rlim_cur: 0,
            rlim_max: 0,
        };
        #[allow(unsafe_code, reason = "reads the limit the test just raised")]
        // SAFETY: `limit` is a valid, writable rlimit for the call to fill.
        let status = unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &raw mut limit) };
        assert_eq!(status, 0);
        assert!(limit.rlim_cur >= 3000, "{}", limit.rlim_cur);
    }
}