garage44.eu/jeroen/cartopolis

logclone: git clone https://garage44.eu/jeroen/cartopolis.git

.. /crates/atlas/src/feeds.rs

raw

//! Data layers: records from a source outside Cartopolis, placed on the map and
//! kept current (`docs/notes/data-layers.md`, `docs/mockups/data-layers/`).
//!
//! A layer is a definition, not code: a source (TripleXL's saved queries
//! first), the column that places a record, the column that titles it, the one
//! its colour follows and the ones its card shows. Operators keep them through
//! `/api/pipeline/feeds`; each is a JSON file under `data_dir/feeds/`.
//!
//! A refresh asks the source, places every record that has a point, bins them
//! into the z14 cells every other tree uses and publishes the cells under a
//! stamped manifest of the layer's own (`crate::stamped`). **Only a cell whose
//! bytes changed gets a new stamp**, so a refresh that finds nothing new costs a
//! client one manifest fetch and no cell fetches. `feeds/index.json` lists every
//! layer that has been published at least once, with what the Layers panel and
//! the card need.

use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use cartopolis_geo::formats::feeds::{self as format, Record, MAX_VALUES};
use serde::{Deserialize, Serialize};

use crate::pipeline::tile::{lat_lng_to_cell, Cell, CACHE_ZOOM};
use crate::stamped;

/// How often the refresh loop looks for a layer that is due.
const TICK: Duration = Duration::from_secs(60);

/// A source answer larger than this is refused rather than read: TripleXL's own
/// largest answer is 16 MB, and a layer that size is not one a phone can draw.
const MAX_ANSWER_BYTES: u64 = 64 * 1024 * 1024;

/// The kinds of source a layer can read. One adapter each.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SourceKind {
    /// A saved query of a TripleXL dataset: `{dataset}/queries/{query}`,
    /// answered as SPARQL JSON without a token when the dataset is public.
    #[default]
    Triplexl,
}

#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Source {
    #[serde(default)]
    pub kind: SourceKind,
    /// The dataset's address, `https://www.triplexl.nl/datasets/{account}/{dataset}`.
    pub dataset: String,
    /// The saved query's name, `stuwen-kaart`.
    pub query: String,
}

/// A layer, as an operator defines it.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Def {
    pub id: String,
    pub name: String,
    /// The publisher it is grouped under in Layers ▸ Data.
    pub group: String,
    pub source: Source,
    /// The column holding the geometry, a GeoSPARQL `wktLiteral`.
    #[serde(default = "default_geometry")]
    pub geometry: String,
    /// The column that titles a record on its card.
    pub title: String,
    /// The column the colours follow; empty for one colour.
    #[serde(default)]
    pub colour_by: String,
    /// The columns the card shows, in order.
    #[serde(default)]
    pub fields: Vec<String>,
    /// The column holding the record's own address; empty for the first
    /// column the source answers as an IRI.
    #[serde(default)]
    pub link: String,
    pub credit: String,
    #[serde(default)]
    pub licence: String,
    /// Ask the source again after this many hours.
    #[serde(default = "default_refresh_hours")]
    pub refresh_hours: u32,
    /// Also ask again as soon as the dataset has a new commit: its revision
    /// is looked at every minute ([`Feeds::moved`]).
    #[serde(default = "default_follow")]
    pub follow: bool,
}

fn default_follow() -> bool {
    true
}

fn default_geometry() -> String {
    "wkt".into()
}

fn default_refresh_hours() -> u32 {
    6
}

impl Def {
    /// Refuse a definition that could not work, before anything is written.
    ///
    /// # Errors
    ///
    /// What is wrong with it, in words for the operator.
    pub fn validate(&self) -> Result<(), String> {
        if !valid_id(&self.id) {
            return Err("An id is 1–40 lower-case letters, digits and dashes.".into());
        }
        if self.name.trim().is_empty() {
            return Err("A layer needs a name.".into());
        }
        if self.title.trim().is_empty() {
            return Err("Say which column titles a record.".into());
        }
        if self.credit.trim().is_empty() {
            return Err("Say whom the data is credited to.".into());
        }
        if !self.source.dataset.starts_with("https://") {
            return Err("The dataset's address starts with https://.".into());
        }
        if self.source.query.is_empty()
            || !self
                .source
                .query
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c))
        {
            return Err("A saved query's name is letters, digits, '-', '_' and '.'.".into());
        }
        if !(1..=24 * 30).contains(&self.refresh_hours) {
            return Err("Refresh every 1 to 720 hours.".into());
        }
        Ok(())
    }

    fn query_url(&self) -> String {
        match self.source.kind {
            SourceKind::Triplexl => format!(
                "{}/queries/{}",
                self.source.dataset.trim_end_matches('/'),
                self.source.query
            ),
        }
    }

    fn via(&self) -> &'static str {
        match self.source.kind {
            SourceKind::Triplexl => "TripleXL",
        }
    }
}

fn valid_id(id: &str) -> bool {
    (1..=40).contains(&id.len())
        && id
            .chars()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
        && !id.starts_with('-')
}

/// What the last refresh of a layer found, kept beside its definition.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct State {
    /// When a refresh last ran, ms since the epoch.
    #[serde(default)]
    pub tried_ms: u64,
    /// When a refresh last succeeded.
    #[serde(default)]
    pub ok_ms: u64,
    /// When the published records last changed.
    #[serde(default)]
    pub changed_ms: u64,
    /// Why the last refresh failed; `None` after a success.
    #[serde(default)]
    pub error: Option<String>,
    /// Rows the source answered.
    #[serde(default)]
    pub rows: u64,
    /// Rows placed on the map.
    #[serde(default)]
    pub placed: u64,
    #[serde(default)]
    pub cells: u64,
    #[serde(default)]
    pub values: Vec<String>,
    /// The dataset's revision the published records were read at, when the
    /// source said.
    #[serde(default)]
    pub source_revision: Option<u64>,
}

