geolith-dataset-builder 0.4.2

Raster datasets for geolith: district areas, normals, numbers and a map layer per period, and the steps that stage, verify and publish them to any S3-compatible bucket
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
//! `geolith dataset baseline-pass`: the NDVI baseline, one file at a time.
//!
//! Ported from `baseline-pass` of the former `scripts/datasets/datasets.sh`.
//! For each line of `lists/baseline.txt`, in period order: a dekad whose
//! values cache file `<stem>.values.csv` exists is skipped (the cache is the
//! ledger); else, with `DATASETS_MIN_FREE_GB` (100) GB + 2 × its bytes free,
//! it is fetched alone into `src/<cc>/baseline/`, `dataset values` writes its
//! cache file, and only then is the raster deleted. A failure keeps the file
//! and exits with the failing code. The pass ends with the normals from the
//! cache alone.
//!
//! `--mode full` reads the whole file in Rust; `--mode clip` (the default)
//! reads the country's pixel window through `gdal_translate`, the one
//! optional external tool, refused with [`Exit`] `3` when it is absent.

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;

/// Free space kept before each file, in GB (`DATASETS_MIN_FREE_GB`).
const DEFAULT_MIN_FREE_GB: u64 = 100;

/// Run `geolith dataset baseline-pass`.
///
/// # Errors
///
/// Fails with [`Exit`] `2` on a bad mode, `3` when the clip has no GDAL, and
/// when the list, a download, a values write or the normals fail.
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)
}

/// The pass over `s`, with `mode` and the floor `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(())
}

/// `$DATA_ROOT/datasets/<dataset>/<cc>/lists/baseline.txt`, written first when
/// absent: the baseline years from the config's `record_start` on.
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)
}

/// The list's rasters, one at a time, into the values cache of `s`.
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(())
}

/// The country window of the clip, printed as the script printed it.
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("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)
}

/// The values cache of a windowed dataset:
/// `$DATA_ROOT/datasets/<dataset>/<cc>/cache/<release>/values`.
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")
}

/// The listed entries; a line that is neither blank nor a comment must parse.
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)
}

/// The cache file stem of a raster name: `ndvi300-v3.2019.01.1`.
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")))
}

/// The free bytes on the file system of `path`.
#[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()))?;
    // SAFETY: a live C string, and a zeroed struct the call fills on success.
    let mut stats = std::mem::MaybeUninit::<libc::statvfs>::zeroed();
    // SAFETY: both pointers are valid for the call.
    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()));
    }
    // SAFETY: statvfs returned 0, so it filled the struct.
    let stats = unsafe { stats.assume_init() };
    let block = if stats.f_frsize > 0 {
        stats.f_frsize
    } else {
        stats.f_bsize
    };
    // `f_bavail` is `u32` on macOS and `u64` on Linux; widen both.
    let available = u128::from(stats.f_bavail);
    let block = u128::from(block);
    Ok(u64::try_from(available.saturating_mul(block)).unwrap_or(u64::MAX))
}

/// Write the normals from the cache alone, into
/// `…/normals/<release>/<baseline>/normals.csv`; returns that path.
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;

    /// The areas of the fixture's bbox: one small polygon, one area.
    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");
    }

    /// The real repo's configs with a temporary data root.
    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
    }

    /// A root whose areas are complete, with `count` baseline lines.
    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)
    }

    /// The list file of `entries`, with its own byte counts filled in.
    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
    }

    /// The NDVI fixture's bytes, filed under `entry`.
    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");
        // The cached line was never requested; the other two were.
        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"
        );
        // Every fetched raster is gone once its cache file exists.
        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);
        // The second dekad is missing from the store: its download fails.
        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();
        // Only a `<dest>.part` of the failed dekad may remain, never a raster.
        assert!(left.iter().all(|name| !name.ends_with(".tif")), "{left:?}");
        // The third dekad was never asked for.
        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}");
    }
}