garage44.eu/jeroen/cartopolis

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

cartopolis-agent · 2026-11-30T18:30:07Z

feat(atlas): look up a TripleXL dataset and preview a data layer

Two routes for the Admin page's new-layer form, behind pipeline_run:
POST /api/pipeline/feeds/inspect takes a pasted address, finds the
dataset behind it and lists its saved queries, the ones TripleXL marks
as maps first, with whether one asks for a value; POST .../preview asks
a query and answers its columns, how many rows have a place, the column
that holds the points, the colour column's ranked values and up to 3,000
points for a preview map. The preview passes the same checks a saved
layer does, since an operator's text goes into a URL.

An ignored test (live_triplexl) runs it against www.triplexl.nl: on
2026-11-30 Noorderzijlvest's stuwen-kaart gave 1,578 rows, all placed,
in 450 cells.
crates/atlas/src/api.rs   |  48 ++++++++
 crates/atlas/src/feeds.rs | 284 +++++++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 326 insertions(+), 6 deletions(-)

diff --git a/crates/atlas/src/api.rs b/crates/atlas/src/api.rs
index 9ad6ea72..0a0746f6 100644
--- a/crates/atlas/src/api.rs
+++ b/crates/atlas/src/api.rs
@@ -112,6 +112,8 @@ pub fn router(state: ApiState) -> Router {
         )
         // Data layers (`crate::feeds`, `docs/notes/data-layers.md`).
         .route("/feeds", get(list_feeds))
+        .route("/feeds/inspect", post(inspect_feed_source))
+        .route("/feeds/preview", post(preview_feed))
         .route(
             "/feeds/{id}",
             axum::routing::put(put_feed).delete(delete_feed),
@@ -785,6 +787,52 @@ async fn put_feed(
     }
 }
 
+#[derive(Deserialize)]
+struct InspectBody {
+    url: String,
+}
+
+/// What a pasted address holds: the dataset and its saved queries.
+async fn inspect_feed_source(
+    State(state): State<ApiState>,
+    headers: HeaderMap,
+    Json(body): Json<InspectBody>,
+) -> Response {
+    if let Err(r) = admin(&state, &headers).await {
+        return r;
+    }
+    match blocking(move || crate::feeds::inspect(&body.url)).await {
+        Ok(i) => Json(json!({ "dataset": i })).into_response(),
+        Err(e) => fail(StatusCode::BAD_REQUEST, &e),
+    }
+}
+
+#[derive(Deserialize)]
+struct PreviewBody {
+    source: crate::feeds::Source,
+    #[serde(default)]
+    geometry: String,
+    #[serde(default)]
+    colour_by: String,
+}
+
+/// What a layer would draw, before it is saved.
+async fn preview_feed(
+    State(state): State<ApiState>,
+    headers: HeaderMap,
+    Json(body): Json<PreviewBody>,
+) -> Response {
+    if let Err(r) = admin(&state, &headers).await {
+        return r;
+    }
+    match blocking(move || crate::feeds::preview(&body.source, &body.geometry, &body.colour_by))
+        .await
+    {
+        Ok(p) => Json(json!({ "preview": p })).into_response(),
+        Err(e) => fail(StatusCode::BAD_GATEWAY, &e),
+    }
+}
+
 async fn delete_feed(
     State(state): State<ApiState>,
     headers: HeaderMap,
diff --git a/crates/atlas/src/feeds.rs b/crates/atlas/src/feeds.rs
index 598ad30e..9a086289 100644
--- a/crates/atlas/src/feeds.rs
+++ b/crates/atlas/src/feeds.rs
@@ -473,16 +473,15 @@ fn read_json<T: serde::de::DeserializeOwned>(path: &Path) -> Option<T> {
         .and_then(|b| serde_json::from_slice(&b).ok())
 }
 
-/// Ask the source for every row.
-fn fetch(def: &Def) -> Result<Vec<Row>, String> {
+/// 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 url = def.query_url();
     let resp = agent
-        .get(&url)
-        .set("Accept", "application/sparql-results+json")
+        .get(url)
+        .set("Accept", accept)
         .call()
         .map_err(|e| format!("{url}: {e}"))?;
     let mut body = Vec::new();
@@ -497,7 +496,220 @@ fn fetch(def: &Def) -> Result<Vec<Row>, String> {
             MAX_ANSWER_BYTES >> 20
         ));
     }
-    parse_sparql_json(&body)
+    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()),
+    }
+}
+
+/// "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.
@@ -797,6 +1009,66 @@ mod tests {
         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();
+        eprintln!("live: {} rows, {} placed, {} cells, values {:?}", s.rows, s.placed, s.cells, s.values);
+        assert!(s.cells > 10);
+    }
+
     #[test]
     fn a_definition_is_checked_before_it_is_kept() {
         let mut d = def();