/// A layer and its state, as the Admin page lists them.
#[derive(Clone, Debug, Serialize)]
pub struct Listed {
    pub def: Def,
    pub state: State,
}

/// One answer row: column → value, as text.
pub type Row = HashMap<String, Value>;

/// A value as the source typed it.
#[derive(Clone, Debug, PartialEq)]
pub struct Value {
    pub text: String,
    pub iri: bool,
}

/// The records of one refresh, binned by cell.
#[derive(Debug, Default)]
pub struct Built {
    pub cells: BTreeMap<Cell, Vec<Record>>,
    pub values: Vec<String>,
    pub placed: u64,
}

pub struct Feeds {
    defs: PathBuf,
    site: PathBuf,
    /// One refresh or edit at a time: they share the index.
    lock: Mutex<()>,
}

impl Feeds {
    #[must_use]
    pub fn new(data_dir: &Path, site_dir: &Path) -> Self {
        Self {
            defs: data_dir.join("feeds"),
            site: site_dir.join("feeds"),
            lock: Mutex::new(()),
        }
    }

    fn def_path(&self, id: &str) -> PathBuf {
        self.defs.join(format!("{id}.json"))
    }

    fn state_path(&self, id: &str) -> PathBuf {
        self.defs.join(format!("{id}.state.json"))
    }

    #[must_use]
    pub fn get(&self, id: &str) -> Option<Def> {
        if !valid_id(id) {
            return None;
        }
        read_json(&self.def_path(id))
    }

    fn state(&self, id: &str) -> State {
        read_json(&self.state_path(id)).unwrap_or_default()
    }

    /// Every layer, sorted by group and name.
    #[must_use]
    pub fn list(&self) -> Vec<Listed> {
        let mut out: Vec<Listed> = std::fs::read_dir(&self.defs)
            .into_iter()
            .flatten()
            .flatten()
            .filter_map(|e| {
                let name = e.file_name().into_string().ok()?;
                let id = name.strip_suffix(".json")?;
                if id.ends_with(".state") {
                    return None;
                }
                let def = self.get(id)?;
                Some(Listed {
                    state: self.state(id),
                    def,
                })
            })
            .collect();
        out.sort_by(|a, b| (&a.def.group, &a.def.name).cmp(&(&b.def.group, &b.def.name)));
        out
    }

    /// Save a definition. The caller refreshes it after.
    ///
    /// # Errors
    ///
    /// When it does not validate, or the file cannot be written.
    pub fn save(&self, def: &Def) -> Result<(), String> {
        def.validate()?;
        let _guard = self.lock.lock().map_err(|e| e.to_string())?;
        let body = serde_json::to_vec_pretty(def).map_err(|e| e.to_string())?;
        stamped::write_atomic(&self.def_path(&def.id), &body).map_err(|e| e.to_string())
    }

    /// Remove a layer and everything it published. `false` when there was none.
    ///
    /// # Errors
    ///
    /// When a file cannot be removed.
    pub fn remove(&self, id: &str) -> Result<bool, String> {
        if self.get(id).is_none() {
            return Ok(false);
        }
        let _guard = self.lock.lock().map_err(|e| e.to_string())?;
        std::fs::remove_file(self.def_path(id)).map_err(|e| e.to_string())?;
        let _ = std::fs::remove_file(self.state_path(id));
        // The index first, so no client is sent to a tree that is going.
        self.write_index()?;
        match std::fs::remove_dir_all(self.site.join(id)) {
            Ok(()) => Ok(true),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(true),
            Err(e) => Err(e.to_string()),
        }
    }

    /// Ask the source and publish what changed.
    ///
    /// # Errors
    ///
    /// When there is no such layer, the source cannot be read, or the tree
    /// cannot be written; the error is also kept in the layer's state.
    pub fn refresh(&self, id: &str) -> Result<State, String> {
        let def = self.get(id).ok_or("There is no such layer.")?;
        // The revision first: a commit landing between the two is then seen
        // as new on the next look, rather than taken as already read.
        let revision = source_revision(&def.source.dataset).ok();
        let fetched = fetch(&def);
        let mut state = self.publish(&def, fetched)?;
        if revision.is_some() {
            let _guard = self.lock.lock().map_err(|e| e.to_string())?;
            state.source_revision = revision;
            self.keep_state(&def.id, &state)?;
        }
        Ok(state)
    }

    /// The layers that follow their source and whose dataset has moved past
    /// the revision they were read at: one small request per dataset.
    fn moved(&self, now_ms: u64) -> Vec<String> {
        let mut by_dataset: BTreeMap<String, Vec<Listed>> = BTreeMap::new();
        for l in self.list() {
            let every = u64::from(l.def.refresh_hours) * 3_600_000;
            // A source that failed is not asked again every minute.
            let resting =
                l.state.error.is_some() && now_ms.saturating_sub(l.state.tried_ms) < every / 10;
            if l.def.follow && !resting {
                by_dataset
                    .entry(l.def.source.dataset.clone())
                    .or_default()
                    .push(l);
            }
        }
        let mut out = Vec::new();
        for (dataset, layers) in by_dataset {
            match source_revision(&dataset) {
                Ok(r) => out.extend(
                    layers
                        .into_iter()
                        .filter(|l| l.state.source_revision != Some(r))
                        .map(|l| l.def.id),
                ),
                Err(error) => {
                    tracing::debug!(%dataset, %error, "could not read a dataset's revision")
                }
            }
        }
        out
    }

