geolith-dataset-builder 0.5.0

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 inputs`: the record of what an engine build was made
//! from, and the newest period on disk.
//!
//! Ported from the former `scripts/datasets/rasters.ts`. The record is the sha256 of the
//! engine binary, the published list, the normals, the areas and the
//! crosswalk, plus every raster used with its bytes, sorted by
//! `<status>/<name>`; `run` writes it as `inputs.json` in the engine build.

use crate::error::{DatasetError, IoOp, IoResultExt as _, JsonResultExt as _, Result};
use serde::Serialize;

use crate::cli::InputsArgs;
use crate::config::DatasetConfig;
use crate::layout::{hex, sha256_file};
use crate::period::{RasterOnDisk, period_end_iso, period_key, rasters_on_disk};

/// The inputs record, in the script's field order.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct InputsRecord {
    /// sha256 of the engine binary.
    pub engine_sha256: String,
    /// sha256 of the published list.
    pub published_sha256: String,
    /// sha256 of the normals.
    pub normals_sha256: String,
    /// sha256 of the areas GeoJSON.
    pub areas_sha256: String,
    /// sha256 of the crosswalk, when the build read one.
    pub crosswalk_sha256: Option<String>,
    /// Every raster used, by `<status>/<name>`.
    pub rasters: Vec<RasterInput>,
}

/// One raster of the record.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct RasterInput {
    /// `<status>/<name>`.
    pub path: String,
    /// Its size in bytes.
    pub bytes: u64,
}

/// The inputs record of an engine build over these files.
///
/// # Errors
///
/// Fails when the config or any input cannot be read.
pub fn record(
    config: &DatasetConfig,
    src: &std::path::Path,
    engine: &std::path::Path,
    published: &std::path::Path,
    normals: &std::path::Path,
    areas: &std::path::Path,
    crosswalk: Option<&std::path::Path>,
) -> Result<InputsRecord> {
    let rasters: Vec<RasterOnDisk> = rasters_on_disk(config, src)?.into_values().collect();
    let mut list: Vec<RasterInput> = Vec::new();
    for raster in rasters {
        let path = src.join(&raster.file);
        let bytes = std::fs::metadata(&path).io_at(IoOp::Read, &path)?.len();
        list.push(RasterInput {
            path: raster.file,
            bytes,
        });
    }
    let sha = |path: &std::path::Path| -> Result<String> { Ok(hex(&sha256_file(path)?)) };
    Ok(InputsRecord {
        engine_sha256: sha(engine)?,
        published_sha256: sha(published)?,
        normals_sha256: sha(normals)?,
        areas_sha256: sha(areas)?,
        crosswalk_sha256: match crosswalk {
            Some(path) => Some(sha(path)?),
            None => None,
        },
        rasters: list,
    })
}

/// The newest period on disk: its `YYYY.MM.P` key and its last day.
///
/// # Errors
///
/// Fails when the config cannot be read.
pub fn latest(config: &DatasetConfig, src: &std::path::Path) -> Result<Option<(String, String)>> {
    let periods = rasters_on_disk(config, src)?;
    let Some((_, raster)) = periods.iter().next_back() else {
        return Ok(None);
    };
    Ok(Some((
        period_key(raster.period),
        period_end_iso(raster.period),
    )))
}

/// Run `geolith dataset inputs`.
///
/// # Errors
///
/// Fails when the files are missing, or when `--latest` finds no raster.
pub fn run(args: &InputsArgs) -> Result<()> {
    let config = DatasetConfig::load(&args.config)?;
    let src = &args.src;
    if args.latest {
        let Some((key, end)) = latest(&config, src)? else {
            return Err(DatasetError::usage(format!(
                "no raster in {}",
                src.display()
            )));
        };
        println!("{key} {end}");
        return Ok(());
    }
    let (Some(engine), Some(published), Some(normals), Some(areas)) = (
        args.engine.as_ref(),
        args.published.as_ref(),
        args.normals.as_ref(),
        args.areas.as_ref(),
    ) else {
        return Err(DatasetError::usage(
            "inputs needs <engine-bin> <published.csv> <normals.csv> <areas.geojson>",
        ));
    };
    let record = record(
        &config,
        src,
        engine,
        published,
        normals,
        areas,
        args.crosswalk.as_deref(),
    )?;
    println!(
        "{}",
        serde_json::to_string_pretty(&record).json_of("serializing the record")?
    );
    Ok(())
}