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
//! `geolith dataset lists`: the CHIRPS download lists of the series, the
//! season and the baseline.
//!
//! Ported from the former `scripts/datasets/lists.ts`. A listing is the host's
//! directory HTML or a plain list of names; every
//! `chirps-v3.0.YYYY.MM.P.(cog|tif)` name in it counts. The latest pentad is
//! the newest in either listing, a pentad uses its final when the final
//! listing has it, else its prelim. Writes `series.txt` (the latest 12),
//! `season.txt` (from the season start through the latest) and
//! `baseline.txt` (all 72 pentads of every baseline year).

use std::collections::BTreeMap;
use std::fs;
use std::path::Path;

use crate::error::{
    DatasetError, IoOp, IoResultExt as _, IoStepExt as _, NumberResultExt as _, Result,
};

use crate::cli::ListsArgs;
use crate::exit::Exit;
use crate::period::{Period, period_key, period_list};

/// Pentads in a year.
const PENTADS_PER_YEAR: i64 = 72;

/// Pentads in a month.
const PENTADS_PER_MONTH: i64 = 6;

/// Length of the series list.
const SERIES_LEN: usize = 12;

/// Where the final COGs live, host-relative.
const FINAL: &str =
    "/products/CHIRPS/v3.0/pentads/global/cogs/chirps-v3.0.{year}.{month}.{pentad}.cog";

/// Where the preliminary TIFs live, host-relative.
const PRELIM: &str =
    "/products/CHIRPS/v3.0/prelim/pentads/global/tifs/chirps-v3.0.{year}.{month}.{pentad}.tif";

/// The pentads named in `text`, keyed `YYYY.MM.P`.
fn listed(text: &str) -> BTreeMap<String, Period> {
    let mut found = BTreeMap::new();
    let bytes = text.as_bytes();
    let needle = b"chirps-v3.0.";
    let mut at = 0;
    while let Some(offset) = find(&bytes[at..], needle) {
        let start = at + offset + needle.len();
        if let Some((period, end)) = name_at(text, start)
            && !bytes
                .get(end)
                .is_some_and(|byte| byte.is_ascii_alphanumeric() || *byte == b'_' || *byte == b'.')
        {
            found.insert(period_key(period), period);
        }
        at = start;
    }
    found
}

/// The first occurrence of `needle` in `haystack`.
fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    haystack
        .windows(needle.len())
        .position(|window| window == needle)
}

/// The period of the name starting at `start` and the index just past it.
fn name_at(text: &str, start: usize) -> Option<(Period, usize)> {
    let bytes = text.as_bytes();
    let year = digits(bytes, start, 4)?;
    if bytes.get(start + 4).copied() != Some(b'.') {
        return None;
    }
    let (month, after_month) = digits_upto(bytes, start + 5, 2)?;
    if !(1..=12).contains(&month) || bytes.get(after_month).copied() != Some(b'.') {
        return None;
    }
    let (index, after_index) = digits_upto(bytes, after_month + 1, 1)?;
    if !(1..=6).contains(&index) || bytes.get(after_index).copied() != Some(b'.') {
        return None;
    }
    let rest = &text[after_index + 1..];
    if !(rest.starts_with("cog") || rest.starts_with("tif")) {
        return None;
    }
    let end = after_index + 4;
    Some((
        Period {
            year: i64::from(year),
            month,
            index,
        },
        end,
    ))
}

/// A run of exactly `width` digits at `start`.
fn digits(bytes: &[u8], start: usize, width: usize) -> Option<u32> {
    let slice = bytes.get(start..start + width)?;
    if !slice.iter().all(u8::is_ascii_digit) {
        return None;
    }
    std::str::from_utf8(slice).ok()?.parse().ok()
}

/// A run of one to `width` digits at `start`, and where it ends.
fn digits_upto(bytes: &[u8], start: usize, width: usize) -> Option<(u8, usize)> {
    let mut end = start;
    while end < bytes.len() && end - start < width && bytes[end].is_ascii_digit() {
        end += 1;
    }
    if end == start {
        return None;
    }
    let value = std::str::from_utf8(&bytes[start..end]).ok()?.parse().ok()?;
    Some((value, end))
}