    /// Publish one source answer (or its failure) for `def`.
    ///
    /// # Errors
    ///
    /// As [`Self::refresh`].
    pub fn publish(&self, def: &Def, fetched: Result<Vec<Row>, String>) -> Result<State, String> {
        let _guard = self.lock.lock().map_err(|e| e.to_string())?;
        let mut state = self.state(&def.id);
        state.tried_ms = stamped::now_ms();
        let result = fetched.and_then(|rows| {
            let built = build(def, &rows);
            let changed = self.write_cells(def, &built)?;
            Ok((rows.len(), built, changed))
        });
        match result {
            Ok((rows, built, changed)) => {
                if changed || built.values != state.values || state.changed_ms == 0 {
                    state.changed_ms = state.tried_ms;
                }
                state.ok_ms = state.tried_ms;
                state.error = None;
                state.rows = rows as u64;
                state.placed = built.placed;
                state.cells = built.cells.len() as u64;
                state.values = built.values;
                self.keep_state(&def.id, &state)?;
                self.write_index()?;
                Ok(state)
            }
            Err(e) => {
                state.error = Some(e.clone());
                self.keep_state(&def.id, &state)?;
                Err(e)
            }
        }
    }

    fn keep_state(&self, id: &str, state: &State) -> Result<(), String> {
        let body = serde_json::to_vec_pretty(state).map_err(|e| e.to_string())?;
        stamped::write_atomic(&self.state_path(id), &body).map_err(|e| e.to_string())
    }

    /// Write the cells whose bytes changed and drop the ones left empty; `true`
    /// when anything did.
    fn write_cells(&self, def: &Def, built: &Built) -> Result<bool, String> {
        let root = self.site.join(&def.id);
        let manifest = root.join("coverage.json");
        let before = stamped::read_cells(&manifest);
        let mut after = BTreeMap::new();
        let mut changed = false;
        let now = stamped::now_ms();
        for (&cell, records) in &built.cells {
            let path = root.join(crate::pipeline::tile::cell_path("", cell));
            let body = cartopolis_geo::formats::to_vec(&format::Cell {
                records: records.clone(),
            })
            .map_err(|e| e.to_string())?;
            let was = before.get(&cell).copied();
            let same = was.is_some() && std::fs::read(&path).is_ok_and(|b| b == body);
            if same {
                after.insert(cell, was.unwrap_or(0));
            } else {
                stamped::write_served(&path, &body).map_err(|e| e.to_string())?;
                after.insert(cell, now.max(was.unwrap_or(0) + 1));
                changed = true;
            }
        }
        for &cell in before.keys() {
            if !after.contains_key(&cell) {
                let path = root.join(crate::pipeline::tile::cell_path("", cell));
                stamped::remove_served(&path).map_err(|e| e.to_string())?;
                changed = true;
            }
        }
        if changed || !manifest.exists() {
            let mut extra = serde_json::Map::new();
            extra.insert("attribution".into(), def.credit.clone().into());
            stamped::write_manifest(&manifest, CACHE_ZOOM, &after, extra)
                .map_err(|e| e.to_string())?;
        }
        Ok(changed)
    }

    /// Rewrite `feeds/index.json` from every layer that has published.
    fn write_index(&self) -> Result<(), String> {
        let feeds = self
            .list()
            .into_iter()
            .filter(|l| l.state.ok_ms > 0)
            .map(|Listed { def, state }| format::Feed {
                changed_ms: state.changed_ms,
                colour_by: def.colour_by.clone(),
                credit: def.credit.clone(),
                fields: def.fields.clone(),
                group: def.group.clone(),
                licence: def.licence.clone(),
                name: def.name.clone(),
                records: state.placed,
                values: state.values,
                via: def.via().into(),
                id: def.id,
            })
            .collect();
        let body =
            cartopolis_geo::formats::to_vec(&format::Index { feeds }).map_err(|e| e.to_string())?;
        stamped::write_served(&self.site.join("index.json"), &body).map_err(|e| e.to_string())
    }

    /// The layers whose refresh is due.
    fn due(&self, now_ms: u64) -> Vec<String> {
        self.list()
            .into_iter()
            .filter(|l| {
                let every = u64::from(l.def.refresh_hours) * 3_600_000;
                // A failed try waits a tenth of the interval, not all of it.
                let wait = if l.state.error.is_some() {
                    every / 10
                } else {
                    every
                };
                now_ms.saturating_sub(l.state.tried_ms) >= wait
            })
            .map(|l| l.def.id)
            .collect()
    }

    /// Refresh every layer as it comes due, for as long as the process runs.
    pub fn spawn_refresh(self: &Arc<Self>) {
        let feeds = self.clone();
        tokio::spawn(async move {
            loop {
                let f = feeds.clone();
                let due = tokio::task::spawn_blocking(move || {
                    let now = stamped::now_ms();
                    let mut ids = f.due(now);
                    for id in f.moved(now) {
                        if !ids.contains(&id) {
                            ids.push(id);
                        }
                    }
                    ids
                })
                .await
                .unwrap_or_default();
                for id in due {
                    let f = feeds.clone();
                    let i = id.clone();
                    match tokio::task::spawn_blocking(move || f.refresh(&i)).await {
                        Ok(Ok(s)) => {
                            tracing::info!(feed = %id, rows = s.rows, placed = s.placed, cells = s.cells, "data layer refreshed");
                        }
                        Ok(Err(error)) => {
                            tracing::warn!(feed = %id, %error, "data layer refresh failed; keeping the last copy");
                        }
                        Err(error) => {
                            tracing::warn!(feed = %id, %error, "data layer refresh panicked")
                        }
                    }
                }
                tokio::time::sleep(TICK).await;
            }
        });
    }
}

