use std::fs;
use std::path::{Path, PathBuf};
use crate::error::{DatasetError, IoOp, IoResultExt as _, IoStepExt as _, Result, WithinExt as _};
use crate::cdse::{self, Client, ListLine};
use crate::cli::{BaselinePassArgs, NormalsArgs, ValuesArgs};
use crate::config::{DatasetConfig, Reader};
use crate::country::CountryConfig;
use crate::exit::Exit;
use crate::layout::{Settings, settings};
use crate::normals;
use crate::run::{all_slots, ensure_areas};
use crate::settings as deployment;
const DEFAULT_MIN_FREE_GB: u64 = 100;
pub fn run(args: &BaselinePassArgs) -> Result<()> {
let s = settings(args.dataset.as_deref(), Some(args.country.as_str()))?;
pass(&s, args.mode.as_deref(), args.min_free_gb)
}
fn pass(s: &Settings, mode: Option<&str>, min_free_gb: Option<u64>) -> Result<()> {
let mode = mode.unwrap_or("clip");
if !matches!(mode, "clip" | "full") {
return Err(DatasetError::Exit(Exit(2)));
}
let config = DatasetConfig::load(&s.config_path)?;
if config.reader != Reader::Windowed {
return Err(DatasetError::data(format!(
"baseline-pass streams windowed datasets only; {} reads whole rasters",
s.dataset
)));
}
let min_free_gb = min_free_gb
.or(deployment::current().run.min_free_gb)
.unwrap_or(DEFAULT_MIN_FREE_GB);
let areas = ensure_areas(s)?.join("areas.geojson");
let list = baseline_list(s, &config)?;
let client = Client::open()?;
stream(s, &list, &areas, &client, mode, min_free_gb)?;
let normals = write_normals(s, &config, &areas)?;
println!("{}", normals.display());
Ok(())
}
fn baseline_list(s: &Settings, config: &DatasetConfig) -> Result<PathBuf> {
let lists = s
.data_root
.join("datasets")
.join(&s.dataset)
.join(&s.cc)
.join("lists");
fs::create_dir_all(&lists).io_at(IoOp::Create, &lists)?;
let path = lists.join("baseline.txt");
if path.is_file() {
return Ok(path);
}
let (first, last) = s.baseline.split_once('-').ok_or_else(|| {
DatasetError::data(format!(
"baseline {:?} is not FIRST-LAST (2019-2025)",
s.baseline
))
})?;
let mut from = format!("{first}-01-01");
let to = format!("{last}-12-31");
if let Some(start) = &config.record_start
&& start.as_str() > from.as_str()
{
from.clone_from(start);
}
let stac = deployment::current()
.sources
.cdse_stac
.as_deref()
.unwrap_or(cdse::DEFAULT_STAC);
let text = cdse::list(&from, &to, stac)?.join("\n");
cdse::write_atomic(&path, &text)?;
Ok(path)
}
fn stream(
s: &Settings,
list: &Path,
areas: &Path,
client: &Client,
mode: &str,
min_free_gb: u64,
) -> Result<()> {
let entries = entries(list)?;
let cache = values_cache(s);
fs::create_dir_all(&cache).io_at(IoOp::Create, &cache)?;
let src = s
.data_root
.join("datasets")
.join(&s.dataset)
.join("src")
.join(&s.cc)
.join("baseline");
fs::create_dir_all(&src).io_at(IoOp::Create, &src)?;
let window = if mode == "clip" {
Some(clip_window(s, areas)?)
} else {
None
};
let mut probed = false;
for entry in &entries {
let cached = cache.join(format!("{}.values.csv", stem(&entry.name)?));
if cached.is_file() {
println!("SKIP {} (cached)", entry.name);
continue;
}
let need = min_free_gb
.saturating_mul(1_000_000_000)
.saturating_add(entry.bytes.saturating_mul(2));
let free = free_bytes(&s.data_root)?;
if free < need {
return Err(DatasetError::data(format!(
"{free} bytes free on {}, {} needs {need} ({min_free_gb} GB + 2 x {}): stopping",
s.data_root.display(),
entry.name,
entry.bytes
)));
}
match window {
Some(window) => {
if !probed {
client.probe_entry(entry, window)?;
probed = true;
}
client.clip_entry(entry, &src, window)?;
}
None => client.download_entry(entry, &src)?,
}
let raster = src.join(&entry.name);
normals::run_values(&ValuesArgs {
config: s.config_path.clone(),
raster: raster.clone(),
areas: areas.to_path_buf(),
cache: cache.clone(),
})
.within({
format!(
"dataset values failed on {}; {} kept",
entry.name,
raster.display()
)
})?;
if !cached.is_file() {
return Err(DatasetError::data(format!(
"dataset values wrote no {}; {} kept",
cached.display(),
raster.display()
)));
}
let _ = fs::remove_file(&raster);
let _ = fs::remove_file(format!("{}.src", raster.display()));
println!("CACHED {}", entry.name);
}
Ok(())
}
fn clip_window(s: &Settings, areas: &Path) -> Result<(i64, i64, u32, u32)> {
let country = s.country_config();
let outline = country
.as_ref()
.filter(|config| config.boundaries.holds_soi_land)
.map(|_| s.data_root.join("inputs/india/india-composite.geojson"));
let window = cdse::window(
areas,
outline.as_deref(),
&s.cc.to_uppercase(),
cdse::NDVI_GRID,
512,
)?;
println!("window {} {} {} {}", window.0, window.1, window.2, window.3);
Ok(window)
}
fn values_cache(s: &Settings) -> PathBuf {
s.data_root
.join("datasets")
.join(&s.dataset)
.join(&s.cc)
.join("cache")
.join(&s.boundary_release)
.join("values")
}
fn entries(list: &Path) -> Result<Vec<ListLine>> {
let text = fs::read_to_string(list).io_at(IoOp::Read, list)?;
let mut entries = Vec::new();
for line in text.lines() {
let line = line.trim_end();
if line.is_empty() || line.starts_with('#') {
continue;
}
let Some(entry) = cdse::list_line(line) else {
return Err(DatasetError::data(format!("bad baseline line: {line}")));
};
entries.push(entry);
}
Ok(entries)
}
fn stem(name: &str) -> Result<&str> {
Path::new(name)
.file_stem()
.and_then(|stem| stem.to_str())
.ok_or_else(|| DatasetError::data(format!("{name} has no file stem")))
}
#[allow(
unsafe_code,
reason = "libc::statvfs fills a zeroed struct; each unsafe block has a SAFETY comment"
)]
fn free_bytes(path: &Path) -> Result<u64> {
use std::os::unix::ffi::OsStrExt as _;
let c_path = std::ffi::CString::new(path.as_os_str().as_bytes())
.within(format!("{} holds a NUL byte", path.display()))?;
let mut stats = std::mem::MaybeUninit::<libc::statvfs>::zeroed();
if unsafe { libc::statvfs(c_path.as_ptr(), stats.as_mut_ptr()) } != 0 {
return Err(std::io::Error::last_os_error())
.io_step(format!("reading the free space of {}", path.display()));
}
let stats = unsafe { stats.assume_init() };
let block = if stats.f_frsize > 0 {
stats.f_frsize
} else {
stats.f_bsize
};
let available = u128::from(stats.f_bavail);
let block = u128::from(block);
Ok(u64::try_from(available.saturating_mul(block)).unwrap_or(u64::MAX))
}
fn write_normals(s: &Settings, config: &DatasetConfig, areas: &Path) -> Result<PathBuf> {
let country = CountryConfig::load(&s.country_config_path)?;
let normals_path = s
.data_root
.join("datasets")
.join(&s.dataset)
.join(&s.cc)
.join("normals")
.join(&s.boundary_release)
.join(&s.baseline)
.join("normals.csv");
let dir = normals_path
.parent()
.ok_or_else(|| DatasetError::data(format!("{} has no parent", normals_path.display())))?;
let partial = dir.join(".normals.partial");
if partial.exists() {
fs::remove_dir_all(&partial).io_at(IoOp::Remove, &partial)?;
}
fs::create_dir_all(&partial).io_at(IoOp::Create, &partial)?;
let cache = values_cache(s);
normals::run(&NormalsArgs {
config: s.config_path.clone(),
rasters: cache.clone(),
areas: areas.to_path_buf(),
baseline: s.baseline.clone(),
slots: all_slots(config.period),
out: partial.join("normals.csv"),
cache: Some(cache),
allow_empty: country
.limits(&s.dataset)
.is_some_and(|limits| limits.min_coverage_pct.is_some()),
})?;
let stats = partial.join("normals-stats.json");
if stats.is_file() {
let dest = dir.join("normals-stats.json");
fs::rename(&stats, &dest).io_step(format!(
"renaming {} to {}",
stats.display(),
dest.display()
))?;
}
let written = partial.join("normals.csv");
fs::rename(&written, &normals_path).io_step({
format!(
"renaming {} to {}",
written.display(),
normals_path.display()
)
})?;
fs::remove_dir_all(&partial).io_at(IoOp::Remove, &partial)?;
Ok(normals_path)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cdse::tests::store;
use crate::layout::Settings;
use std::path::PathBuf;
const AREAS: &str = r#"{
"type": "FeatureCollection",
"boundary_release": "2026-10-06.0",
"attribution": "a test",
"features": [{
"type": "Feature",
"properties": {
"id": "00000000-0000-3000-8000-000000000001",
"name": "A test area",
"country": "US",
"level": "county"
},
"geometry": {
"type": "Polygon",
"coordinates": [[[-1.4, 19.0], [0.0, 19.0], [0.0, 20.0], [-1.4, 20.0], [-1.4, 19.0]]]
}
}]
}"#;
fn write(path: &Path, text: &str) {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).expect("mkdir");
}
fs::write(path, text).expect("write");
}
fn settings_for(root: &Path) -> Settings {
let repo = Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.and_then(Path::parent)
.expect("the workspace root")
.to_path_buf();
let mut s = Settings::for_test("ndvi", "us", &root.to_string_lossy());
s.data_root = root.to_path_buf();
s.stage_root = root.join("datasets/stage");
s.repo = repo.clone();
s.config_path = repo.join("packages/dataset-builder/data/datasets/ndvi.json");
s.country_config_path =
repo.join("packages/dataset-builder/data/datasets/countries/us.json");
s.boundary_release = "2026-10-06.0".to_owned();
s.baseline = "2019-2025".to_owned();
s
}
fn root_with(count: usize) -> (tempfile::TempDir, Settings, Vec<ListLine>) {
let dir = tempfile::tempdir().expect("a temp dir");
let s = settings_for(dir.path());
let areas = dir.path().join("datasets/boundaries/us/2026-10-06.0-r1");
write(&areas.join("areas.geojson"), AREAS);
write(
&areas.join("gaps.geojson"),
r#"{"type":"FeatureCollection","features":[]}"#,
);
write(&areas.join("areas.pmtiles"), "a test pmtiles");
let mut entries = Vec::new();
for index in 1..=count {
let name = format!("ndvi300-v3.2019.01.{index}.tif");
entries.push(ListLine {
key: format!("k/2019/01/0{index}/c.tiff"),
name,
bytes: 0,
});
}
(dir, s, entries)
}
fn list_of(root: &Path, entries: &[ListLine], sizes: &[u64]) -> PathBuf {
let path = root.join("datasets/ndvi/us/lists/baseline.txt");
let text = entries
.iter()
.zip(sizes)
.map(|(entry, bytes)| {
ListLine {
key: entry.key.clone(),
name: entry.name.clone(),
bytes: *bytes,
}
.final_line()
})
.collect::<Vec<_>>()
.join("\n");
write(&path, &text);
path
}
fn fixture_store(entries: &[ListLine], bodies: &[Vec<u8>]) -> cdse::tests::Store {
store(
entries
.iter()
.zip(bodies)
.map(|(entry, body)| (entry.key.clone(), body.clone()))
.collect(),
Vec::new(),
)
}
fn fixture() -> Vec<u8> {
fs::read(Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/ndvi-deflate.tif"))
.expect("the fixture")
}
#[test]
fn a_cached_dekad_is_skipped_and_its_file_is_never_asked_for() {
let (dir, s, entries) = root_with(3);
let body = fixture();
let sizes = [body.len() as u64, body.len() as u64, body.len() as u64];
let list = list_of(dir.path(), &entries, &sizes);
let store = fixture_store(&entries, &[body.clone(), body.clone(), body]);
let cache = values_cache(&s);
write(&cache.join("ndvi300-v3.2019.01.1.values.csv"), "cached\n");
let areas = dir
.path()
.join("datasets/boundaries/us/2026-10-06.0-r1/areas.geojson");
stream(&s, &list, &areas, &store.client(), "full", 0).expect("a pass");
let targets: Vec<String> = store
.log
.lock()
.expect("log")
.iter()
.map(|record| record.target.clone())
.collect();
assert!(
targets.iter().all(|target| !target.contains("01/01/")),
"{targets:?}"
);
assert_eq!(
fs::read_to_string(cache.join("ndvi300-v3.2019.01.1.values.csv")).expect("read"),
"cached\n"
);
for entry in &entries[1..] {
assert!(
cache
.join(format!("{}.values.csv", stem(&entry.name).expect("stem")))
.is_file()
);
}
assert_eq!(
fs::read_dir(dir.path().join("datasets/ndvi/src/us/baseline"))
.expect("the src dir")
.count(),
0
);
}
#[test]
fn a_failed_download_keeps_no_raster_and_no_values_file() {
let (dir, s, entries) = root_with(3);
let body = fixture();
let sizes = [body.len() as u64, body.len() as u64, body.len() as u64];
let list = list_of(dir.path(), &entries, &sizes);
let store = fixture_store(&entries, std::slice::from_ref(&body));
let areas = dir
.path()
.join("datasets/boundaries/us/2026-10-06.0-r1/areas.geojson");
let error = stream(&s, &list, &areas, &store.client(), "full", 0)
.expect_err("a failed download stops the pass");
assert!(!geolith::error::report(&error).is_empty());
let cache = values_cache(&s);
assert!(cache.join("ndvi300-v3.2019.01.1.values.csv").is_file());
assert!(!cache.join("ndvi300-v3.2019.01.2.values.csv").exists());
let src = dir.path().join("datasets/ndvi/src/us/baseline");
let left: Vec<String> = fs::read_dir(&src)
.expect("the src dir")
.map(|entry| {
entry
.expect("an entry")
.file_name()
.to_string_lossy()
.into_owned()
})
.collect();
assert!(left.iter().all(|name| !name.ends_with(".tif")), "{left:?}");
let targets: Vec<String> = store
.log
.lock()
.expect("log")
.iter()
.map(|record| record.target.clone())
.collect();
assert!(
targets.iter().all(|target| !target.contains("01/03/")),
"{targets:?}"
);
}
#[test]
fn the_floor_stops_the_pass_before_any_download() {
let (dir, s, entries) = root_with(1);
let body = fixture();
let list = list_of(dir.path(), &entries, &[body.len() as u64]);
let store = fixture_store(&entries, &[body]);
let areas = dir
.path()
.join("datasets/boundaries/us/2026-10-06.0-r1/areas.geojson");
let error =
stream(&s, &list, &areas, &store.client(), "full", 1_000_000_000).expect_err("no room");
let text = geolith::error::report(&error);
assert!(text.contains("free"), "{text}");
assert!(store.log.lock().expect("log").is_empty());
assert!(
!values_cache(&s)
.join("ndvi300-v3.2019.01.1.values.csv")
.exists()
);
}
#[test]
fn a_mode_other_than_clip_or_full_is_a_usage_error() {
let (dir, s, _entries) = root_with(1);
let error = pass(&s, Some("whole"), None).expect_err("a bad mode");
assert_eq!(error.exit(), Some(Exit(2)));
assert!(dir.path().exists());
}
#[test]
fn a_whole_raster_dataset_is_refused_by_name() {
let dir = tempfile::tempdir().expect("a temp dir");
let repo = Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.and_then(Path::parent)
.expect("the workspace root");
let mut s = settings_for(dir.path());
s.dataset = "rainfall".to_owned();
s.config_path = repo.join("packages/dataset-builder/data/datasets/rainfall.json");
let error = pass(&s, Some("full"), None).expect_err("a whole dataset");
let text = geolith::error::report(&error);
assert!(text.contains("windowed datasets only"), "{text}");
assert!(text.contains("rainfall"), "{text}");
}
}