use std::collections::BTreeMap;
use std::env;
use std::fs;
use std::io::Read as _;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::{SystemTime, UNIX_EPOCH};
use crate::error::{
DatasetError, IoOp, IoResultExt as _, IoStepExt as _, JsonResultExt as _, NumberResultExt as _,
Result,
};
use serde_json::Value;
use sha2::{Digest as _, Sha256};
use crate::country::CountryConfig;
use crate::settings;
pub const DEFAULT_BOUNDARY_RELEASE: &str = "2026-10-21.0";
pub const DEFAULT_BASELINE: &str = "1991-2020";
pub const RESERVED_DATASET_IDS: [&str; 4] = ["files", "health", "catalog", "boundaries"];
#[must_use]
pub fn is_dataset_id(text: &str) -> bool {
is_segment(text) && !RESERVED_DATASET_IDS.contains(&text)
}
fn dataset_id_refusal(dataset: &str) -> Option<String> {
if RESERVED_DATASET_IDS.contains(&dataset) {
return Some(format!(
"dataset id {dataset:?} is reserved (reserved ids: {})",
RESERVED_DATASET_IDS.join(", ")
));
}
if !is_segment(dataset) {
return Some(format!(
"dataset id {dataset:?} must match ^[a-z0-9][a-z0-9-]*$"
));
}
None
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Settings {
pub dataset: String,
pub cc: String,
pub data_root: PathBuf,
pub repo: PathBuf,
pub key_root: String,
pub boundary_release: String,
pub boundary_tiles_revision: u8,
pub baseline: String,
pub config_path: PathBuf,
pub country_config_path: PathBuf,
pub published_csv: PathBuf,
pub stage_root: PathBuf,
}
impl Settings {
#[cfg(test)]
#[must_use]
pub fn for_test(dataset: &str, cc: &str, data_root: &str) -> Self {
let repo = PathBuf::from("/nonexistent/repo");
let data_root = PathBuf::from(data_root);
Self {
dataset: dataset.to_owned(),
cc: cc.to_owned(),
repo: repo.clone(),
key_root: crate::settings::DEFAULT_KEY_PREFIX.to_owned(),
config_path: repo
.join("packages/dataset-builder/data/datasets")
.join(format!("{dataset}.json")),
country_config_path: repo
.join("packages/dataset-builder/data/datasets/countries")
.join(format!("{cc}.json")),
published_csv: repo
.join("packages/dataset-builder/data/datasets")
.join(cc)
.join("published.csv"),
stage_root: data_root.join("datasets/stage"),
data_root,
boundary_release: DEFAULT_BOUNDARY_RELEASE.to_owned(),
boundary_tiles_revision: 1,
baseline: DEFAULT_BASELINE.to_owned(),
}
}
#[allow(clippy::too_many_arguments)]
pub fn new(
dataset: &str,
cc: &str,
data_root: impl Into<PathBuf>,
repo: impl Into<PathBuf>,
key_root: &str,
boundary_release: &str,
boundary_tiles_revision: u8,
baseline: &str,
) -> Result<Self> {
if let Some(refusal) = dataset_id_refusal(dataset) {
return Err(DatasetError::config(refusal));
}
let cc = cc.to_lowercase();
if !is_segment(&cc) {
return Err(DatasetError::config(format!(
"country {cc:?} must match ^[a-z0-9][a-z0-9-]*$"
)));
}
if !key_root.ends_with('/') {
return Err(DatasetError::config(format!(
"key prefix {key_root:?} must end in /"
)));
}
if !(1..=99).contains(&boundary_tiles_revision) {
return Err(DatasetError::config(
"boundary tiles revision must be an integer 1..99",
));
}
let repo = repo.into();
let data_root = data_root.into();
let datasets = repo.join("packages/dataset-builder/data/datasets");
Ok(Self {
dataset: dataset.to_owned(),
config_path: datasets.join(format!("{dataset}.json")),
country_config_path: datasets.join("countries").join(format!("{cc}.json")),
published_csv: datasets.join(&cc).join("published.csv"),
stage_root: data_root.join("datasets/stage"),
cc,
data_root,
repo,
key_root: key_root.to_owned(),
boundary_release: boundary_release.to_owned(),
boundary_tiles_revision,
baseline: baseline.to_owned(),
})
}
#[must_use]
pub fn country_config(&self) -> Option<CountryConfig> {
CountryConfig::load(&self.country_config_path).ok()
}
#[must_use]
pub fn key_top(&self) -> &str {
self.key_root.split('/').next().unwrap_or_default()
}
}
pub fn repo_root() -> Result<PathBuf> {
if let Some(dir) = settings::current().repo.clone() {
return Ok(dir);
}
let built = Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.map(Path::to_path_buf)
.ok_or_else(|| DatasetError::config("the crate manifest has no repo root"))?;
if is_checkout(&built) {
return Ok(built);
}
let cwd = env::current_dir().io_step("reading the working directory")?;
let output = Command::new("git")
.arg("-C")
.arg(&cwd)
.args(["rev-parse", "--show-toplevel"])
.output()
.io_step("running git rev-parse")?;
if !output.status.success() {
return Err(DatasetError::config(format!(
"not in a geolith checkout: {} (set GEOLITH_REPO): {}",
cwd.display(),
String::from_utf8_lossy(&output.stderr).trim()
)));
}
let root = PathBuf::from(String::from_utf8_lossy(&output.stdout).trim());
if !is_checkout(&root) {
return Err(DatasetError::config(format!(
"{} is not a geolith checkout (set GEOLITH_REPO)",
root.display()
)));
}
Ok(root)
}
fn is_checkout(dir: &Path) -> bool {
dir.join("packages/dataset-builder/data/datasets/boundaries.json")
.is_file()
}
pub fn data_root() -> Result<PathBuf> {
if let Some(dir) = settings::current().data_root.clone() {
return Ok(dir);
}
let repo = repo_root()?;
let output = Command::new("git")
.arg("-C")
.arg(&repo)
.args(["rev-parse", "--path-format=absolute", "--git-common-dir"])
.output()
.io_step("running git rev-parse")?;
if !output.status.success() {
return Err(DatasetError::config(format!(
"not in a git checkout: {} (set DATA_ROOT): {}",
repo.display(),
String::from_utf8_lossy(&output.stderr).trim()
)));
}
let common = PathBuf::from(String::from_utf8_lossy(&output.stdout).trim());
let root = common.join("..").join(".data");
if !root.is_dir() {
return Err(DatasetError::config(format!(
"data root not found: {} (set DATA_ROOT)",
root.display()
)));
}
fs::canonicalize(&root).io_step(format!("resolving {}", root.display()))
}
pub fn settings(dataset: Option<&str>, country: Option<&str>) -> Result<Settings> {
let data_root = data_root()?;
let repo = repo_root()?;
let run = &settings::current().run;
let dataset = dataset
.map(str::to_owned)
.or_else(|| run.dataset.clone())
.unwrap_or_else(|| "rainfall".to_owned());
if let Some(refusal) = dataset_id_refusal(&dataset) {
return Err(DatasetError::config(refusal));
}
let cc = country
.map(str::to_owned)
.or_else(|| run.country.clone())
.unwrap_or_else(|| "in".to_owned())
.to_lowercase();
let datasets = repo.join("packages/dataset-builder/data/datasets");
let config_path = datasets.join(format!("{dataset}.json"));
let country_config_path = run
.country_config
.clone()
.unwrap_or_else(|| datasets.join("countries").join(format!("{cc}.json")));
let boundary_release = run
.boundary_release
.clone()
.or_else(|| country_release(&country_config_path))
.unwrap_or_else(|| DEFAULT_BOUNDARY_RELEASE.to_owned());
let boundary_tiles_revision = match &run.boundary_tiles_revision {
Some(value) => value.parse::<u8>().number_of(format!(
"BOUNDARY_TILES_REVISION {value:?} is not a tiles revision"
))?,
None => config_tiles_revision(&datasets.join("boundaries.json"))?,
};
if boundary_tiles_revision == 0 {
return Err(DatasetError::config(format!(
"{}: tiles_revision must be an integer 1..99",
datasets.join("boundaries.json").display()
)));
}
let baseline = run
.baseline
.clone()
.or_else(|| {
read_json(&config_path).ok().and_then(|value| {
value
.get("baseline")
.and_then(Value::as_str)
.map(str::to_owned)
})
})
.unwrap_or_else(|| DEFAULT_BASELINE.to_owned());
let published_csv = run
.published_csv
.clone()
.unwrap_or_else(|| datasets.join(&cc).join("published.csv"));
Ok(Settings {
dataset,
cc,
stage_root: data_root.join("datasets/stage"),
data_root,
repo,
key_root: settings::current().key_root().to_owned(),
boundary_release,
boundary_tiles_revision,
baseline,
config_path,
country_config_path,
published_csv,
})
}
pub fn config_tiles_revision(path: &Path) -> Result<u8> {
let value = read_json(path)?
.get("tiles_revision")
.and_then(Value::as_u64)
.ok_or_else(|| {
DatasetError::config({
format!(
"{}: tiles_revision must be an integer 1..99",
path.display()
)
})
})?;
let revision = u8::try_from(value)
.ok()
.filter(|revision| (1..=99).contains(revision))
.ok_or_else(|| {
DatasetError::config({
format!(
"{}: tiles_revision must be an integer 1..99",
path.display()
)
})
})?;
Ok(revision)
}
fn country_release(path: &Path) -> Option<String> {
read_json(path)
.ok()?
.get("boundaries")?
.get("release")?
.as_str()
.filter(|release| !release.is_empty())
.map(str::to_owned)
}
pub fn read_json(path: &Path) -> Result<Value> {
let text = fs::read_to_string(path).io_at(IoOp::Read, path)?;
serde_json::from_str(&text).json_of(format!("parsing {}", path.display()))
}
#[must_use]
pub fn boundaries_dir(s: &Settings) -> String {
if s.boundary_tiles_revision >= 2 {
format!("{}-r{}", s.boundary_release, s.boundary_tiles_revision)
} else {
s.boundary_release.clone()
}
}
#[must_use]
pub fn build_prefix(s: &Settings, id: &str) -> String {
format!("{}{}/{}/{id}/", s.key_root, s.dataset, s.cc)
}
#[must_use]
pub fn boundaries_prefix(s: &Settings) -> String {
format!("{}boundaries/{}/{}/", s.key_root, s.cc, boundaries_dir(s))
}
#[must_use]
pub fn current_key(s: &Settings) -> String {
format!("{}{}/{}/current.json", s.key_root, s.dataset, s.cc)
}
#[must_use]
pub fn is_public(s: &Settings, id: &str, key: &str) -> bool {
let build = build_prefix(s, id);
if let Some(rest) = key.strip_prefix(&format!("{build}areas/")) {
return is_area_file(rest);
}
if let Some(rest) = key.strip_prefix(&format!("{build}tiles/")) {
return is_period_layer(rest);
}
let boundaries = boundaries_prefix(s);
[
format!("{build}index.json"),
format!("{build}series.json"),
format!("{build}numbers.csv"),
format!("{build}numbers.parquet"),
format!("{build}tiles.pmtiles"),
format!("{boundaries}areas.pmtiles"),
format!("{boundaries}areas.parquet"),
format!("{boundaries}LICENSE.txt"),
current_key(s),
]
.iter()
.any(|public| public == key)
}
fn is_area_file(name: &str) -> bool {
let Some(stem) = name.strip_suffix(".json") else {
return false;
};
let mut bytes = stem.bytes();
let Some(first) = bytes.next() else {
return false;
};
if !(first.is_ascii_alphanumeric() || first == b'_' || first == b'-') {
return false;
}
bytes.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'-'))
}
fn is_period_layer(name: &str) -> bool {
let Some(date) = name.strip_suffix(".pmtiles") else {
return false;
};
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())
}
#[must_use]
pub fn is_layout_key(key_root: &str, key: &str, pointer: bool) -> bool {
if key.split('/').any(|part| part == ".." || part == ".") {
return false;
}
let Some(rest) = key.strip_prefix(key_root) else {
return false;
};
let parts: Vec<&str> = rest.split('/').collect();
let Some(head) = parts.first() else {
return false;
};
if *head == "boundaries" {
return match parts.as_slice() {
[_, cc, release, file] => {
!pointer
&& is_segment(cc)
&& is_release(release)
&& matches!(*file, "areas.pmtiles" | "areas.parquet" | "LICENSE.txt")
}
_ => false,
};
}
if !is_dataset_id(head) {
return false;
}
match parts.as_slice() {
[ds, cc, pointer_file] => {
pointer && is_segment(ds) && is_segment(cc) && *pointer_file == "current.json"
}
[ds, cc, id, file] => {
!pointer && is_segment(ds) && is_segment(cc) && is_build_id(id) && is_build_file(file)
}
[ds, cc, id, dir, file] => {
!pointer
&& is_segment(ds)
&& is_segment(cc)
&& is_build_id(id)
&& (match *dir {
"tiles" => is_period_layer(file),
"areas" => is_area_file(file),
_ => false,
})
}
_ => false,
}
}
fn is_build_file(name: &str) -> bool {
matches!(
name,
"index.json" | "series.json" | "numbers.csv" | "numbers.parquet" | "tiles.pmtiles"
)
}
fn is_segment(text: &str) -> bool {
let mut bytes = text.bytes();
let Some(first) = bytes.next() else {
return false;
};
(first.is_ascii_lowercase() || first.is_ascii_digit())
&& bytes.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
}
#[must_use]
pub fn is_build_id(text: &str) -> bool {
let bytes = text.as_bytes();
bytes.len() == 25
&& bytes[4] == b'-'
&& bytes[7] == b'-'
&& bytes[10] == b'.'
&& bytes[19] == b'T'
&& bytes[24] == b'Z'
&& [
0, 1, 2, 3, 5, 6, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23,
]
.iter()
.all(|i| bytes[*i].is_ascii_digit())
}
fn is_release(text: &str) -> bool {
let bytes = text.as_bytes();
if bytes.len() < 11
|| bytes[4] != b'-'
|| bytes[7] != b'-'
|| bytes[10] != b'.'
|| ![0, 1, 2, 3, 5, 6, 8, 9]
.iter()
.all(|i| bytes[*i].is_ascii_digit())
{
return false;
}
let rest = &text[11..];
let (number, suffix) = match rest.split_once("-r") {
Some((number, revision)) => (number, Some(revision)),
None => (rest, None),
};
if number.is_empty() || !number.bytes().all(|b| b.is_ascii_digit()) {
return false;
}
match suffix {
None => true,
Some(revision) => match revision.parse::<u8>() {
Ok(value) => (2..=99).contains(&value) && !revision.starts_with('0'),
Err(_) => false,
},
}
}
#[must_use]
pub fn layout_key_refusal(key_root: &str, key: &str, pointer: bool) -> Option<String> {
if is_layout_key(key_root, key, pointer) {
return None;
}
let what = if pointer {
"a current.json pointer"
} else {
"a dated dataset key"
};
Some(format!("key {key} refused: not {what} under {key_root}"))
}
#[must_use]
pub fn complete_stages(root: &Path) -> Vec<String> {
let Ok(entries) = fs::read_dir(root) else {
return Vec::new();
};
let mut names: Vec<String> = entries
.filter_map(|entry| entry.ok())
.filter(|entry| !entry.file_name().to_string_lossy().starts_with('.'))
.filter(|entry| entry.path().join("stage.json").is_file())
.map(|entry| entry.file_name().to_string_lossy().into_owned())
.collect();
names.sort();
names
}
pub fn files_under(dir: &Path) -> Result<Vec<String>> {
fn walk(dir: &Path, prefix: &str, out: &mut Vec<String>) -> Result<()> {
for entry in fs::read_dir(dir).io_at(IoOp::Read, dir)? {
let entry = entry.io_at(IoOp::Read, dir)?;
let name = entry.file_name().to_string_lossy().into_owned();
let path = entry.path();
if path.is_dir() {
walk(&path, &format!("{prefix}{name}/"), out)?;
} else {
out.push(format!("{prefix}{name}"));
}
}
Ok(())
}
let mut out = Vec::new();
walk(dir, "", &mut out)?;
out.sort();
Ok(out)
}
pub fn sha256_file(path: &Path) -> Result<[u8; 32]> {
let mut file = fs::File::open(path).io_at(IoOp::Open, path)?;
let mut hasher = Sha256::new();
let mut buffer = vec![0_u8; 1 << 16];
loop {
let read = file.read(&mut buffer).io_at(IoOp::Read, path)?;
if read == 0 {
break;
}
hasher.update(&buffer[..read]);
}
Ok(hasher.finalize().into())
}
pub fn sha256_hex(path: &Path) -> Result<String> {
Ok(hex(&sha256_file(path)?))
}
#[must_use]
pub fn hex(digest: &[u8]) -> String {
use std::fmt::Write as _;
digest.iter().fold(String::new(), |mut out, byte| {
let _ = write!(out, "{byte:02x}");
out
})
}
#[must_use]
pub fn format_utc(secs: i64) -> String {
let (year, month, day, hour, minute, second) = split_utc(secs);
format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}Z")
}
#[must_use]
pub fn date_utc(secs: i64) -> String {
let (year, month, day, _, _, _) = split_utc(secs);
format!("{year:04}-{month:02}-{day:02}")
}
#[must_use]
pub fn format_utc_millis(millis: i128) -> String {
let secs = i64::try_from(millis.div_euclid(1000)).unwrap_or(i64::MAX);
let rest = millis.rem_euclid(1000);
let (year, month, day, hour, minute, second) = split_utc(secs);
format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}.{rest:03}Z")
}
#[must_use]
pub fn utc_now() -> String {
format_utc(unix_seconds())
}
#[must_use]
pub fn today_utc() -> String {
date_utc(unix_seconds())
}
#[must_use]
pub fn unix_seconds() -> i64 {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default();
i64::try_from(now.as_secs()).unwrap_or(i64::MAX)
}
pub fn modified_millis(path: &Path) -> Result<i128> {
let modified = fs::metadata(path)
.io_at(IoOp::Read, path)?
.modified()
.io_step(format!("reading the mtime of {}", path.display()))?;
let Ok(since) = modified.duration_since(UNIX_EPOCH) else {
return Ok(0);
};
let nanos = i128::from(since.subsec_nanos());
Ok(i128::from(since.as_secs()) * 1000 + (nanos + 500_000) / 1_000_000)
}
fn split_utc(secs: i64) -> (i64, i64, i64, i64, i64, i64) {
let days = secs.div_euclid(86_400);
let rest = secs.rem_euclid(86_400);
let (year, month, day) = civil_from_days(days);
(year, month, day, rest / 3600, rest % 3600 / 60, rest % 60)
}
#[must_use]
fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
let year = if month <= 2 { year - 1 } else { year };
let era = year.div_euclid(400);
let yoe = year - era * 400;
let mp = if month > 2 { month - 3 } else { month + 9 };
let doy = (153 * mp + 2) / 5 + day - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
era * 146_097 + doe - 719_468
}
#[must_use]
fn civil_from_days(days: i64) -> (i64, i64, i64) {
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = doy - (153 * mp + 2) / 5 + 1;
let month = if mp < 10 { mp + 3 } else { mp - 9 };
let year = yoe + era * 400 + i64::from(month <= 2);
(year, month, day)
}
#[must_use]
pub fn days_of_date(date: &str) -> Option<i64> {
let mut parts = date.split('-');
let year = parts.next()?.parse::<i64>().ok()?;
let month = parts.next()?.parse::<i64>().ok()?;
let day = parts.next()?.parse::<i64>().ok()?;
if parts.next().is_some() {
return None;
}
Some(days_from_civil(year, month, day))
}
pub type StagedFiles = BTreeMap<String, StageFile>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StageFile {
pub key: String,
pub bytes: u64,
pub sha256: String,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_public_set_is_the_build_files_the_areas_and_the_three_boundary_files() {
let s = Settings::for_test("rainfall", "in", "/nonexistent/data");
let base = "datasets/rainfall/in/2026-11-20.20261120T0000Z/";
for ok in [
"index.json",
"numbers.csv",
"numbers.parquet",
"tiles.pmtiles",
"areas/dr-kolkata.json",
] {
assert!(
is_public(&s, "2026-11-20.20261120T0000Z", &format!("{base}{ok}")),
"{ok}"
);
}
assert!(is_public(
&s,
"2026-11-20.20261120T0000Z",
"datasets/boundaries/in/2026-10-21.0/LICENSE.txt"
));
assert!(!is_public(
&s,
"2026-11-20.20261120T0000Z",
&format!("{base}manifest.json")
));
assert!(!is_public(
&s,
"2026-11-20.20261120T0000Z",
&format!("{base}stats/notes.csv")
));
}
#[test]
fn complete_stages_are_oldest_first_and_need_a_stage_json() {
let dir = tempfile::tempdir().expect("a temp dir");
for name in ["2026-11-20.20261120T0000Z", "2026-11-10.20261110T0000Z"] {
std::fs::create_dir(dir.path().join(name)).expect("mkdir");
std::fs::write(dir.path().join(name).join("stage.json"), "{}").expect("write");
}
std::fs::create_dir(dir.path().join("2026-11-15.20261115T0000Z")).expect("mkdir");
assert_eq!(
complete_stages(dir.path()),
vec![
"2026-11-10.20261110T0000Z".to_owned(),
"2026-11-20.20261120T0000Z".to_owned()
]
);
}
#[test]
fn the_tiles_revision_of_the_boundaries_config_is_read() {
let dir = tempfile::tempdir().expect("a temp dir");
let path = dir.path().join("boundaries.json");
std::fs::write(&path, r#"{"tiles_revision": 2}"#).expect("write");
assert_eq!(config_tiles_revision(&path).expect("revision"), 2);
std::fs::write(&path, r#"{"tiles_revision": 0}"#).expect("write");
assert!(config_tiles_revision(&path).is_err());
}
#[test]
fn a_revision_two_boundaries_folder_carries_the_suffix() {
let mut s = Settings::for_test("rainfall", "in", "/d");
s.boundary_tiles_revision = 2;
assert_eq!(boundaries_dir(&s), "2026-10-21.0-r2");
s.boundary_tiles_revision = 1;
assert_eq!(boundaries_dir(&s), "2026-10-21.0");
}
#[test]
fn a_deep_key_prefix_moves_every_key_and_the_stage_top() {
let mut s = Settings::for_test("rainfall", "in", "/d");
s.key_root = "mirror/ds/".to_owned();
assert_eq!(s.key_top(), "mirror");
let id = "2026-11-20.20261120T0000Z";
assert_eq!(
build_prefix(&s, id),
"mirror/ds/rainfall/in/2026-11-20.20261120T0000Z/"
);
assert_eq!(current_key(&s), "mirror/ds/rainfall/in/current.json");
assert_eq!(
boundaries_prefix(&s),
"mirror/ds/boundaries/in/2026-10-21.0/"
);
assert!(is_public(&s, id, ¤t_key(&s)));
assert!(!is_public(&s, id, "datasets/rainfall/in/current.json"));
}
#[test]
fn a_release_folder_with_an_r1_suffix_is_not_a_boundaries_key() {
let root = "datasets/";
assert!(
layout_key_refusal(
root,
"datasets/boundaries/in/2026-10-21.0-r1/areas.pmtiles",
false
)
.is_some()
);
assert!(
layout_key_refusal(
root,
"datasets/boundaries/in/2026-10-21.0-r2/areas.pmtiles",
false
)
.is_none()
);
}
#[test]
fn a_key_outside_the_prefix_or_with_a_path_traversal_is_refused() {
let root = "mirror/ds/";
let pointer = "mirror/ds/rainfall/in/current.json";
assert!(layout_key_refusal(root, pointer, true).is_none());
assert!(layout_key_refusal(root, pointer, false).is_some());
assert!(layout_key_refusal(root, "mirror/ds/../../etc/passwd", false).is_some());
let error =
layout_key_refusal(root, "datasets/rainfall/in/current.json", true).expect("refused");
assert!(error.contains("under mirror/ds/"), "{error}");
let build = "mirror/ds/rainfall/in/2026-11-20.20261120T0000Z/tiles.pmtiles";
assert!(layout_key_refusal(root, build, false).is_none());
assert!(
layout_key_refusal(
root,
"mirror/ds/Rain/in/2026-11-20.20261120T0000Z/tiles.pmtiles",
false
)
.is_some()
);
}
#[test]
fn a_formatted_utc_second_is_its_iso_string() {
assert_eq!(format_utc(1_795_132_800), "2026-11-20T00:00:00Z");
}
#[test]
fn reserved_dataset_ids_are_not_dataset_ids() {
for reserved in ["files", "health", "catalog", "boundaries"] {
assert!(!is_dataset_id(reserved), "{reserved}");
}
for ok in ["rainfall", "ndvi", "a", "x-1", "9"] {
assert!(is_dataset_id(ok), "{ok}");
}
for bad in ["", "Rain", "-x", "a_b", "a/b", ".."] {
assert!(!is_dataset_id(bad), "{bad:?}");
}
}
#[test]
fn a_reserved_dataset_is_not_a_layout_key_but_boundaries_keep_their_shape() {
let root = "datasets/";
for reserved in ["files", "health", "catalog"] {
assert!(
layout_key_refusal(root, &format!("datasets/{reserved}/in/current.json"), true)
.is_some(),
"{reserved}"
);
}
assert!(
layout_key_refusal(
root,
"datasets/boundaries/in/2026-10-21.0/areas.pmtiles",
false
)
.is_none()
);
}
#[test]
fn settings_from_explicit_values_read_nothing_and_refuse_reserved_ids() {
let s = Settings::new(
"rainfall",
"IN",
"/d",
"/r",
"datasets/",
"2026-10-21.0",
2,
"1991-2020",
)
.expect("settings");
assert_eq!(s.cc, "in");
assert_eq!(s.stage_root, PathBuf::from("/d/datasets/stage"));
assert_eq!(boundaries_dir(&s), "2026-10-21.0-r2");
assert_eq!(current_key(&s), "datasets/rainfall/in/current.json");
for (dataset, cc, root, revision) in [
("files", "in", "datasets/", 1),
("boundaries", "in", "datasets/", 1),
("Rain", "in", "datasets/", 1),
("rainfall", "IN/", "datasets/", 1),
("rainfall", "in", "datasets", 1),
("rainfall", "in", "datasets/", 0),
] {
assert!(
Settings::new(dataset, cc, "/d", "/r", root, "2026-10-21.0", revision, "b")
.is_err(),
"{dataset} {cc} {root} {revision}"
);
}
}
#[test]
fn the_sha256_of_an_empty_file_is_the_known_digest() {
let dir = tempfile::tempdir().expect("a temp dir");
let path = dir.path().join("empty");
std::fs::write(&path, b"").expect("write");
assert_eq!(
sha256_hex(&path).expect("digest"),
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
);
}
}