geolith-dataset-builder 0.2.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 keys`: the object keys an upload would write, from the
//! local stage only (no network).
//!
//! Ported from the `keys` verb of the former `scripts/datasets/remote.ts`: prints
//! `build <id>`, `bucket <name>`, a `bytes key` table (the area files folded
//! into one row), `upload <n> keys <total> bytes`, and the pointer publish
//! would overwrite.

use std::fs;

use anyhow::{Context, Result};

use crate::cli::KeysArgs;
use crate::layout::{current_key, layout_key_refusal, settings};
use crate::settings as deployment;
use crate::stage::{public_objects, read_stage, staged_pointer};

/// The table rows of a stage, its total bytes and its key count.
pub type Plan = (Vec<(String, String)>, u64, usize);

/// The table rows of each key, the total bytes and the key count of a stage.
///
/// # Errors
///
/// Fails when the stage is missing, a key is outside the layout, or the
/// pointer differs from `stage.json`.
pub fn plan_rows(s: &crate::layout::Settings, id: &str) -> Result<Plan> {
    let stage = read_stage(s, id)?;
    let objects = public_objects(s, &stage, id)?;
    // The staged pointer matches stage.json and names the build.
    staged_pointer(s, &stage, id)?;
    let current = current_key(s);
    if let Some(refusal) = layout_key_refusal(&s.key_root, &current, true) {
        anyhow::bail!("{refusal}");
    }
    let areas = format!("{}{}/{}/{id}/areas/", s.key_root, s.dataset, s.cc);
    let area_files: Vec<_> = objects
        .iter()
        .filter(|file| file.key.starts_with(&areas))
        .collect();
    let mut rows = Vec::new();
    for file in objects {
        if !file.key.starts_with(&areas) {
            rows.push((file.bytes.to_string(), file.key.clone()));
        } else if area_files.first().is_some_and(|area| area.key == file.key) {
            let bytes: Vec<u64> = area_files.iter().map(|area| area.bytes).collect();
            rows.push((
                bytes.iter().sum::<u64>().to_string(),
                format!(
                    "{areas}<area-id>.json ({} files, max {} bytes)",
                    area_files.len(),
                    bytes.iter().copied().max().unwrap_or_default()
                ),
            ));
        }
    }
    Ok((
        rows,
        objects.iter().map(|file| file.bytes).sum(),
        objects.len(),
    ))
}

/// Run `geolith dataset keys`.
///
/// # Errors
///
/// Propagates [`plan_rows`]'s errors and the settings' errors.
pub fn run(args: &KeysArgs) -> Result<()> {
    let s = settings(args.dataset.as_deref(), args.country.as_deref())?;
    let (rows, total, keys) = plan_rows(&s, &args.build_id)?;
    let width = rows
        .iter()
        .map(|(bytes, _)| bytes.len())
        .chain(std::iter::once(5))
        .max()
        .unwrap_or(5);
    println!("build {}", args.build_id);
    println!(
        "bucket {}",
        deployment::current()
            .storage
            .bucket
            .as_deref()
            .unwrap_or("none (storage.bucket is not set)")
    );
    println!("{:>width$}  key", "bytes");
    for (bytes, key) in &rows {
        println!("{bytes:>width$}  {key}");
    }
    println!("upload {keys} keys {total} bytes");
    let stage = read_stage(&s, &args.build_id)?;
    let current = current_key(&s);
    let pointer = stage.dir.join(&current);
    let pointer_bytes = fs::metadata(&pointer)
        .with_context(|| format!("reading {}", pointer.display()))?
        .len();
    println!("publish {current} {pointer_bytes} bytes (the only key ever overwritten)");
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::layout::Settings;
    use std::path::Path;

    /// A stage of two build files, three area files and a pointer.
    fn staged(root: &Path) -> Settings {
        let id = "2026-11-20.20261120T0000Z";
        let stage_root = root.join("datasets/stage");
        let dir = stage_root.join(id);
        let base = format!("datasets/rainfall/in/{id}");
        let dirs = dir.join(&base);
        std::fs::create_dir_all(dirs.join("areas")).expect("mkdir");
        std::fs::create_dir_all(dir.join("datasets/rainfall/in")).expect("mkdir");
        std::fs::write(dirs.join("index.json"), b"{}").expect("write");
        std::fs::write(dirs.join("numbers.csv"), b"12345").expect("write");
        for (name, size) in [("a", 7_u64), ("b", 9), ("c", 11)] {
            std::fs::write(
                dirs.join("areas").join(format!("{name}.json")),
                vec![b'x'; size as usize],
            )
            .expect("write");
        }
        std::fs::write(
            dir.join("datasets/rainfall/in/current.json"),
            format!(r#"{{"build_id":"{id}","period_end":"2026-11-18"}}"#),
        )
        .expect("write");
        let pointer_path = dir.join("datasets/rainfall/in/current.json");
        let pointer_sha = crate::layout::sha256_hex(&pointer_path).expect("digest");
        let pointer_len = std::fs::metadata(&pointer_path).expect("metadata").len();
        let entry =
            |key: String, bytes: u64| format!(r#"{{"key":"{key}","bytes":{bytes},"sha256":""}}"#);
        let pointer_entry = format!(
            r#"{{"key":"datasets/rainfall/in/current.json","bytes":{pointer_len},"sha256":"{pointer_sha}"}}"#
        );
        let files = [
            entry(format!("{base}/index.json"), 2),
            entry(format!("{base}/numbers.csv"), 5),
            entry(format!("{base}/areas/a.json"), 7),
            entry(format!("{base}/areas/b.json"), 9),
            entry(format!("{base}/areas/c.json"), 11),
            pointer_entry,
        ]
        .join(",");
        std::fs::write(
            dir.join("stage.json"),
            format!(
                r#"{{"build_id":"{id}","files":[{files}],"staged_at":"2026-11-21T00:00:00Z"}}"#
            ),
        )
        .expect("write");
        let mut s = Settings::for_test("rainfall", "in", "/nonexistent/data");
        s.stage_root = stage_root;
        s
    }

    #[test]
    fn the_area_files_fold_into_one_row() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let s = staged(dir.path());
        let (rows, total, count) = plan_rows(&s, "2026-11-20.20261120T0000Z").expect("plan");
        assert_eq!(count, 5);
        assert_eq!(rows.len(), 3);
        assert_eq!(
            rows[0],
            (
                "27".to_owned(),
                "datasets/rainfall/in/2026-11-20.20261120T0000Z/areas/<area-id>.json (3 files, max 11 bytes)".to_owned()
            )
        );
        assert_eq!(
            rows[1],
            (
                "2".to_owned(),
                "datasets/rainfall/in/2026-11-20.20261120T0000Z/index.json".to_owned()
            )
        );
        assert_eq!(rows[2].0, "5");
        assert_eq!(total, 34);
    }
}