use std::fs;
use std::path::{Path, PathBuf};
use crate::error::{
DatasetError, IoOp, IoResultExt as _, IoStepExt as _, JsonResultExt as _, Result,
};
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,
}
pub fn pointer_json(
s: &Settings,
build_id: &str,
index: &Value,
attribution: &str,
boundaries_attribution: &str,
written_at: &str,
) -> Result<String> {
let index: EngineIndex = serde_json::from_value(index.clone())
.json_of("index.json lacks the fields of a pointer")?;
let pointer = PointerFile {
dataset: &s.dataset,
country: s.cc.to_uppercase(),
build_id,
prefix: build_prefix(s, build_id),
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: attribution.to_owned(),
boundaries_attribution: boundaries_attribution.to_owned(),
codes_attribution: index.codes_attribution,
sensor: index.comparison.and_then(|comparison| comparison.sensor),
written_at: written_at.to_owned(),
};
let mut text = serde_json::to_string_pretty(&pointer).json_of("serializing the pointer")?;
text.push('\n');
Ok(text)
}
#[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).json_of(format!("serializing {}", path.display()))?;
text.push('\n');
let partial = path.with_extension("partial");
fs::write(&partial, text).io_at(IoOp::Write, &partial)?;
fs::rename(&partial, path).io_at(IoOp::RenameTo, path)
}
fn copy_file(from: &Path, to: &Path) -> Result<()> {
if !from.is_file() {
return Err(DatasetError::stage(format!("missing {}", from.display())));
}
if let Some(parent) = to.parent() {
fs::create_dir_all(parent).io_at(IoOp::Create, parent)?;
}
let partial = to.with_extension("partial");
fs::copy(from, &partial).io_step(format!(
"copying {} to {}",
from.display(),
partial.display()
))?;
fs::rename(&partial, to).io_at(IoOp::RenameTo, to)
}
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())
.ok_or_else(|| {
DatasetError::stage(format!("{} has no source", engine_dir.join(path).display()))
})?;
match &source {
None => {
source = Some(name.to_owned());
first = path;
}
Some(known) if known != name => {
return Err(DatasetError::stage(format!(
"{} names source {name}, not {known} ({first})",
engine_dir.join(path).display()
)));
}
Some(_) => {}
}
}
source.ok_or_else(|| DatasetError::stage(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"))?)
.io_at(IoOp::Read, engine_dir.join("manifest.json"))?;
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 {
return Err(DatasetError::stage(format!(
"{} 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() {
return Err(DatasetError::stage(format!(
"{} exists without stage.json",
done.display()
)));
}
let partial = s.stage_root.join(format!(".{id}.partial"));
if partial.exists() {
fs::remove_dir_all(&partial).io_at(IoOp::Remove, &partial)?;
}
let prefix = build_prefix(s, &id);
for file in &manifest.files {
if !is_public(s, &id, &format!("{prefix}{}", file.path)) {
return Err(DatasetError::stage(format!(
"{} 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)? {
return Err(DatasetError::stage(format!(
"{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 = read_json(&engine_dir.join("index.json"))?;
let boundaries_attribution = read_json(&areas_dir.join("areas.geojson"))?
.get("attribution")
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned();
let pointer = pointer_json(
s,
&id,
&index,
&manifest.attribution,
&boundaries_attribution,
&utc_now(),
)?;
let pointer_path = partial.join(current_key(s));
let pointer_partial = pointer_path.with_extension("partial");
if let Some(parent) = pointer_path.parent() {
fs::create_dir_all(parent).io_at(IoOp::Create, parent)?;
}
fs::write(&pointer_partial, pointer).io_at(IoOp::Write, &pointer_partial)?;
fs::rename(&pointer_partial, &pointer_path).io_at(IoOp::RenameTo, &pointer_path)?;
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).io_at(IoOp::Read, &path)?.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).io_step(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) {
return Err(DatasetError::stage(format!(
"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() {
return Err(DatasetError::stage(format!(
"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) {
return Err(DatasetError::stage(format!(
"{} refused: not a public file of {id}",
file.key
)));
}
if let Some(refusal) = layout_key_refusal(&s.key_root, &file.key, false) {
return Err(DatasetError::stage(refusal.to_string()));
}
}
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()
.ok_or_else(|| DatasetError::stage(format!("stage.json of {id} does not list {key}")))?;
if !local.is_file() {
return Err(DatasetError::stage(format!(
"{key} is missing from the stage of {id}"
)));
}
let bytes = fs::metadata(&local).io_at(IoOp::Read, &local)?.len();
if bytes != entry.bytes {
return Err(DatasetError::stage(format!(
"{key} has {bytes} bytes, stage.json lists {}: not published",
entry.bytes
)));
}
if sha256_hex(&local)? != entry.sha256 {
return Err(DatasetError::stage(format!(
"sha256 of {key} differs from stage.json: not published"
)));
}
let pointer: Pointer = serde_json::from_value(read_json(&local)?)
.json_of(format!("cannot read {key}: not a pointer"))?;
if pointer.build_id != id {
return Err(DatasetError::stage(format!(
"{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(),
}),
_ => Err(DatasetError::stage(
"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 the_pointer_text_is_pretty_json_in_the_script_field_order() {
let mut s = Settings::for_test("rainfall", "in", "/nonexistent/data");
s.boundary_tiles_revision = 2;
let index = serde_json::json!({
"period_start": "2026-11-06",
"period_end": "2026-11-10",
"status": "prelim",
"stale_after": "2026-11-28",
"codes_attribution": "Codes",
"comparison": { "sensor": "OLCI" }
});
let text = pointer_json(
&s,
"2026-11-10.20251117T0900Z",
&index,
"Attribution",
"Boundaries",
"2026-11-27T00:00:00Z",
)
.expect("pointer");
let expected = concat!(
"{\n",
" \"dataset\": \"rainfall\",\n",
" \"country\": \"IN\",\n",
" \"build_id\": \"2026-11-10.20251117T0900Z\",\n",
" \"prefix\": \"datasets/rainfall/in/2026-11-10.20251117T0900Z/\",\n",
" \"period_start\": \"2026-11-06\",\n",
" \"period_end\": \"2026-11-10\",\n",
" \"status\": \"prelim\",\n",
" \"stale_after\": \"2026-11-28\",\n",
" \"boundaries\": \"datasets/boundaries/in/2026-10-21.0-r2/\",\n",
" \"boundary_release\": \"2026-10-21.0\",\n",
" \"boundary_tiles_revision\": 2,\n",
" \"attribution\": \"Attribution\",\n",
" \"boundaries_attribution\": \"Boundaries\",\n",
" \"codes_attribution\": \"Codes\",\n",
" \"sensor\": \"OLCI\",\n",
" \"written_at\": \"2026-11-27T00:00:00Z\"\n",
"}\n"
);
assert_eq!(text, expected);
assert!(pointer_json(&s, "x", &serde_json::json!({}), "a", "b", "c").is_err());
}
#[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"
);
}
}