fn read_json<T: serde::de::DeserializeOwned>(path: &Path) -> Option<T> {
    std::fs::read(path)
        .ok()
        .and_then(|b| serde_json::from_slice(&b).ok())
}

/// One GET to a source, its body capped at [`MAX_ANSWER_BYTES`].
fn get(url: &str, accept: &str) -> Result<Vec<u8>, String> {
    let agent = ureq::AgentBuilder::new()
        .user_agent("cartopolis-atlas (+https://cartopolis.org)")
        .timeout(Duration::from_secs(120))
        .build();
    let resp = agent
        .get(url)
        .set("Accept", accept)
        .call()
        .map_err(|e| format!("{url}: {e}"))?;
    let mut body = Vec::new();
    std::io::Read::read_to_end(
        &mut std::io::Read::take(resp.into_reader(), MAX_ANSWER_BYTES + 1),
        &mut body,
    )
    .map_err(|e| e.to_string())?;
    if body.len() as u64 > MAX_ANSWER_BYTES {
        return Err(format!(
            "{url}: the answer is over {} MB",
            MAX_ANSWER_BYTES >> 20
        ));
    }
    Ok(body)
}

/// Ask the source for every row.
fn fetch(def: &Def) -> Result<Vec<Row>, String> {
    parse_sparql_json(&get(&def.query_url(), "application/sparql-results+json")?)
}

/// A TripleXL dataset as the Admin page offers it: who publishes it, under
/// which licence, and its saved queries, the ones meant as maps first.
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
pub struct Inspected {
    /// The dataset's address, as a layer's `source.dataset` takes it.
    pub dataset: String,
    pub name: String,
    pub publisher: String,
    pub licence: String,
    pub statements: u64,
    pub queries: Vec<SavedQuery>,
}

#[derive(Clone, Debug, Default, PartialEq, Serialize)]
pub struct SavedQuery {
    pub name: String,
    pub description: String,
    /// TripleXL marked it as a map (`view.kind = "map"`).
    pub map: bool,
    /// The column its colours follow, when it names one.
    pub colour: String,
    /// It asks for a value, so it cannot be a layer by itself.
    pub parameters: usize,
}

/// The dataset behind an address an operator pasted: the dataset's own, or
/// one of its pages or queries (`…/datasets/{account}/{dataset}/…`).
///
/// # Errors
///
/// When it is not a TripleXL dataset address.
pub fn dataset_of(url: &str) -> Result<String, String> {
    let url = url.trim();
    let rest = url
        .strip_prefix("https://")
        .ok_or("A dataset's address starts with https://.")?;
    let (host, path) = rest
        .split_once('/')
        .ok_or("That address names no dataset.")?;
    let parts: Vec<&str> = path.split('/').filter(|p| !p.is_empty()).collect();
    match parts.as_slice() {
        ["datasets", account, dataset, ..]
            if [account, dataset].iter().all(|p| {
                p.chars()
                    .all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c))
            }) =>
        {
            Ok(format!("https://{host}/datasets/{account}/{dataset}"))
        }
        _ => Err("Paste a dataset's address: https://…/datasets/{account}/{dataset}.".into()),
    }
}

/// A TripleXL dataset's current revision: it moves with every commit.
fn source_revision(dataset: &str) -> Result<u64, String> {
    let about: serde_json::Value =
        serde_json::from_slice(&get(dataset, "application/json")?).map_err(|e| e.to_string())?;
    about["revision"]
        .as_u64()
        .ok_or_else(|| format!("{dataset}: no revision"))
}

/// "CC-BY-4.0" as people write it.
fn licence_words(id: &str) -> String {
    if id.to_ascii_uppercase().starts_with("CC") {
        id.replace('-', " ")
    } else {
        id.to_string()
    }
}

/// Read a dataset's description and its saved queries.
///
/// # Errors
///
/// When the address is not a dataset's, or the source does not answer.
pub fn inspect(url: &str) -> Result<Inspected, String> {
    let dataset = dataset_of(url)?;
    let about: serde_json::Value = serde_json::from_slice(&get(&dataset, "application/json")?)
        .map_err(|e| format!("{dataset}: {e}"))?;
    let queries: serde_json::Value =
        serde_json::from_slice(&get(&format!("{dataset}/queries"), "application/json")?)
            .map_err(|e| format!("{dataset}/queries: {e}"))?;
    Ok(read_inspected(dataset, &about, &queries))
}

