use std::fs;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::areas::run as run_areas;
use crate::cli::{AreasArgs, StageArgs};
use crate::downloads::{check_parquet, write_numbers_parquet};
use crate::layout::{
Settings, boundaries_dir, boundaries_prefix, build_prefix, current_key, files_under,
is_build_id, is_public, layout_key_refusal, read_json, settings, sha256_hex, utc_now,
};
#[derive(Debug, Deserialize)]
struct EngineManifest {
build_id: String,
attribution: String,
files: Vec<EngineFile>,
}
#[derive(Debug, Deserialize)]
struct EngineFile {
path: String,
}
#[derive(Debug, Deserialize)]
struct EngineIndex {
period_start: String,
period_end: String,
status: String,
stale_after: String,
#[serde(default)]
codes_attribution: Option<String>,
#[serde(default)]
comparison: Option<EngineComparison>,
}
#[derive(Debug, Deserialize)]
struct EngineComparison {
#[serde(default)]
sensor: Option<String>,
}
#[derive(Debug, Serialize)]
struct PointerFile<'a> {
dataset: &'a str,
country: String,
build_id: &'a str,
prefix: String,
period_start: String,
period_end: String,
status: String,
stale_after: String,
boundaries: String,
boundary_release: String,
boundary_tiles_revision: u8,
attribution: String,
boundaries_attribution: String,
codes_attribution: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
sensor: Option<String>,
written_at: String,
}
#[derive(Debug, Serialize)]
struct StageJson {
build_id: String,
files: Vec<StageEntry>,
staged_at: String,
}
#[derive(Debug, Serialize)]
struct StageEntry {
key: String,
bytes: u64,
sha256: String,
}
#[derive(Debug, Clone)]
pub struct Stage {
pub dir: PathBuf,
pub objects: Vec<crate::layout::StageFile>,
pub pointer: Option<crate::layout::StageFile>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct Pointer {
#[serde(default)]
pub build_id: String,
#[serde(default)]
pub period_end: String,
}
fn write_json<T: Serialize + ?Sized>(path: &Path, value: &T) -> Result<()> {
let mut text = serde_json::to_string_pretty(value)
.with_context(|| format!("serializing {}", path.display()))?;
text.push('\n');
let partial = path.with_extension("partial");
fs::write(&partial, text).with_context(|| format!("writing {}", partial.display()))?;
fs::rename(&partial, path).with_context(|| format!("renaming to {}", path.display()))
}
fn copy_file(from: &Path, to: &Path) -> Result<()> {
if !from.is_file() {
bail!("missing {}", from.display());
}
if let Some(parent) = to.parent() {
fs::create_dir_all(parent).with_context(|| format!("creating {}", parent.display()))?;
}
let partial = to.with_extension("partial");
fs::copy(from, &partial)
.with_context(|| format!("copying {} to {}", from.display(), partial.display()))?;
fs::rename(&partial, to).with_context(|| format!("renaming to {}", to.display()))
}
fn source_of(engine_dir: &Path, manifest: &EngineManifest) -> Result<String> {
let mut areas: Vec<&str> = manifest
.files
.iter()
.map(|file| file.path.as_str())
.filter(|path| path.starts_with("areas/"))
.collect();
areas.sort_unstable();
let mut source: Option<String> = None;
let mut first = "";
for path in areas {
let value = read_json(&engine_dir.join(path))?;
let name = value
.get("source")
.and_then(Value::as_str)
.filter(|text| !text.trim().is_empty())
.with_context(|| format!("{} has no source", engine_dir.join(path).display()))?;
match &source {
None => {
source = Some(name.to_owned());
first = path;
}
Some(known) if known != name => bail!(
"{} names source {name}, not {known} ({first})",
engine_dir.join(path).display()
),
Some(_) => {}
}
}
source.with_context(|| format!("{} has no area file", engine_dir.display()))
}
fn stale_download(areas_dir: &Path) -> Result<Option<String>> {
let geojson = areas_dir.join("areas.geojson");
let parquet = areas_dir.join("areas.parquet");
let geojson_time = crate::layout::modified_millis(&geojson)?;
let parquet_time = crate::layout::modified_millis(&parquet)?;
if geojson_time > parquet_time {
return Ok(Some(format!(
"{} is newer than {}",
geojson.display(),
parquet.display()
)));
}
let features = read_json(&geojson)?
.get("features")
.and_then(Value::as_array)
.map_or(0, Vec::len);
let report = check_parquet(&parquet)?;
if report.rows == i64::try_from(features).unwrap_or(i64::MAX) {
Ok(None)
} else {
Ok(Some(format!(
"{} has {} rows, {} has {features}",
parquet.display(),
report.rows,
geojson.display()
)))
}
}
pub fn stage(s: &Settings, engine_dir: &Path) -> Result<PathBuf> {
let manifest: EngineManifest =
serde_json::from_value(read_json(&engine_dir.join("manifest.json"))?)
.with_context(|| format!("reading {}", engine_dir.join("manifest.json").display()))?;
let id = manifest.build_id.clone();
let name = engine_dir
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default();
if name != id {
bail!("{} holds build {id}, not {name}", engine_dir.display());
}
let done = s.stage_root.join(&id);
if done.join("stage.json").is_file() {
return Ok(done);
}
if done.exists() {
bail!("{} exists without stage.json", done.display());
}
let partial = s.stage_root.join(format!(".{id}.partial"));
if partial.exists() {
fs::remove_dir_all(&partial).with_context(|| format!("removing {}", partial.display()))?;
}
let prefix = build_prefix(s, &id);
for file in &manifest.files {
if !is_public(s, &id, &format!("{prefix}{}", file.path)) {
bail!("{} of the engine manifest is not a public file", file.path);
}
copy_file(
&engine_dir.join(&file.path),
&partial.join(&prefix).join(&file.path),
)?;
}
let source = source_of(engine_dir, &manifest)?;
write_numbers_parquet(
&engine_dir.join("numbers.csv"),
&engine_dir.join("index.json"),
&source,
&partial.join(&prefix).join("numbers.parquet"),
)?;
let areas_dir = s
.data_root
.join("datasets/boundaries")
.join(&s.cc)
.join(boundaries_dir(s));
if !areas_dir.join("areas.parquet").is_file() || !areas_dir.join("LICENSE.txt").is_file() {
run_areas(&AreasArgs {
overture: None,
country_config: s
.country_config_path
.is_file()
.then(|| s.country_config_path.clone()),
boundaries_dir: None,
countries: None,
subtype: "county".to_owned(),
india_outline: None,
release: Some(s.boundary_release.clone()),
max_zoom: 8,
allow_districtless: None,
out: areas_dir.clone(),
})?;
}
if let Some(problem) = stale_download(&areas_dir)? {
bail!(
"{problem}: move {} and {} away and rerun (stage never rewrites them)",
areas_dir.join("areas.parquet").display(),
areas_dir.join("LICENSE.txt").display()
);
}
for name in ["areas.pmtiles", "areas.parquet", "LICENSE.txt"] {
copy_file(
&areas_dir.join(name),
&partial.join(boundaries_prefix(s)).join(name),
)?;
}
let index: EngineIndex = serde_json::from_value(read_json(&engine_dir.join("index.json"))?)
.with_context(|| format!("reading {}", engine_dir.join("index.json").display()))?;
let boundaries_attribution = read_json(&areas_dir.join("areas.geojson"))?
.get("attribution")
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned();
let pointer = PointerFile {
dataset: &s.dataset,
country: s.cc.to_uppercase(),
build_id: &id,
prefix: prefix.clone(),
period_start: index.period_start,
period_end: index.period_end,
status: index.status,
stale_after: index.stale_after,
boundaries: boundaries_prefix(s),
boundary_release: s.boundary_release.clone(),
boundary_tiles_revision: s.boundary_tiles_revision,
attribution: manifest.attribution,
boundaries_attribution,
codes_attribution: index.codes_attribution,
sensor: index.comparison.and_then(|comparison| comparison.sensor),
written_at: utc_now(),
};
write_json(&partial.join(current_key(s)), &pointer)?;
let mut files = Vec::new();
let top = s.key_top();
for key in files_under(&partial.join(top))?
.into_iter()
.map(|relative| format!("{top}/{relative}"))
{
let path = partial.join(&key);
let bytes = fs::metadata(&path)
.with_context(|| format!("reading {}", path.display()))?
.len();
files.push(StageEntry {
key,
bytes,
sha256: sha256_hex(&path)?,
});
}
write_json(
&partial.join("stage.json"),
&StageJson {
build_id: id.clone(),
files,
staged_at: utc_now(),
},
)?;
fs::rename(&partial, &done)
.with_context(|| format!("renaming {} to {}", partial.display(), done.display()))?;
Ok(done)
}
pub fn run(args: &StageArgs) -> Result<PathBuf> {
let s = settings(args.dataset.as_deref(), args.country.as_deref())?;
stage(&s, &args.engine_build_dir)
}
pub fn read_stage(s: &Settings, id: &str) -> Result<Stage> {
if !is_build_id(id) {
bail!("build id {id} is not <YYYY-MM-DD>.<YYYYMMDDTHHMMZ>");
}
let dir = s.stage_root.join(id);
let path = dir.join("stage.json");
if !path.is_file() {
bail!("no complete stage {id} in {}", s.stage_root.display());
}
let value = read_json(&path)?;
let files: Vec<crate::layout::StageFile> = value
.get("files")
.and_then(Value::as_array)
.map(|files| {
files
.iter()
.filter_map(|file| {
Some(crate::layout::StageFile {
key: file.get("key")?.as_str()?.to_owned(),
bytes: file.get("bytes")?.as_u64()?,
sha256: file
.get("sha256")
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned(),
})
})
.collect()
})
.unwrap_or_default();
let current = current_key(s);
let mut objects: Vec<_> = files
.iter()
.filter(|file| file.key != current)
.cloned()
.collect();
objects.sort_by(|a, b| a.key.cmp(&b.key));
let pointer = files.iter().find(|file| file.key == current).cloned();
Ok(Stage {
dir,
objects,
pointer,
})
}
pub fn public_objects<'a>(
s: &Settings,
stage: &'a Stage,
id: &str,
) -> Result<&'a [crate::layout::StageFile]> {
for file in &stage.objects {
if !is_public(s, id, &file.key) {
bail!("{} refused: not a public file of {id}", file.key);
}
if let Some(refusal) = layout_key_refusal(&s.key_root, &file.key, false) {
bail!("{refusal}");
}
}
Ok(&stage.objects)
}
pub fn staged_pointer(s: &Settings, stage: &Stage, id: &str) -> Result<Pointer> {
let key = current_key(s);
let local = stage.dir.join(&key);
let entry = stage
.pointer
.as_ref()
.with_context(|| format!("stage.json of {id} does not list {key}"))?;
if !local.is_file() {
bail!("{key} is missing from the stage of {id}");
}
let bytes = fs::metadata(&local)
.with_context(|| format!("reading {}", local.display()))?
.len();
if bytes != entry.bytes {
bail!(
"{key} has {bytes} bytes, stage.json lists {}: not published",
entry.bytes
);
}
if sha256_hex(&local)? != entry.sha256 {
bail!("sha256 of {key} differs from stage.json: not published");
}
let pointer: Pointer = serde_json::from_value(read_json(&local)?)
.with_context(|| format!("cannot read {key}: not a pointer"))?;
if pointer.build_id != id {
bail!(
"{key} names build {}, not {id}: not published",
pointer.build_id
);
}
Ok(pointer)
}
pub fn parse_pointer(value: &Value) -> Result<Pointer> {
let period_end = value
.get("period_end")
.and_then(Value::as_str)
.filter(|date| {
let bytes = date.as_bytes();
bytes.len() == 10
&& bytes[4] == b'-'
&& bytes[7] == b'-'
&& [0, 1, 2, 3, 5, 6, 8, 9]
.iter()
.all(|i| bytes[*i].is_ascii_digit())
});
let build_id = value
.get("build_id")
.and_then(Value::as_str)
.filter(|id| is_build_id(id));
match (period_end, build_id) {
(Some(period_end), Some(build_id)) => Ok(Pointer {
build_id: build_id.to_owned(),
period_end: period_end.to_owned(),
}),
_ => bail!("lacks a YYYY-MM-DD period_end or a build-id build_id"),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::layout::Settings;
#[test]
fn a_pointer_names_the_build_and_its_period() {
let value = serde_json::json!({
"build_id": "2026-11-20.20261121T2329Z",
"period_end": "2026-11-18",
"dataset": "ndvi"
});
let pointer = parse_pointer(&value).expect("pointer");
assert_eq!(pointer.build_id, "2026-11-20.20261121T2329Z");
assert_eq!(pointer.period_end, "2026-11-18");
}
#[test]
fn a_pointer_without_a_dated_period_end_is_refused() {
let value = serde_json::json!({ "build_id": "2026-11-20.20261121T2329Z" });
assert!(parse_pointer(&value).is_err());
}
#[test]
fn a_stage_reads_back_without_its_pointer_among_the_objects() {
let dir = tempfile::tempdir().expect("a temp dir");
let stage_root = dir.path().join("datasets/stage");
let id = "2026-11-20.20261120T0000Z";
let stage_dir = stage_root.join(id);
std::fs::create_dir_all(&stage_dir).expect("mkdir");
std::fs::write(
stage_dir.join("stage.json"),
r#"{"build_id":"2026-11-20.20261120T0000Z","files":[
{"key":"datasets/rainfall/in/2026-11-20.20261120T0000Z/tiles.pmtiles","bytes":3,"sha256":"aa"},
{"key":"datasets/rainfall/in/current.json","bytes":2,"sha256":"bb"},
{"key":"datasets/rainfall/in/2026-11-20.20261120T0000Z/index.json","bytes":1,"sha256":"cc"}]}"#,
)
.expect("write");
let mut s = Settings::for_test("rainfall", "in", "/nonexistent/data");
s.stage_root = stage_root;
let stage = read_stage(&s, id).expect("stage");
assert_eq!(stage.objects.len(), 2);
assert_eq!(
stage.objects[0].key,
"datasets/rainfall/in/2026-11-20.20261120T0000Z/index.json"
);
assert_eq!(
stage.objects[1].key,
"datasets/rainfall/in/2026-11-20.20261120T0000Z/tiles.pmtiles"
);
assert_eq!(
stage.pointer.expect("pointer entry").key,
"datasets/rainfall/in/current.json"
);
}
}