use std::path::{Path, PathBuf};
use crate::config::TilesConfig;
use crate::source;
use crate::tiles_error::{Result, TilesError};
const GIB: u64 = 1024 * 1024 * 1024;
const CHUNK_PER_INPUT_BYTE: f64 = 0.48;
const OUTPUT_PER_INPUT_BYTE: f64 = 0.35;
const NODE_STORE_PER_PBF_BYTE: f64 = 1.2;
const MARGIN: f64 = 1.1;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Estimate {
pub chunks: u64,
pub output: u64,
pub node_store: u64,
}
impl Estimate {
pub(crate) fn for_inputs(input_bytes: u64, pbf_bytes: u64) -> Self {
let scale = |per_byte: f64, bytes: u64| (per_byte * bytes as f64 * MARGIN) as u64;
Self {
chunks: scale(CHUNK_PER_INPUT_BYTE, input_bytes),
output: scale(OUTPUT_PER_INPUT_BYTE, input_bytes),
node_store: scale(NODE_STORE_PER_PBF_BYTE, pbf_bytes),
}
}
}
#[derive(Debug)]
struct Need {
probe: PathBuf,
device: u64,
chunks: u64,
output: u64,
node_store: u64,
credit: u64,
transient: u64,
}
impl Need {
const fn peak(&self, reclaim_chunks: bool) -> u64 {
let both = if reclaim_chunks {
if self.chunks > self.output {
self.chunks
} else {
self.output
}
} else {
self.chunks + self.output
};
let net = (both + self.node_store).saturating_sub(self.credit);
if self.credit > 0 && self.chunks > 0 && net < self.transient {
self.transient
} else {
net
}
}
fn what(&self) -> &'static str {
match (self.chunks > 0, self.output > 0, self.node_store > 0) {
(true, true, true) => "sort chunks, output archive and node store",
(true, true, false) => "sort chunks and output archive",
(true, false, true) => "sort chunks and node store",
(false, true, true) => "output archive and node store",
(true, false, false) => "sort chunks",
(false, true, false) => "output archive",
(false, false, true) => "node store",
(false, false, false) => "nothing",
}
}
}
pub(crate) fn preflight(config: &TilesConfig, tmp_dir: &Path) -> Result<()> {
let (estimate, reclaimable) = estimate_for(config)?;
check(
&needs(config, tmp_dir, estimate, reclaimable),
config.reclaim_chunks,
free_bytes,
)
}
fn estimate_for(config: &TilesConfig) -> Result<(Estimate, u64)> {
let mut parquet = 0u64;
for src in source::discover(config.data.as_path())? {
if src
.target_layers
.iter()
.any(|&l| config.overture_enabled(l))
{
parquet += std::fs::metadata(&src.path)?.len();
}
}
let pbf = match &config.osm_pbf {
Some(path) => std::fs::metadata(path)?.len(),
None => 0,
};
let reclaimable = if config.reclaim_source_after_read {
parquet
} else {
0
};
Ok((Estimate::for_inputs(parquet + pbf, pbf), reclaimable))
}
fn needs(config: &TilesConfig, tmp_dir: &Path, estimate: Estimate, reclaimable: u64) -> Vec<Need> {
let output_dir = config
.output
.parent()
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."));
let transient = transient_bytes(config, estimate);
let mut parts: Vec<(&Path, u64, u64, u64, u64, u64)> = vec![
(tmp_dir, estimate.chunks, 0, 0, 0, 0),
(output_dir, 0, estimate.output, 0, 0, 0),
(config.data.as_path(), 0, 0, 0, reclaimable, transient),
];
if let Some(store) = &config.node_store
&& !store.exists()
&& let Some(dir) = store.parent().filter(|p| !p.as_os_str().is_empty())
{
parts.push((dir, 0, 0, estimate.node_store, 0, 0));
}
let mut needs: Vec<Need> = Vec::new();
for (path, chunks, output, node_store, credit, part_transient) in parts {
let probe = existing_ancestor(path);
let device = device_of(&probe);
if let Some(same) = needs.iter_mut().find(|n| n.device == device) {
same.chunks += chunks;
same.output += output;
same.node_store += node_store;
same.credit += credit;
same.transient = same.transient.max(part_transient);
} else {
needs.push(Need {
probe,
device,
chunks,
output,
node_store,
credit,
transient: part_transient,
});
}
}
needs
}
fn transient_bytes(config: &TilesConfig, estimate: Estimate) -> u64 {
let threads = config.threads.unwrap_or_else(|| {
std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(4)
});
let buffers =
(threads as u128 * config.effective_chunk_bytes() as u128).min(u128::from(u64::MAX)) as u64;
buffers.min(estimate.chunks)
}
fn check(needs: &[Need], reclaim_chunks: bool, free: impl Fn(&Path) -> Option<u64>) -> Result<()> {
for need in needs {
let Some(available) = free(&need.probe) else {
continue;
};
let bytes = need.peak(reclaim_chunks);
if available < bytes {
return Err(TilesError::InsufficientDisk {
path: need.probe.clone(),
need_gib: bytes.div_ceil(GIB),
free_gib: available / GIB,
what: need.what(),
reclaim_chunks,
});
}
}
Ok(())
}
fn existing_ancestor(path: &Path) -> PathBuf {
let absolute = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf());
absolute
.ancestors()
.find(|p| p.exists())
.map_or_else(|| PathBuf::from("/"), Path::to_path_buf)
}
#[cfg(unix)]
fn device_of(path: &Path) -> u64 {
use std::os::unix::fs::MetadataExt;
std::fs::metadata(path).map_or(0, |m| m.dev())
}
#[cfg(not(unix))]
fn device_of(_path: &Path) -> u64 {
0
}
#[cfg(unix)]
#[allow(
unsafe_code,
clippy::useless_conversion,
clippy::unnecessary_cast,
reason = "statvfs fills a MaybeUninit; its field widths differ by platform"
)]
fn free_bytes(path: &Path) -> Option<u64> {
use std::os::unix::ffi::OsStrExt;
let c_path = std::ffi::CString::new(path.as_os_str().as_bytes()).ok()?;
let mut stat = std::mem::MaybeUninit::<libc::statvfs>::uninit();
let result = unsafe { libc::statvfs(c_path.as_ptr(), stat.as_mut_ptr()) };
if result != 0 {
return None;
}
let stat = unsafe { stat.assume_init() };
Some(u64::from(stat.f_bavail) * (stat.f_frsize as u64))
}
#[cfg(not(unix))]
fn free_bytes(_path: &Path) -> Option<u64> {
None
}
#[cfg(test)]
mod tests {
use super::*;
fn config(output: &Path, reclaim: bool) -> TilesConfig {
let mut config = TilesConfig::new("/data", "/ne", "/w", "/l", output);
config.reclaim_chunks = reclaim;
config
}
const PLANET_TRANSIENT: u64 = 64 * GIB;
fn need(chunks: u64, output: u64) -> Need {
Need {
probe: PathBuf::from("/vol"),
device: 1,
chunks,
output,
node_store: 0,
credit: 0,
transient: PLANET_TRANSIENT,
}
}
#[test]
fn the_estimate_scales_with_the_inputs_and_carries_the_margin() {
let e = Estimate::for_inputs(1000 * GIB, 100 * GIB);
let near = |got: u64, gib: u64| got.abs_diff(gib * GIB) < GIB / 1000;
assert!(near(e.chunks, 528), "{}", e.chunks);
assert!(near(e.output, 385), "{}", e.output);
assert!(near(e.node_store, 132), "{}", e.node_store);
}
#[test]
fn chunks_and_archive_add_up_unless_the_merge_reclaims() {
let n = need(200 * GIB, 190 * GIB);
assert_eq!(n.peak(false), 390 * GIB);
assert_eq!(n.peak(true), 200 * GIB);
}
#[test]
fn one_volume_holds_what_the_build_puts_there() {
let dir = tempfile::tempdir().expect("tmpdir");
let est = Estimate {
chunks: 200 * GIB,
output: 190 * GIB,
node_store: 100 * GIB,
};
let mut config = config(&dir.path().join("out.pmtiles"), false);
config.node_store = Some(dir.path().join("nodes.store"));
let n = needs(&config, &dir.path().join("sort"), est, 0);
assert_eq!(n.len(), 1, "same volume folds to one need");
assert_eq!(n[0].peak(false), 490 * GIB);
assert_eq!(n[0].peak(true), 300 * GIB);
assert_eq!(n[0].what(), "sort chunks, output archive and node store");
}
#[test]
fn a_short_volume_stops_the_build_and_names_the_gib() {
let err =
check(&[need(300 * GIB + 1, 0)], false, |_| Some(100 * GIB)).expect_err("short volume");
match err {
TilesError::InsufficientDisk {
need_gib,
free_gib,
what,
..
} => {
assert_eq!(need_gib, 301);
assert_eq!(free_gib, 100);
assert_eq!(what, "sort chunks");
}
other => panic!("wrong error: {other}"),
}
}
#[test]
fn enough_free_space_passes_and_an_unknown_volume_is_skipped() {
assert!(check(&[need(10 * GIB, 0)], false, |_| Some(100 * GIB)).is_ok());
assert!(check(&[need(u64::MAX / 2, 0)], false, |_| None).is_ok());
}
#[test]
fn the_temp_dir_reports_free_space() {
#[cfg(unix)]
assert!(free_bytes(&std::env::temp_dir()).is_some_and(|b| b > 0));
}
fn planet_need(
dir: &Path,
reclaim_chunks: bool,
reclaim_sources: bool,
) -> std::result::Result<(), (u64, u64)> {
let mut config = config(&dir.join("out.pmtiles"), reclaim_chunks);
config.data = dir.join("overture");
config.node_store = Some(dir.join("nodes.store"));
let estimate = Estimate::for_inputs(606 * GIB, 90 * GIB);
let credit = if reclaim_sources { 516 * GIB } else { 0 };
let n = needs(&config, &dir.join("sort"), estimate, credit);
assert_eq!(n.len(), 1, "one volume");
match check(&n, reclaim_chunks, |_| Some(150 * GIB)) {
Ok(()) => Ok(()),
Err(TilesError::InsufficientDisk {
need_gib, free_gib, ..
}) => Err((need_gib, free_gib)),
Err(other) => panic!("wrong error: {other}"),
}
}
#[test]
fn the_planet_needs_what_each_reclaim_flag_leaves() {
let dir = tempfile::tempdir().expect("tmpdir");
let p = dir.path();
assert_eq!(planet_need(p, false, false), Err((673, 150)));
assert_eq!(planet_need(p, true, false), Err((439, 150)));
assert_eq!(planet_need(p, false, true), Err((157, 150)));
assert_eq!(planet_need(p, true, true), Ok(()));
}
#[test]
fn a_source_credit_never_takes_the_peak_below_the_floor() {
let mut n = need(10 * GIB, 0);
n.credit = 500 * GIB;
assert_eq!(n.peak(false), PLANET_TRANSIENT);
let mut sources_only = need(0, 0);
sources_only.credit = 500 * GIB;
assert_eq!(sources_only.peak(false), 0);
}
#[test]
fn only_a_reclaiming_build_counts_its_sources_as_freed() {
let dir = tempfile::tempdir().expect("tmpdir");
let part = dir.path().join("theme=buildings/type=building");
std::fs::create_dir_all(&part).expect("dirs");
std::fs::write(part.join("a.parquet"), vec![0u8; 1000]).expect("write");
std::fs::write(part.join("b.parquet"), vec![0u8; 234]).expect("write");
let mut config = config(&dir.path().join("out.pmtiles"), false);
config.data = dir.path().to_path_buf();
assert_eq!(estimate_for(&config).expect("estimate").1, 0);
config.reclaim_source_after_read = true;
assert_eq!(estimate_for(&config).expect("estimate").1, 1234);
}
#[test]
fn a_credit_that_covers_the_peak_still_leaves_room_to_start() {
let mut n = need(320 * GIB, 233 * GIB);
n.node_store = 119 * GIB;
n.credit = 516 * GIB;
assert_eq!(n.peak(true), PLANET_TRANSIENT, "the floor, not zero");
let err = check(&[need_with(&n)], true, |_| Some(40 * GIB)).expect_err("40 GiB free");
match err {
TilesError::InsufficientDisk {
need_gib, free_gib, ..
} => assert_eq!((need_gib, free_gib), (64, 40)),
other => panic!("wrong error: {other}"),
}
assert!(check(&[need_with(&n)], true, |_| Some(70 * GIB)).is_ok());
}
#[test]
fn without_a_credit_the_peak_is_not_raised_to_the_floor() {
let n = need(10 * GIB, 0);
assert_eq!(n.peak(false), 10 * GIB);
}
fn need_with(n: &Need) -> Need {
Need {
probe: n.probe.clone(),
device: n.device,
chunks: n.chunks,
output: n.output,
node_store: n.node_store,
credit: n.credit,
transient: n.transient,
}
}
#[test]
fn the_transient_floor_is_the_buffers_the_build_fills() {
let dir = tempfile::tempdir().expect("tmpdir");
let mut config = config(&dir.path().join("out.pmtiles"), false);
config.threads = Some(4);
config.chunk_size_mb = 64;
let small = Estimate {
chunks: 3 * 1024 * 1024,
output: 2 * 1024 * 1024,
node_store: 0,
};
assert_eq!(
transient_bytes(&config, small),
3 * 1024 * 1024,
"never more than the chunks the build writes"
);
let planet = Estimate {
chunks: 300 * GIB,
output: 200 * GIB,
node_store: 100 * GIB,
};
assert_eq!(
transient_bytes(&config, planet),
4 * 64 * 1024 * 1024,
"4 workers x 64 MB"
);
}
#[test]
fn a_small_build_is_not_asked_for_a_planets_transient_room() {
let dir = tempfile::tempdir().expect("tmpdir");
let est = Estimate {
chunks: 3 * 1024 * 1024,
output: 2 * 1024 * 1024,
node_store: 0,
};
let mut config = config(&dir.path().join("out.pmtiles"), false);
config.reclaim_source_after_read = true;
config.threads = Some(4);
config.chunk_size_mb = 64;
let n = needs(&config, &dir.path().join("sort"), est, 3 * 1024 * 1024);
assert_eq!(n.len(), 1, "same volume folds to one need");
assert_eq!(n[0].peak(false), 3 * 1024 * 1024);
assert!(
check(&n, false, |_| Some(11 * GIB),).is_ok(),
"11 GiB free is enough for a 3 MiB build"
);
}
}