fn read_inspected(
    dataset: String,
    about: &serde_json::Value,
    queries: &serde_json::Value,
) -> Inspected {
    let text = |v: &serde_json::Value| v.as_str().unwrap_or_default().to_string();
    let mut list: Vec<SavedQuery> = queries
        .as_array()
        .into_iter()
        .flatten()
        .map(|q| SavedQuery {
            name: text(&q["name"]),
            description: text(&q["description"]),
            map: q["view"]["kind"] == "map",
            colour: text(&q["view"]["colour"]),
            parameters: q["parameters"].as_array().map_or(0, Vec::len),
        })
        .filter(|q| !q.name.is_empty())
        .collect();
    list.sort_by(|a, b| b.map.cmp(&a.map).then(a.name.cmp(&b.name)));
    Inspected {
        name: [&about["displayName"], &about["name"]]
            .into_iter()
            .map(text)
            .find(|t| !t.is_empty())
            .unwrap_or_default(),
        publisher: text(&about["publisher"]["name"]),
        licence: licence_words(&text(&about["license"])),
        statements: about["statements"].as_u64().unwrap_or(0),
        queries: list,
        dataset,
    }
}

/// What a layer would draw, before it is saved: the columns the source
/// answers, how many rows have a place, and the places themselves.
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
pub struct Preview {
    pub columns: Vec<String>,
    pub rows: u64,
    pub placed: u64,
    /// The column that looks like the geometry: the first whose values are
    /// WKT points.
    pub geometry: String,
    /// The colour column's values, most common first, when one is given.
    pub values: Vec<String>,
    /// `[lat, lng, value]`, at most [`PREVIEW_POINTS`] of them.
    pub points: Vec<(f64, f64, i64)>,
    /// A few rows as they would show on a card: column → value.
    pub sample: Vec<BTreeMap<String, String>>,
}

/// Points sent back for the preview map; an even sample past it.
pub const PREVIEW_POINTS: usize = 3_000;

/// Ask the source and say what a layer over it would draw.
///
/// # Errors
///
/// When the source does not answer.
pub fn preview(source: &Source, geometry: &str, colour_by: &str) -> Result<Preview, String> {
    let def = Def {
        id: "preview".into(),
        name: "preview".into(),
        title: "preview".into(),
        credit: "preview".into(),
        refresh_hours: 1,
        source: source.clone(),
        ..Def::default()
    };
    // The same checks a saved layer passes: an operator's text goes into a URL.
    def.validate()?;
    Ok(preview_of(&fetch(&def)?, geometry, colour_by))
}

fn preview_of(rows: &[Row], geometry: &str, colour_by: &str) -> Preview {
    let mut columns: Vec<String> = rows
        .iter()
        .take(200)
        .flat_map(|r| r.keys().cloned())
        .collect::<std::collections::BTreeSet<_>>()
        .into_iter()
        .collect();
    columns.sort();
    let geometry = if geometry.is_empty() {
        columns
            .iter()
            .find(|c| {
                rows.iter()
                    .take(50)
                    .any(|r| r.get(*c).is_some_and(|v| place(&v.text).is_some()))
            })
            .cloned()
            .unwrap_or_default()
    } else {
        geometry.to_string()
    };
    let def = Def {
        geometry: geometry.clone(),
        colour_by: colour_by.to_string(),
        title: geometry.clone(),
        ..Def::default()
    };
    let built = build(&def, rows);
    let all: Vec<(f64, f64, i64)> = built
        .cells
        .values()
        .flatten()
        .map(|r| (r.0, r.1, r.3))
        .collect();
    let step = all.len().div_ceil(PREVIEW_POINTS).max(1);
    Preview {
        rows: rows.len() as u64,
        placed: built.placed,
        values: built.values,
        points: all.into_iter().step_by(step).collect(),
        sample: rows
            .iter()
            .take(3)
            .map(|r| {
                r.iter()
                    .filter(|(k, _)| **k != geometry)
                    .map(|(k, v)| (k.clone(), v.text.chars().take(120).collect()))
                    .collect()
            })
            .collect(),
        columns,
        geometry,
    }
}

/// A SPARQL 1.1 JSON result set, as rows of text.
///
/// # Errors
///
/// When it is not one.
pub fn parse_sparql_json(body: &[u8]) -> Result<Vec<Row>, String> {
    #[derive(Deserialize)]
    struct Answer {
        results: Results,
    }
    #[derive(Deserialize)]
    struct Results {
        bindings: Vec<HashMap<String, Term>>,
    }
    #[derive(Deserialize)]
    struct Term {
        #[serde(rename = "type")]
        kind: String,
        value: String,
    }
    let answer: Answer =
        serde_json::from_slice(body).map_err(|e| format!("not a SPARQL result set: {e}"))?;
    Ok(answer
        .results
        .bindings
        .into_iter()
        .map(|b| {
            b.into_iter()
                .map(|(k, t)| {
                    (
                        k,
                        Value {
                            iri: t.kind == "uri",
                            text: t.value,
                        },
                    )
                })
                .collect()
        })
        .collect())
}

/// Where a GeoSPARQL `wktLiteral` stands, as `(lat, lng)`, when it is a point.
///
/// The CRS is the IRI in front, as GeoSPARQL writes it: none or CRS84 is
/// longitude first, EPSG 4326 latitude first, EPSG 28992 RD metres.
#[must_use]
pub fn place(wkt: &str) -> Option<(f64, f64)> {
    let wkt = wkt.trim();
    let (crs, shape) = match wkt.strip_prefix('<') {
        Some(rest) => {
            let end = rest.find('>')?;
            (&rest[..end], rest[end + 1..].trim())
        }
        None => ("", wkt),
    };
    let upper = shape.to_ascii_uppercase();
    let inner = upper
        .strip_prefix("POINT")?
        .trim()
        .trim_start_matches('Z')
        .trim();
    let inner = inner.strip_prefix('(')?.strip_suffix(')')?;
    let mut numbers = inner.split_whitespace().map(str::parse::<f64>);
    let a = numbers.next()?.ok()?;
    let b = numbers.next()?.ok()?;
    let (lat, lng) = if crs.ends_with("/28992") {
        crate::pipeline::rd::rd_to_lat_lng(a, b)
    } else if crs.ends_with("/4326") {
        (a, b)
    } else {
        (b, a)
    };
    ((-90.0..=90.0).contains(&lat) && (-180.0..=180.0).contains(&lng)).then_some((lat, lng))
}

