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
//! Give the disk space of a file's read prefix back to the file system.
//!
//! The merge reads every run once from front to back. Once a block is in
//! memory its bytes on disk are dead, so the merge punches a hole over them:
//! the file keeps its length, and the file system frees the blocks. Chunks
//! and the archive then do not peak together.

use std::fs::File;
use std::sync::atomic::{AtomicBool, Ordering};

/// The step of a punch: the file system frees whole blocks, and a punch
/// call per block of a run would cost more than it frees.
const STEP: u64 = 8 * 1024 * 1024;

/// The alignment a hole must have. Every file system the build runs on
/// (APFS, ext4, XFS) frees whole 4 KiB blocks at least.
const ALIGN: u64 = 4096;

/// Free the bytes of `file` from `from` up to the last aligned offset below
/// `read_to`, when at least [`STEP`] bytes are ready.
///
/// Returns the new start of the unfreed part, or `None` when nothing was
/// freed (not enough bytes yet, or the file system cannot punch holes, in
/// which case the file is only deleted at its end).
pub fn punch_whole_blocks(file: &File, from: u64, read_to: u64) -> Option<u64> {
    let upto = read_to - read_to % ALIGN;
    if upto < from + STEP {
        return None;
    }
    match punch(file, from, upto - from) {
        Ok(()) => Some(upto),
        Err(e) => {
            // Reclaiming is an optimisation of the disk peak, never a
            // condition of a correct merge: the bytes stay where they are
            // and the run is still deleted at its end. Say so once.
            static WARNED: AtomicBool = AtomicBool::new(false);
            if !WARNED.swap(true, Ordering::Relaxed) {
                tracing::warn!(
                    "cannot give disk space back while merging ({e}); \
                     --reclaim-chunks only deletes each run at its end"
                );
            }
            None
        }
    }
}

#[cfg(target_os = "macos")]
#[allow(
    unsafe_code,
    reason = "fcntl(F_PUNCHHOLE) takes a pointer to a fpunchhole_t that lives through the call"
)]
fn punch(file: &File, offset: u64, len: u64) -> std::io::Result<()> {
    use std::os::fd::AsRawFd;
    let request = libc::fpunchhole_t {
        fp_flags: 0,
        reserved: 0,
        fp_offset: libc::off_t::try_from(offset).map_err(std::io::Error::other)?,
        fp_length: libc::off_t::try_from(len).map_err(std::io::Error::other)?,
    };
    // SAFETY: the descriptor is open for writing (the reader opened it so),
    // and `request` is a valid fpunchhole_t that outlives the call.
    let result = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_PUNCHHOLE, &request) };
    if result == -1 {
        return Err(std::io::Error::last_os_error());
    }
    Ok(())
}

#[cfg(target_os = "linux")]
#[allow(
    unsafe_code,
    reason = "fallocate(PUNCH_HOLE | KEEP_SIZE) takes only integers and a descriptor"
)]
fn punch(file: &File, offset: u64, len: u64) -> std::io::Result<()> {
    use std::os::fd::AsRawFd;
    // SAFETY: the descriptor is open for writing (the reader opened it so);
    // the call reads no memory.
    let result = unsafe {
        libc::fallocate(
            file.as_raw_fd(),
            libc::FALLOC_FL_PUNCH_HOLE | libc::FALLOC_FL_KEEP_SIZE,
            libc::off_t::try_from(offset).map_err(std::io::Error::other)?,
            libc::off_t::try_from(len).map_err(std::io::Error::other)?,
        )
    };
    if result == -1 {
        return Err(std::io::Error::last_os_error());
    }
    Ok(())
}

#[cfg(not(any(target_os = "macos", target_os = "linux")))]
fn punch(_file: &File, _offset: u64, _len: u64) -> std::io::Result<()> {
    Err(std::io::Error::from(std::io::ErrorKind::Unsupported))
}

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

    #[test]
    fn nothing_is_freed_before_a_step_is_ready() {
        let file = tempfile::tempfile().expect("tempfile");
        assert_eq!(punch_whole_blocks(&file, 0, STEP - 1), None);
    }

    #[test]
    fn a_punched_file_keeps_its_length_and_reads_zeros_in_the_hole() {
        let dir = tempfile::tempdir().expect("tmpdir");
        let path = dir.path().join("hole");
        let mut file = File::create(&path).expect("create");
        file.write_all(&vec![0xAB; (STEP * 2) as usize])
            .expect("write");
        file.sync_all().expect("sync");
        drop(file);
        let file = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open(&path)
            .expect("open");
        let Some(upto) = punch_whole_blocks(&file, 0, STEP + 5000) else {
            // The file system cannot punch holes (the call said so): there is
            // nothing to check here, and the skip is not silent.
            eprintln!("skipped: this file system cannot punch holes");
            return;
        };
        assert_eq!(upto % ALIGN, 0);
        assert!(upto >= STEP);
        let data = std::fs::read(&path).expect("read");
        assert_eq!(data.len() as u64, STEP * 2);
        assert!(data[..upto as usize].iter().all(|b| *b == 0));
        assert!(data[upto as usize..].iter().all(|b| *b == 0xAB));
    }
}