use std::collections::BTreeMap;
use std::path::Path;
use anyhow::{Context as _, bail};
use geo::{BooleanOps as _, Coord, MultiPolygon, Rect};
use md5::{Digest as _, Md5};
use serde::{Deserialize, Serialize};
use super::areas::Area;
const MAX_ZOOM_LIMIT: u8 = 22;
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum BoundarySource {
Overture,
Shapefile,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UnitWords {
pub one: String,
pub many: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BoundaryFile {
pub url: String,
pub member: String,
pub sha256: String,
pub fields: Fields,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub skip: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Fields {
pub code: String,
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parent: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Invariants {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub areas: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parents: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub min_areas_per_parent: Option<usize>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Boundaries {
pub source: BoundarySource,
pub release: String,
pub attribution: String,
#[serde(default)]
pub codes_attribution: Option<String>,
pub licence_id: String,
#[serde(default)]
pub licence_file: Option<String>,
#[serde(default)]
pub holds_soi_land: bool,
pub level: String,
#[serde(default)]
pub units: Option<BoundaryFile>,
#[serde(default)]
pub parents: Option<BoundaryFile>,
#[serde(default)]
pub invariants: Invariants,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DatasetLimits {
#[serde(default)]
pub min_coverage_pct: Option<f64>,
#[serde(default)]
pub max_zoom: Option<u8>,
#[serde(default)]
pub history_max_zoom: Option<u8>,
}
fn default_published_first() -> usize {
24
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CountryConfig {
pub code: String,
pub name: String,
pub unit: UnitWords,
pub parent: UnitWords,
pub bounds: [f64; 4],
pub boundaries: Boundaries,
#[serde(default)]
pub datasets: BTreeMap<String, DatasetLimits>,
#[serde(default = "default_published_first")]
pub published_first: usize,
}
impl CountryConfig {
pub fn load(path: &Path) -> anyhow::Result<Self> {
let text = std::fs::read_to_string(path)
.with_context(|| format!("reading country config {}", path.display()))?;
Self::from_json_str(&text)
.with_context(|| format!("invalid country config {}", path.display()))
}
pub fn from_json_str(s: &str) -> anyhow::Result<Self> {
let config: Self = serde_json::from_str(s).context("parsing country config JSON")?;
config.validate()?;
Ok(config)
}
fn validate(&self) -> anyhow::Result<()> {
let code_ok = self.code.len() == 2
&& self
.code
.chars()
.all(|c| c.is_ascii_lowercase() && c.is_ascii_alphabetic());
if !code_ok {
bail!("code {:?} is not two lowercase letters", self.code);
}
let [min_lon, min_lat, max_lon, max_lat] = self.bounds;
let rises = |a: f64, b: f64| a.partial_cmp(&b) == Some(std::cmp::Ordering::Less);
if !rises(min_lon, max_lon) || !rises(min_lat, max_lat) {
bail!(
"bounds [{min_lon}, {min_lat}, {max_lon}, {max_lat}] are out of order: \
needs min_lon < max_lon and min_lat < max_lat"
);
}
if self.boundaries.release.trim().is_empty() {
bail!("boundaries.release is empty");
}
if self.boundaries.attribution.trim().is_empty() {
bail!("boundaries.attribution is empty");
}
if self.boundaries.licence_id.trim().is_empty() {
bail!("boundaries.licence_id is empty");
}
match self.boundaries.source {
BoundarySource::Shapefile => {
if self.boundaries.units.is_none() {
bail!("boundaries.source is shapefile, so it needs a units file");
}
if self.boundaries.parents.is_none() {
bail!("boundaries.source is shapefile, so it needs a parents file");
}
}
BoundarySource::Overture => {
if self.boundaries.units.is_some() {
bail!("boundaries.source is overture, so units must be absent");
}
if self.boundaries.parents.is_some() {
bail!("boundaries.source is overture, so parents must be absent");
}
}
}
for (dataset, limits) in &self.datasets {
for (key, zoom) in [
("max_zoom", limits.max_zoom),
("history_max_zoom", limits.history_max_zoom),
] {
if let Some(zoom) = zoom
&& zoom > MAX_ZOOM_LIMIT
{
bail!("datasets.{dataset}.{key} {zoom} is above {MAX_ZOOM_LIMIT}");
}
}
if let Some(pct) = limits.min_coverage_pct
&& !(0.0..=100.0).contains(&pct)
{
bail!("datasets.{dataset}.min_coverage_pct {pct} is not 0..=100");
}
}
Ok(())
}
#[must_use]
pub fn limits(&self, dataset: &str) -> Option<&DatasetLimits> {
self.datasets.get(dataset)
}
#[must_use]
pub fn area_id(&self, code: &str) -> String {
official_id(&self.code, code)
}
pub fn check_counts(&self, areas: &[Area]) -> anyhow::Result<()> {
let invariants = &self.boundaries.invariants;
if let Some(expected) = invariants.areas
&& areas.len() != expected
{
bail!("expected {expected} areas, found {}", areas.len());
}
let mut per_parent: BTreeMap<&str, usize> = BTreeMap::new();
let mut orphans = 0_usize;
for area in areas {
match area.parent_id.as_deref() {
Some(parent) => *per_parent.entry(parent).or_default() += 1,
None => orphans += 1,
}
}
if let Some(expected) = invariants.parents
&& per_parent.len() != expected
{
bail!("expected {expected} parents, found {}", per_parent.len());
}
if (invariants.parents.is_some() || invariants.min_areas_per_parent.is_some())
&& orphans > 0
{
bail!("{orphans} areas have no parent: they name a parent the parent file lacks");
}
if let Some(minimum) = invariants.min_areas_per_parent {
for (parent, count) in &per_parent {
if *count < minimum {
bail!(
"parent {parent} holds {count} areas, under the {minimum} the config asks for"
);
}
}
}
Ok(())
}
}
#[must_use]
pub fn official_id(country: &str, code: &str) -> String {
let mut hasher = Md5::new();
hasher.update(format!("geolith:{}:{code}", country.to_lowercase()).as_bytes());
let mut bytes: [u8; 16] = hasher.finalize().into();
bytes[6] = (bytes[6] & 0x0f) | 0x30;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
let hex: String = bytes.iter().map(|b| format!("{b:02x}")).collect();
format!(
"{}-{}-{}-{}-{}",
&hex[0..8],
&hex[8..12],
&hex[12..16],
&hex[16..20],
&hex[20..32]
)
}
fn shift(shape: &MultiPolygon<f64>, dx: f64) -> MultiPolygon<f64> {
shift_by(shape, |x| x + dx)
}
fn rebase_negative(shape: &MultiPolygon<f64>) -> MultiPolygon<f64> {
shift_by(shape, |x| if x < 0.0 { x + 360.0 } else { x })
}
fn shift_by(shape: &MultiPolygon<f64>, f: impl Fn(f64) -> f64) -> MultiPolygon<f64> {
let moved: Vec<geo::Polygon<f64>> = shape
.0
.iter()
.map(|polygon| {
let exterior = map_ring(polygon.exterior(), &f);
let holes = polygon
.interiors()
.iter()
.map(|ring| map_ring(ring, &f))
.collect();
geo::Polygon::new(exterior, holes)
})
.collect();
MultiPolygon(moved)
}
fn map_ring(ring: &geo::LineString<f64>, f: &impl Fn(f64) -> f64) -> geo::LineString<f64> {
geo::LineString::new(ring.0.iter().map(|c| Coord { x: f(c.x), y: c.y }).collect())
}
#[must_use]
pub fn split_antimeridian(shape: &MultiPolygon<f64>) -> MultiPolygon<f64> {
let mut crosses = false;
for polygon in &shape.0 {
let mut lo = f64::INFINITY;
let mut hi = f64::NEG_INFINITY;
for ring in std::iter::once(polygon.exterior()).chain(polygon.interiors()) {
for coord in &ring.0 {
lo = lo.min(coord.x);
hi = hi.max(coord.x);
}
}
if hi - lo > 180.0 {
crosses = true;
break;
}
}
if !crosses {
return shape.clone();
}
let shifted = rebase_negative(shape);
let seam = |x0: f64, x1: f64| {
Rect::new(Coord { x: x0, y: -90.0 }, Coord { x: x1, y: 90.0 }).to_polygon()
};
let mut parts: Vec<MultiPolygon<f64>> = Vec::new();
for (band, back) in [(seam(0.0, 180.0), 0.0), (seam(180.0, 360.0), -360.0)] {
let piece = shifted.intersection(&band);
if piece.0.is_empty() {
continue;
}
parts.push(if back == 0.0 {
piece
} else {
shift(&piece, back)
});
}
if parts.is_empty() {
return shape.clone();
}
use geo::orient::{Direction, Orient as _};
geo::unary_union(&parts).orient(Direction::Default)
}
#[cfg(test)]
mod tests {
use super::*;
use geo::{Area as _, LineString, Polygon};
fn rect(x0: f64, y0: f64, x1: f64, y1: f64) -> MultiPolygon<f64> {
MultiPolygon(vec![Polygon::new(
LineString::new(vec![
Coord { x: x0, y: y0 },
Coord { x: x1, y: y0 },
Coord { x: x1, y: y1 },
Coord { x: x0, y: y1 },
Coord { x: x0, y: y0 },
]),
Vec::new(),
)])
}
fn config_dir() -> std::path::PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("data/datasets/countries")
}
fn load(code: &str) -> CountryConfig {
CountryConfig::load(&config_dir().join(format!("{code}.json")))
.unwrap_or_else(|e| panic!("{code}.json loads: {e:#}"))
}
#[test]
fn the_three_repo_configs_load() {
let india = load("in");
assert_eq!(india.boundaries.source, BoundarySource::Overture);
assert!(india.boundaries.holds_soi_land);
assert!(india.boundaries.units.is_none());
assert_eq!(india.boundaries.release, "2026-10-21.0");
assert_eq!(india.boundaries.invariants.areas, Some(787));
assert_eq!(
india.boundaries.attribution,
crate::areas::BOUNDARIES_ATTRIBUTION
);
assert_eq!(india.published_first, 20);
let us = load("us");
assert_eq!(us.boundaries.source, BoundarySource::Shapefile);
assert_eq!(us.bounds, [-170.0, 18.0, -66.0, 72.0]);
assert_eq!(us.unit.many, "counties");
assert_eq!(us.parent.many, "states");
let units = us.boundaries.units.as_ref().expect("units");
assert_eq!(units.fields.code, "GEOID");
let parents = us.boundaries.parents.as_ref().expect("parents");
assert_eq!(parents.skip, vec!["60", "66", "69", "72", "78"]);
assert_eq!(
us.limits("rainfall")
.expect("rainfall limits")
.min_coverage_pct,
Some(60.0)
);
assert_eq!(us.limits("ndvi").expect("ndvi limits").max_zoom, Some(8));
assert_eq!(us.published_first, 24);
let au = load("au");
assert_eq!(au.boundaries.release, "2025-07-22.0");
assert_eq!(au.unit.many, "local government areas");
assert_eq!(au.boundaries.invariants.areas, Some(548));
assert_eq!(au.boundaries.invariants.parents, Some(9));
}
#[test]
fn a_config_without_bounds_is_refused() {
let json = r#"{
"code": "us", "name": "United States",
"unit": {"one": "county", "many": "counties"},
"parent": {"one": "state", "many": "states"},
"boundaries": {"source": "overture", "release": "2026-01-01.0",
"attribution": "x", "licence_id": "CC0-1.0", "level": "county"}
}"#;
let err = CountryConfig::from_json_str(json).expect_err("no bounds");
assert!(format!("{err:#}").contains("bounds"), "{err:#}");
}
#[test]
fn shapefile_needs_units_and_parents() {
let json = r#"{
"code": "us", "name": "United States",
"unit": {"one": "county", "many": "counties"},
"parent": {"one": "state", "many": "states"},
"bounds": [-170.0, 18.0, -66.0, 72.0],
"boundaries": {"source": "shapefile", "release": "2026-01-01.0",
"attribution": "x", "licence_id": "CC0-1.0", "level": "county"}
}"#;
let err = CountryConfig::from_json_str(json).expect_err("no units");
assert!(format!("{err:#}").contains("units"), "{err:#}");
}
fn area(id: &str, parent: Option<&str>) -> Area {
Area {
code: None,
id: id.to_string(),
name: id.to_string(),
country: "US".to_string(),
level: "county".to_string(),
parent_id: parent.map(str::to_string),
parent_name: parent.map(str::to_string),
region_code: parent.map(str::to_string),
shape: rect(0.0, 0.0, 1.0, 1.0),
}
}
fn with_invariants(invariants: &str) -> CountryConfig {
let json = format!(
r#"{{
"code": "us", "name": "United States",
"unit": {{"one": "county", "many": "counties"}},
"parent": {{"one": "state", "many": "states"}},
"bounds": [-170.0, 18.0, -66.0, 72.0],
"boundaries": {{"source": "overture", "release": "2026-01-01.0",
"attribution": "x", "licence_id": "CC0-1.0", "level": "county",
"invariants": {invariants}}}
}}"#
);
CountryConfig::from_json_str(&json).expect("config parses")
}
#[test]
fn the_invariants_fail_naming_the_difference() {
let config = with_invariants(r#"{"areas": 4}"#);
let areas = vec![
area("a", Some("s1")),
area("b", Some("s1")),
area("c", Some("s2")),
];
let err = config
.check_counts(&areas)
.expect_err("3 areas, 4 expected");
assert!(
format!("{err:#}").contains("expected 4 areas, found 3"),
"{err:#}"
);
let config = with_invariants(r#"{"min_areas_per_parent": 2}"#);
let err = config.check_counts(&areas).expect_err("s2 holds one area");
assert!(format!("{err:#}").contains("s2"), "{err:#}");
let config = with_invariants(r#"{"parents": 3}"#);
let err = config
.check_counts(&[area("a", Some("s1")), area("b", None)])
.expect_err("a parentless area and one parent");
assert!(format!("{err:#}").contains("parent"), "{err:#}");
}
#[test]
fn an_official_id_is_a_stable_uuid() {
let id = official_id("us", "06037");
assert_eq!(id, "8d1a0c7e-33b1-3492-ae2e-9c21f98bc708");
assert_eq!(id, official_id("us", "06037"));
assert_ne!(id, official_id("us", "06038"));
assert_ne!(id, official_id("au", "06037"));
let groups: Vec<&str> = id.split('-').collect();
assert_eq!(
groups.iter().map(|g| g.len()).collect::<Vec<_>>(),
vec![8, 4, 4, 4, 12]
);
assert!(
id.chars()
.filter(|c| *c != '-')
.all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()),
"{id} is lowercase hex"
);
assert!(groups[2].starts_with('3'), "version 3: {id}");
assert!(
matches!(groups[3].as_bytes()[0], b'8' | b'9' | b'a' | b'b'),
"variant 10: {id}"
);
}
#[test]
fn a_ring_crossing_the_antimeridian_is_split() {
let input = rect(179.0, -10.0, -179.5, 10.0);
let split = split_antimeridian(&input);
assert_eq!(split.0.len(), 2, "two parts");
let spans: Vec<(f64, f64)> = split
.0
.iter()
.map(|p| {
let xs: Vec<f64> = p.exterior().0.iter().map(|c| c.x).collect();
(
xs.iter().fold(f64::INFINITY, |a, b| a.min(*b)),
xs.iter().fold(f64::NEG_INFINITY, |a, b| a.max(*b)),
)
})
.collect();
assert!(spans.iter().any(|(lo, _)| *lo >= 179.0), "{spans:?}");
assert!(spans.iter().any(|(_, hi)| *hi <= -179.0), "{spans:?}");
assert_eq!(
split,
split_antimeridian(&split),
"a second split is a no-op"
);
let after = split.unsigned_area();
assert!((after - 30.0).abs() < 1e-9, "{after} vs 30.0");
}
#[test]
fn nothing_spans_more_than_180_degrees() {
let split = split_antimeridian(&rect(179.0, -10.0, -179.5, 10.0));
for polygon in &split.0 {
for ring in std::iter::once(polygon.exterior()).chain(polygon.interiors()) {
let xs: Vec<f64> = ring.0.iter().map(|c| c.x).collect();
let lo = xs.iter().fold(f64::INFINITY, |a, b| a.min(*b));
let hi = xs.iter().fold(f64::NEG_INFINITY, |a, b| a.max(*b));
assert!(hi - lo <= 180.0 + 1e-9, "ring spans {lo}..{hi}");
}
}
}
}