/// Round to a tenth of a metre: enough to stand a marker on, and a coordinate
/// that does not wobble in its last digits from one answer to the next.
fn round6(v: f64) -> f64 {
    (v * 1e6).round() / 1e6
}

/// Place, colour and bin every row.
#[must_use]
pub fn build(def: &Def, rows: &[Row]) -> Built {
    let values = if def.colour_by.is_empty() {
        Vec::new()
    } else {
        let mut counts: HashMap<&str, usize> = HashMap::new();
        for row in rows {
            if let Some(v) = row.get(&def.colour_by) {
                *counts.entry(v.text.as_str()).or_default() += 1;
            }
        }
        let mut ranked: Vec<(&str, usize)> = counts.into_iter().collect();
        ranked.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
        ranked
            .into_iter()
            .take(MAX_VALUES)
            .map(|(v, _)| v.to_string())
            .collect::<Vec<_>>()
    };
    let link_column = if def.link.is_empty() {
        // The first column (by name, so it is the same every time) that the
        // source answered as an IRI.
        rows.first().and_then(|r| {
            let mut iris: Vec<&String> = r.iter().filter(|(_, v)| v.iri).map(|(k, _)| k).collect();
            iris.sort();
            iris.first().map(|k| (*k).clone())
        })
    } else {
        Some(def.link.clone())
    };
    let mut built = Built {
        values,
        ..Built::default()
    };
    for row in rows {
        let Some((lat, lng)) = row.get(&def.geometry).and_then(|v| place(&v.text)) else {
            continue;
        };
        let text = |column: &str| row.get(column).map(|v| v.text.clone()).unwrap_or_default();
        let value = if def.colour_by.is_empty() {
            -1
        } else {
            let v = text(&def.colour_by);
            built
                .values
                .iter()
                .position(|x| *x == v)
                .unwrap_or(MAX_VALUES) as i64
        };
        let mut title = text(&def.title);
        if title.is_empty() {
            // A record with no name is still a record; its first field names it.
            title = def.fields.first().map(|f| text(f)).unwrap_or_default();
        }
        let record: Record = (
            round6(lat),
            round6(lng),
            title,
            value,
            def.fields.iter().map(|f| text(f)).collect(),
            link_column.as_deref().map(text).unwrap_or_default(),
        );
        built
            .cells
            .entry(lat_lng_to_cell(lat, lng))
            .or_default()
            .push(record);
        built.placed += 1;
    }
    // The order the source answered in is not promised; the bytes must be.
    for records in built.cells.values_mut() {
        records.sort_by(|a, b| {
            (&a.2, &a.5)
                .cmp(&(&b.2, &b.5))
                .then(a.0.total_cmp(&b.0))
                .then(a.1.total_cmp(&b.1))
        });
    }
    built
}

#[cfg(test)]
mod tests {
    use super::*;