/// The pentad slot `MM-DD` starts.
///
/// # Errors
///
/// Fails when the date does not start a pentad.
fn season_slot(text: &str) -> Result<(u8, u8)> {
    let message = format!(
        "season start must be MM-DD on a pentad start (day 1, 6, 11, 16, 21 or 26): {text}"
    );
    let bytes = text.as_bytes();
    if bytes.len() != 5 || bytes[2] != b'-' {
        return Err(DatasetError::data(message.to_string()));
    }
    let month = digits(bytes, 0, 2).ok_or_else(|| DatasetError::data("month"))?;
    let day = digits(bytes, 3, 2).ok_or_else(|| DatasetError::data("day"))?;
    if !(1..=12).contains(&month) || !(1..=26).contains(&day) || (day - 1) % 5 != 0 {
        return Err(DatasetError::data(message.to_string()));
    }
    Ok((
        u8::try_from(month).unwrap_or_default(),
        u8::try_from((day - 1) / 5 + 1).unwrap_or_default(),
    ))
}

/// The host-relative path of `pattern` for `p`.
fn fill(pattern: &str, p: Period) -> String {
    let path = match pattern.split_once("://") {
        Some((_, rest)) => rest.find('/').map_or(pattern, |slash| &rest[slash..]),
        None => pattern,
    };
    path.replace("{year}", &p.year.to_string())
        .replace("{month}", &format!("{:02}", p.month))
        .replace("{pentad}", &p.index.to_string())
}

/// The `download.sh chirps` lines of `periods`.
fn chirps_lines(periods: &[Period], finals: &BTreeMap<String, Period>) -> Vec<String> {
    periods
        .iter()
        .map(|p| {
            let key = period_key(*p);
            if finals.contains_key(&key) {
                format!("final {}", fill(FINAL, *p))
            } else {
                format!("prelim {}", fill(PRELIM, *p))
            }
        })
        .collect()
}

/// Final-release lines for every slot of every year `from..=to`.
fn baseline_lines(from: i64, to: i64) -> Vec<String> {
    let mut lines = Vec::new();
    for year in from..=to {
        for month in 1..=12_u8 {
            for index in 1..=6_u8 {
                lines.push(format!(
                    "final {}",
                    fill(FINAL, Period { year, month, index })
                ));
            }
        }
    }
    lines
}

/// Write the three lists to stdout, as the script did.
///
/// # Errors
///
/// Fails with [`write_lists_to`]'s errors and when stdout cannot be written.
pub fn write_lists(
    listing_final: &Path,
    listing_prelim: &Path,
    season_start: &str,
    baseline: &str,
    out: &Path,
) -> Result<Period> {
    write_lists_to(
        &mut std::io::stdout(),
        listing_final,
        listing_prelim,
        season_start,
        baseline,
        out,
    )
}

/// Write the three lists without printing anything: the refresh reads only
/// `series.txt` and its own log is the transcript.
///
/// # Errors
///
/// Fails with [`write_lists_to`]'s errors.
pub fn write_lists_quiet(
    listing_final: &Path,
    listing_prelim: &Path,
    season_start: &str,
    baseline: &str,
    out: &Path,
) -> Result<Period> {
    write_lists_to(
        &mut std::io::sink(),
        listing_final,
        listing_prelim,
        season_start,
        baseline,
        out,
    )
}

/// Write the three lists, reporting each one to `out`.
///
/// # Errors
///
/// Fails when a listing cannot be read, no pentad is named, the season start
/// is not a pentad start, or a file cannot be written.
pub fn write_lists_to<W: std::io::Write + ?Sized>(
    out: &mut W,
    listing_final: &Path,
    listing_prelim: &Path,
    season_start: &str,
    baseline: &str,
    out_dir: &Path,
) -> Result<Period> {
    let finals = listed(&fs::read_to_string(listing_final).io_at(IoOp::Read, listing_final)?);
    let prelims = listed(&fs::read_to_string(listing_prelim).io_at(IoOp::Read, listing_prelim)?);
    let latest = finals
        .values()
        .chain(prelims.values())
        .max()
        .copied()
        .ok_or_else(|| {
            DatasetError::data({
                format!(
                    "no CHIRPS pentad names in {} or {}",
                    listing_final.display(),
                    listing_prelim.display()
                )
            })
        })?;
    let (month, index) = season_slot(season_start)?;
    let start = Period {
        year: latest.year,
        month,
        index,
    };
    let season_year = if start <= latest {
        latest.year
    } else {
        latest.year - 1
    };
    let season_count = (latest.year - season_year) * PENTADS_PER_YEAR
        + (i64::from(latest.month) - i64::from(month)) * PENTADS_PER_MONTH
        + (i64::from(latest.index) - i64::from(index))
        + 1;
    let season_count = usize::try_from(season_count.max(0)).number_of("season length")?;
    let series = period_list(latest, SERIES_LEN, 6);
    let season = period_list(latest, season_count, 6);
    for period in series.iter().chain(season.iter()) {
        let key = period_key(*period);
        if !finals.contains_key(&key) && !prelims.contains_key(&key) {
            eprintln!("not on the host: {key}");
        }
    }
    let years: Vec<&str> = baseline.split('-').collect();
    let (Ok(from), Ok(to)) = (
        years.first().copied().unwrap_or_default().parse::<i64>(),
        years.get(1).copied().unwrap_or_default().parse::<i64>(),
    ) else {
        return Err(DatasetError::data(format!(
            "baseline must be YYYY-YYYY: {baseline}"
        )));
    };
    if from > to {
        return Err(DatasetError::data(format!(
            "baseline must be YYYY-YYYY: {baseline}"
        )));
    }
    fs::create_dir_all(out_dir).io_at(IoOp::Create, out_dir)?;
    for (name, lines) in [
        ("series.txt", chirps_lines(&series, &finals)),
        ("season.txt", chirps_lines(&season, &finals)),
        ("baseline.txt", baseline_lines(from, to)),
    ] {
        let path = out_dir.join(name);
        fs::write(&path, format!("{}\n", lines.join("\n"))).io_at(IoOp::Write, &path)?;
        writeln!(out, "{name} {} lines", lines.len()).io_step("writing the lists report")?;
    }
    writeln!(out, "latest {}", period_key(latest)).io_step("writing the lists report")?;
    Ok(latest)
}