    const ANSWER: &str = r#"{"head":{"vars":["stuw","code","naam","soort","wkt"]},"results":{"bindings":[
      {"stuw":{"type":"uri","value":"https://www.triplexl.nl/id/noorderzijlvest/stuw/KST6211"},
       "code":{"type":"literal","value":"KST6211"},"naam":{"type":"literal","value":"Hoge Noorderplantsoenstuw"},
       "soort":{"type":"literal","value":"overlaat"},
       "wkt":{"type":"literal","value":"<http://www.opengis.net/def/crs/EPSG/0/28992> POINT(233337.2 582870.6)","datatype":"http://www.opengis.net/ont/geosparql#wktLiteral"}},
      {"stuw":{"type":"uri","value":"https://www.triplexl.nl/id/noorderzijlvest/stuw/KST0704"},
       "code":{"type":"literal","value":"KST0704"},"naam":{"type":"literal","value":"Cibogastuw"},
       "soort":{"type":"literal","value":"stuw met klep"},
       "wkt":{"type":"literal","value":"<http://www.opengis.net/def/crs/EPSG/0/28992> POINT(235300.0 582400.0)"}},
      {"stuw":{"type":"uri","value":"https://www.triplexl.nl/id/noorderzijlvest/stuw/KST9999"},
       "code":{"type":"literal","value":"KST9999"},"naam":{"type":"literal","value":"Zonder plek"},
       "soort":{"type":"literal","value":"overlaat"}}
    ]}}"#;

    fn def() -> Def {
        Def {
            id: "nzv-stuwen".into(),
            name: "Stuwen".into(),
            group: "Waterschap Noorderzijlvest".into(),
            source: Source {
                kind: SourceKind::Triplexl,
                dataset: "https://www.triplexl.nl/datasets/archixl/noorderzijlvest".into(),
                query: "stuwen-kaart".into(),
            },
            geometry: "wkt".into(),
            title: "naam".into(),
            colour_by: "soort".into(),
            fields: vec!["code".into(), "soort".into()],
            link: String::new(),
            credit: "Waterschap Noorderzijlvest open data".into(),
            licence: "CC BY 4.0".into(),
            refresh_hours: 6,
            follow: true,
        }
    }

    #[test]
    fn a_wkt_point_is_placed_in_its_own_crs() {
        // RD: the Martinitoren.
        let (lat, lng) =
            place("<http://www.opengis.net/def/crs/EPSG/0/28992> POINT(233883 582065)").unwrap();
        assert!(
            (lat - 53.2193).abs() < 0.001 && (lng - 6.5682).abs() < 0.001,
            "{lat} {lng}"
        );
        // CRS84 (and no IRI) is longitude first; EPSG 4326 latitude first.
        assert_eq!(place("POINT(6.5 53.2)"), Some((53.2, 6.5)));
        assert_eq!(
            place("<http://www.opengis.net/def/crs/OGC/1.3/CRS84> Point(6.5 53.2)"),
            Some((53.2, 6.5))
        );
        assert_eq!(
            place("<http://www.opengis.net/def/crs/EPSG/0/4326> POINT(53.2 6.5)"),
            Some((53.2, 6.5))
        );
        assert_eq!(place("POINT Z (6.5 53.2 1.0)"), Some((53.2, 6.5)));
        assert_eq!(place("LINESTRING(6.5 53.2, 6.6 53.3)"), None);
        assert_eq!(place("POINT(999 999)"), None);
    }

    #[test]
    fn rows_are_coloured_by_frequency_and_binned() {
        let rows = parse_sparql_json(ANSWER.as_bytes()).unwrap();
        let built = build(&def(), &rows);
        assert_eq!(built.placed, 2, "the row with no place is left out");
        assert_eq!(built.values, vec!["overlaat", "stuw met klep"]);
        let all: Vec<&Record> = built.cells.values().flatten().collect();
        let hoge = all
            .iter()
            .find(|r| r.2 == "Hoge Noorderplantsoenstuw")
            .unwrap();
        assert_eq!(hoge.3, 0);
        assert_eq!(hoge.4, vec!["KST6211", "overlaat"]);
        assert_eq!(
            hoge.5,
            "https://www.triplexl.nl/id/noorderzijlvest/stuw/KST6211"
        );
    }

    #[test]
    fn an_unchanged_answer_restamps_nothing_and_a_change_restamps_its_cell() {
        let dir = tempfile::tempdir().unwrap();
        let feeds = Feeds::new(&dir.path().join("data"), &dir.path().join("site"));
        feeds.save(&def()).unwrap();
        let rows = parse_sparql_json(ANSWER.as_bytes()).unwrap();
        let first = feeds.publish(&def(), Ok(rows.clone())).unwrap();
        assert_eq!((first.rows, first.placed), (3, 2));
        let manifest = dir.path().join("site/feeds/nzv-stuwen/coverage.json");
        let stamps = stamped::read_cells(&manifest);
        assert!(!stamps.is_empty());
        let index = format::parse_index(
            &std::fs::read_to_string(dir.path().join("site/feeds/index.json")).unwrap(),
        )
        .unwrap();
        assert_eq!(index.feeds[0].records, 2);
        assert_eq!(index.feeds[0].via, "TripleXL");

        let again = feeds.publish(&def(), Ok(rows.clone())).unwrap();
        assert_eq!(again.changed_ms, first.changed_ms);
        assert_eq!(stamped::read_cells(&manifest), stamps);

        let mut moved = rows;
        moved[1].get_mut("naam").unwrap().text = "Cibogastuw (nieuw)".into();
        std::thread::sleep(Duration::from_millis(2));
        feeds.publish(&def(), Ok(moved)).unwrap();
        let after = stamped::read_cells(&manifest);
        let restamped = after
            .iter()
            .filter(|(c, s)| stamps.get(c) != Some(s))
            .count();
        assert_eq!(restamped, 1, "only the cell whose record changed");
    }

    #[test]
    fn a_failed_refresh_keeps_the_last_copy() {
        let dir = tempfile::tempdir().unwrap();
        let feeds = Feeds::new(&dir.path().join("data"), &dir.path().join("site"));
        feeds.save(&def()).unwrap();
        let rows = parse_sparql_json(ANSWER.as_bytes()).unwrap();
        feeds.publish(&def(), Ok(rows)).unwrap();
        assert!(feeds.publish(&def(), Err("down".into())).is_err());
        let listed = &feeds.list()[0];
        assert_eq!(listed.state.error.as_deref(), Some("down"));
        assert_eq!(listed.state.placed, 2);
        assert!(dir.path().join("site/feeds/index.json").exists());
    }

    #[test]
    fn removing_a_layer_takes_its_tree_and_its_index_entry() {
        let dir = tempfile::tempdir().unwrap();
        let feeds = Feeds::new(&dir.path().join("data"), &dir.path().join("site"));
        feeds.save(&def()).unwrap();
        feeds
            .publish(&def(), Ok(parse_sparql_json(ANSWER.as_bytes()).unwrap()))
            .unwrap();
        assert!(feeds.remove("nzv-stuwen").unwrap());
        assert!(!dir.path().join("site/feeds/nzv-stuwen").exists());
        let index = std::fs::read_to_string(dir.path().join("site/feeds/index.json")).unwrap();
        assert_eq!(index, r#"{"feeds":[]}"#);
        assert!(!feeds.remove("nzv-stuwen").unwrap());
    }

    #[test]
    fn a_pasted_address_finds_its_dataset() {
        let d = "https://www.triplexl.nl/datasets/archixl/noorderzijlvest";
        assert_eq!(dataset_of(d).unwrap(), d);
        assert_eq!(dataset_of(&format!("{d}/queries/stuwen-kaart")).unwrap(), d);
        assert_eq!(dataset_of(&format!(" {d}/ ")).unwrap(), d);
        assert!(dataset_of("https://www.triplexl.nl/console/").is_err());
        assert!(dataset_of("http://www.triplexl.nl/datasets/a/b").is_err());
    }

    #[test]
    fn a_dataset_offers_its_maps_first() {
        let about = serde_json::json!({
            "displayName": "Waterschap Noorderzijlvest open data",
            "license": "CC-BY-4.0",
            "publisher": {"name": "Waterschap Noorderzijlvest"},
            "statements": 4_144_625
        });
        let queries = serde_json::json!([
            {"name": "bruggen-aantal", "description": "Het aantal bruggen", "parameters": [], "view": null},
            {"name": "stuwen-kaart", "description": "De stuwen op de kaart", "parameters": [], "view": {"kind": "map"}},
            {"name": "stuwen-zoeken", "description": "Stuwen zoeken", "parameters": [{"name": "q"}], "view": {"kind": "map", "colour": "soort"}}
        ]);
        let i = read_inspected("https://x/datasets/a/b".into(), &about, &queries);
        assert_eq!(i.licence, "CC BY 4.0");
        assert_eq!(i.publisher, "Waterschap Noorderzijlvest");
        let names: Vec<&str> = i.queries.iter().map(|q| q.name.as_str()).collect();
        assert_eq!(names, ["stuwen-kaart", "stuwen-zoeken", "bruggen-aantal"]);
        assert_eq!(i.queries[1].parameters, 1);
        assert_eq!(i.queries[1].colour, "soort");
    }

    #[test]
    fn a_preview_finds_the_geometry_itself() {
        let rows = parse_sparql_json(ANSWER.as_bytes()).unwrap();
        let p = preview_of(&rows, "", "soort");
        assert_eq!(p.geometry, "wkt");
        assert_eq!((p.rows, p.placed), (3, 2));
        assert_eq!(p.points.len(), 2);
        assert_eq!(p.columns, ["code", "naam", "soort", "stuw", "wkt"]);
        assert!(!p.sample[0].contains_key("wkt"));
    }

    /// Against the real TripleXL: `cargo test -p cartopolis_atlas live_triplexl -- --ignored`.
    #[test]
    #[ignore = "asks www.triplexl.nl"]
    fn live_triplexl() {
        let i = inspect("https://www.triplexl.nl/datasets/archixl/noorderzijlvest/").unwrap();
        assert!(i.queries.iter().any(|q| q.name == "stuwen-kaart" && q.map));
        let p = preview(&def().source, "", "soort").unwrap();
        assert_eq!(p.geometry, "wkt");
        assert!(p.placed > 1000, "{} placed", p.placed);
        let dir = tempfile::tempdir().unwrap();
        let feeds = Feeds::new(&dir.path().join("data"), &dir.path().join("site"));
        feeds.save(&def()).unwrap();
        let s = feeds.refresh("nzv-stuwen").unwrap();
        assert!(
            s.source_revision.is_some(),
            "the dataset's revision is kept"
        );
        assert!(
            feeds.moved(stamped::now_ms()).is_empty(),
            "nothing moved since"
        );
        eprintln!(
            "live: {} rows, {} placed, {} cells, values {:?}",
            s.rows, s.placed, s.cells, s.values
        );
        assert!(s.cells > 10);
    }

    /// Writes a served tree of three real layers into `$FEEDS_SITE`, for a
    /// capture against a stand-in data host:
    /// `FEEDS_SITE=/tmp/site cargo test -p cartopolis_atlas live_stand_in -- --ignored`.
    #[test]
    #[ignore = "asks www.triplexl.nl and writes $FEEDS_SITE"]
    fn live_stand_in() {
        let Some(site) = std::env::var_os("FEEDS_SITE") else {
            return;
        };
        let data = tempfile::tempdir().unwrap();
        let feeds = Feeds::new(data.path(), Path::new(&site));
        let hea = "https://www.triplexl.nl/datasets/archixl/hunzeenaas";
        let layers = [
            def(),
            Def {
                id: "nzv-gemalen".into(),
                name: "Gemalen".into(),
                source: Source {
                    query: "gemalen-kaart".into(),
                    ..def().source
                },
                colour_by: "functie".into(),
                fields: vec!["code".into(), "functie".into(), "capaciteit".into()],
                ..def()
            },
            Def {
                id: "hea-peil".into(),
                name: "Peil bij stuwen".into(),
                group: "Waterschap Hunze en Aa's".into(),
                source: Source {
                    kind: SourceKind::Triplexl,
                    dataset: hea.into(),
                    query: "peil-kaart".into(),
                },
                colour_by: "toestand".into(),
                fields: vec![
                    "peil".into(),
                    "streefpeil".into(),
                    "verschil".into(),
                    "gemeten".into(),
                ],
                credit: "Waterschap Hunze en Aa's open data".into(),
                ..def()
            },
        ];
        for d in &layers {
            feeds.save(d).unwrap();
            let s = feeds.refresh(&d.id).unwrap();
            eprintln!("{}: {} placed in {} cells", d.id, s.placed, s.cells);
        }
    }

    #[test]
    fn a_definition_is_checked_before_it_is_kept() {
        let mut d = def();
        d.id = "Bad Id".into();
        assert!(d.validate().is_err());
        let mut d = def();
        d.source.dataset = "http://insecure".into();
        assert!(d.validate().is_err());
        let mut d = def();
        d.source.query = "../escape".into();
        assert!(d.validate().is_err());
        assert!(def().validate().is_ok());
    }
}