/// Run `geolith dataset lists`.
///
/// # Errors
///
/// Fails with [`Exit`] `2` on a usage error, and with [`write_lists`]'s
/// errors.
pub fn run(args: &ListsArgs) -> Result<()> {
    let (Some(listing_final), Some(listing_prelim), Some(season_start), Some(out)) = (
        args.listing_final.as_deref(),
        args.listing_prelim.as_deref(),
        args.season_start.as_deref(),
        args.out.as_deref(),
    ) else {
        return Err(DatasetError::Exit(Exit(2)));
    };
    let baseline = args.baseline.as_deref().unwrap_or("1991-2020");
    write_lists(
        Path::new(listing_final),
        Path::new(listing_prelim),
        season_start,
        baseline,
        Path::new(out),
    )?;
    Ok(())
}

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

    #[test]
    fn a_name_is_a_pentad_and_nothing_else() {
        let found = listed(
            "<a href=\"chirps-v3.0.2026.11.4.cog\">x</a> \
             chirps-v3.0.2026.1.1.tif chirps-v3.0.2026.11.7.cog \
             chirps-v3.0.2026.11.4.cog.bak chirps-v3.0.2026.13.1.cog",
        );
        let keys: Vec<&str> = found.keys().map(String::as_str).collect();
        assert_eq!(keys, vec!["2026.01.1", "2026.11.4"]);
    }

    #[test]
    fn the_latest_pentad_of_a_season_crossing_the_year_is_the_new_year() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let finals = dir.path().join("final.html");
        let prelims = dir.path().join("prelim.html");
        std::fs::write(
            &finals,
            "chirps-v3.0.2025.12.5.cog chirps-v3.0.2026.1.1.cog chirps-v3.0.2026.1.2.cog",
        )
        .expect("write");
        std::fs::write(&prelims, "").expect("write");
        let out = dir.path().join("lists");
        let latest = write_lists(&finals, &prelims, "11-06", "1991-2020", &out).expect("lists");
        assert_eq!(period_key(latest), "2026.01.2");
        let season = std::fs::read_to_string(out.join("season.txt")).expect("season");
        let lines: Vec<&str> = season.lines().collect();
        // From 2025-11-06 (pentad 11-2) through 2026-01-2: 5 + 6 + 2.
        assert_eq!(lines.len(), 13);
        assert_eq!(
            lines.first().copied(),
            Some(
                "prelim /products/CHIRPS/v3.0/prelim/pentads/global/tifs/chirps-v3.0.2025.11.2.tif"
            )
        );
        assert_eq!(
            lines.last().copied(),
            Some("final /products/CHIRPS/v3.0/pentads/global/cogs/chirps-v3.0.2026.01.2.cog")
        );
        let series = std::fs::read_to_string(out.join("series.txt")).expect("series");
        assert_eq!(series.lines().count(), 12);
        let baseline = std::fs::read_to_string(out.join("baseline.txt")).expect("baseline");
        assert_eq!(baseline.lines().count(), 2160);
    }

    #[test]
    fn a_season_start_off_a_pentad_is_refused() {
        assert!(season_slot("06-02").is_err());
        assert!(season_slot("06-26").is_ok());
    }
}