garage44.eu/jeroen/cartopolis

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

cartopolis-agent · 2026-11-30T17:57:02Z

feat(atlas): data layers from TripleXL's saved queries

A layer is a definition kept under data_dir/feeds/: a TripleXL dataset
and saved query, the column that places a record (a GeoSPARQL wktLiteral,
RD or WGS 84), the one that titles it, the one its colour follows and the
ones its card shows. atlas asks the source on the layer's clock (6 h by
default), bins the records into the z14 cells and publishes them under a
stamped manifest of the layer's own; only a cell whose bytes changed gets
a new stamp, so an unchanged answer costs a client one manifest fetch.
feeds/index.json lists every published layer for the Layers panel.

Operators keep layers through /api/pipeline/feeds (list, put, delete,
refresh), behind pipeline_run. The format is cartopolis_geo's
formats::feeds, shared with the client.
crates/atlas/src/api.rs         |  88 +++++
 crates/atlas/src/feeds.rs       | 813 ++++++++++++++++++++++++++++++++++++++++
 crates/atlas/src/http.rs        |   1 +
 crates/atlas/src/lib.rs         |   6 +
 crates/geo/src/formats/feeds.rs | 116 ++++++
 crates/geo/src/formats/mod.rs   |   1 +
 6 files changed, 1025 insertions(+)

diff --git a/crates/atlas/src/api.rs b/crates/atlas/src/api.rs
index fe1004aa..9ad6ea72 100644
--- a/crates/atlas/src/api.rs
+++ b/crates/atlas/src/api.rs
@@ -35,6 +35,8 @@ pub struct ApiState {
     pub overrides: Arc<crate::overrides::Overrides>,
     /// Facades measured again on a player's word (`crate::facade_edits`).
     pub facade_edits: Arc<crate::facade_edits::FacadeEdits>,
+    /// Data layers (`crate::feeds`).
+    pub feeds: Arc<crate::feeds::Feeds>,
 }
 
 fn fail(status: StatusCode, message: &str) -> Response {
@@ -108,6 +110,13 @@ pub fn router(state: ApiState) -> Router {
                 cartopolis_core::model_limits::MAX_ASSET_BYTES + 1024,
             )),
         )
+        // Data layers (`crate::feeds`, `docs/notes/data-layers.md`).
+        .route("/feeds", get(list_feeds))
+        .route(
+            "/feeds/{id}",
+            axum::routing::put(put_feed).delete(delete_feed),
+        )
+        .route("/feeds/{id}/refresh", post(refresh_feed))
         .fallback(|| async { fail(StatusCode::NOT_FOUND, "No such endpoint") })
         .with_state(state)
 }
@@ -734,6 +743,84 @@ async fn delete_override(
     }
 }
 
+async fn list_feeds(State(state): State<ApiState>, headers: HeaderMap) -> Response {
+    if let Err(r) = admin(&state, &headers).await {
+        return r;
+    }
+    let feeds = state.feeds.clone();
+    let all = blocking(move || feeds.list()).await;
+    Json(json!({ "feeds": all })).into_response()
+}
+
+/// Save a layer and refresh it at once, so the answer says what the source
+/// gave. A source that fails keeps the definition: it is tried again on the
+/// layer's clock, and the answer carries the error.
+async fn put_feed(
+    State(state): State<ApiState>,
+    headers: HeaderMap,
+    Path(id): Path<String>,
+    Json(def): Json<crate::feeds::Def>,
+) -> Response {
+    let who = match admin(&state, &headers).await {
+        Ok(w) => w,
+        Err(r) => return r,
+    };
+    if def.id != id {
+        return fail(StatusCode::BAD_REQUEST, "The id in the body is not the one in the path");
+    }
+    let feeds = state.feeds.clone();
+    let result = blocking(move || {
+        feeds.save(&def)?;
+        Ok::<_, String>(feeds.refresh(&def.id))
+    })
+    .await;
+    match result {
+        Ok(refreshed) => {
+            tracing::info!(feed = %id, by = %who.username, ok = refreshed.is_ok(), "data layer saved");
+            let feeds = state.feeds.clone();
+            let listed = blocking(move || feeds.list().into_iter().find(|l| l.def.id == id)).await;
+            Json(json!({ "feed": listed, "error": refreshed.err() })).into_response()
+        }
+        Err(e) => fail(StatusCode::BAD_REQUEST, &e),
+    }
+}
+
+async fn delete_feed(
+    State(state): State<ApiState>,
+    headers: HeaderMap,
+    Path(id): Path<String>,
+) -> Response {
+    let who = match admin(&state, &headers).await {
+        Ok(w) => w,
+        Err(r) => return r,
+    };
+    let feeds = state.feeds.clone();
+    let i = id.clone();
+    match blocking(move || feeds.remove(&i)).await {
+        Ok(true) => {
+            tracing::info!(feed = %id, by = %who.username, "data layer deleted");
+            StatusCode::NO_CONTENT.into_response()
+        }
+        Ok(false) => fail(StatusCode::NOT_FOUND, "There is no such layer"),
+        Err(e) => fail(StatusCode::INTERNAL_SERVER_ERROR, &e),
+    }
+}
+
+async fn refresh_feed(
+    State(state): State<ApiState>,
+    headers: HeaderMap,
+    Path(id): Path<String>,
+) -> Response {
+    if let Err(r) = admin(&state, &headers).await {
+        return r;
+    }
+    let feeds = state.feeds.clone();
+    match blocking(move || feeds.refresh(&id)).await {
+        Ok(s) => Json(json!({ "state": s })).into_response(),
+        Err(e) => fail(StatusCode::BAD_GATEWAY, &e),
+    }
+}
+
 fn valid_name(name: &str) -> bool {
     let mut chars = name.chars();
     name.len() <= 40
@@ -910,6 +997,7 @@ mod tests {
                 &dir.path().join("data"),
                 &site,
             )),
+            feeds: Arc::new(crate::feeds::Feeds::new(&dir.path().join("data"), &site)),
         };
         let app = Router::new().nest("/api/pipeline", router(state));
         let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
diff --git a/crates/atlas/src/feeds.rs b/crates/atlas/src/feeds.rs
new file mode 100644
index 00000000..598ad30e
--- /dev/null
+++ b/crates/atlas/src/feeds.rs
@@ -0,0 +1,813 @@
+//! 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,
+}
+
+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>,
+}
+
+/// 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.")?;
+        let fetched = fetch(&def);
+        self.publish(&def, fetched)
+    }
+
+    /// 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 || f.due(stamped::now_ms()))
+                    .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())
+}
+
+/// Ask the source for every row.
+fn fetch(def: &Def) -> Result<Vec<Row>, 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")
+        .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
+        ));
+    }
+    parse_sparql_json(&body)
+}
+
+/// 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(built.values.len()) 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,
+        }
+    }
+
+    #[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_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());
+    }
+}
diff --git a/crates/atlas/src/http.rs b/crates/atlas/src/http.rs
index 3e894076..77c26c7e 100644
--- a/crates/atlas/src/http.rs
+++ b/crates/atlas/src/http.rs
@@ -222,6 +222,7 @@ mod tests {
                     dir.path(),
                     dir.path(),
                 )),
+                feeds: std::sync::Arc::new(crate::feeds::Feeds::new(dir.path(), dir.path())),
             },
             satellites: Arc::new(crate::satellites::SatelliteMirror::new(dir.path(), "")),
             plans: Arc::new(crate::plans::PlansMirror::new(dir.path(), false)),
diff --git a/crates/atlas/src/lib.rs b/crates/atlas/src/lib.rs
index 28e1a892..52b6bfe5 100644
--- a/crates/atlas/src/lib.rs
+++ b/crates/atlas/src/lib.rs
@@ -14,6 +14,7 @@ pub mod countries;
 pub mod coverage;
 pub mod designs;
 pub mod facade_edits;
+pub mod feeds;
 pub mod geocoder;
 pub mod http;
 pub mod jobs;
@@ -64,6 +65,11 @@ pub async fn run(config: config::AtlasConfig) -> anyhow::Result<()> {
             &config.data_dir,
             &config.site_dir,
         )),
+        feeds: {
+            let feeds = Arc::new(feeds::Feeds::new(&config.data_dir, &config.site_dir));
+            feeds.spawn_refresh();
+            feeds
+        },
     };
     let geocoder = {
         let g = Arc::new(geocoder::Geocoder::new(&config.data_dir));
diff --git a/crates/geo/src/formats/feeds.rs b/crates/geo/src/formats/feeds.rs
new file mode 100644
index 00000000..18024ad0
--- /dev/null
+++ b/crates/geo/src/formats/feeds.rs
@@ -0,0 +1,116 @@
+//! `feeds/index.json` and `feeds/{id}/14/{x}/{y}.json` — data layers: records
+//! from a source outside Cartopolis (TripleXL's saved queries first), placed on
+//! the map (`docs/notes/data-layers.md`).
+//!
+//! Written by atlas's `feeds.rs`; read by the client's `systems::feeds`. The
+//! index lists every layer with what its card and key need; a layer's cells sit
+//! under a stamped `coverage.json` of their own (`atlas::stamped`), so a client
+//! refetches only the cells a refresh changed.
+//!
+//! A record's colour is an index into its layer's `values`, not a colour: the
+//! palette is the client's, and a layer that grows an eighth value must not
+//! repaint the seven before it.
+
+use serde::{Deserialize, Serialize};
+
+/// `feeds/index.json`.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+pub struct Index {
+    #[serde(default)]
+    pub feeds: Vec<Feed>,
+}
+
+/// One layer, as the Layers panel, the card and the key need it.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+pub struct Feed {
+    /// When the records last changed, ms since the epoch — not when they were
+    /// last asked for, which changes nothing a reader shows.
+    #[serde(default)]
+    pub changed_ms: u64,
+    /// The column the colours follow, `""` when the layer has one colour.
+    #[serde(default)]
+    pub colour_by: String,
+    /// The credit line, as the source asks for it.
+    #[serde(default)]
+    pub credit: String,
+    /// The columns a record's `fields` hold, in the order the card shows them.
+    #[serde(default)]
+    pub fields: Vec<String>,
+    /// The publisher it is grouped under in Layers ▸ Data.
+    #[serde(default)]
+    pub group: String,
+    pub id: String,
+    #[serde(default)]
+    pub licence: String,
+    pub name: String,
+    /// Records placed on the map, in all cells.
+    #[serde(default)]
+    pub records: u64,
+    /// The values of `colour_by`, most common first, at most
+    /// [`MAX_VALUES`]; a record whose value is not among them has the index
+    /// `values.len()`, "other".
+    #[serde(default)]
+    pub values: Vec<String>,
+    /// Where the data comes from, for "via …" — `"TripleXL"`.
+    #[serde(default)]
+    pub via: String,
+}
+
+/// How many values of a colour column get a colour of their own; the rest are
+/// "other". Eight is what a categorical palette keeps apart at marker size.
+pub const MAX_VALUES: usize = 7;
+
+/// One record: `[lat, lng, title, value, fields, link]`. `value` indexes the
+/// layer's `values` (−1 when it has no colour column); `fields` follow the
+/// layer's `fields`; `link` is the record's own address, `""` when it has none.
+pub type Record = (f64, f64, String, i64, Vec<String>, String);
+
+/// `feeds/{id}/14/{x}/{y}.json`.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+pub struct Cell {
+    #[serde(default)]
+    pub records: Vec<Record>,
+}
+
+/// Parse the index.
+///
+/// # Errors
+///
+/// When the text is not JSON or not this document.
+pub fn parse_index(text: &str) -> Result<Index, String> {
+    super::from_str(text)
+}
+
+/// Parse a cell file.
+///
+/// # Errors
+///
+/// When the text is not JSON or not this document.
+pub fn parse_cell(text: &str) -> Result<Cell, String> {
+    super::from_str(text)
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    const CELL: &str = concat!(
+        r#"{"records":[[53.2229,6.5571,"Hoge Noorderplantsoenstuw",0,"#,
+        r#"["KST6211","overlaat"],"https://www.triplexl.nl/id/noorderzijlvest/stuw/KST6211"]]}"#
+    );
+
+    #[test]
+    fn a_cell_round_trips_byte_for_byte() {
+        let cell = parse_cell(CELL).unwrap();
+        assert_eq!(cell.records[0].2, "Hoge Noorderplantsoenstuw");
+        assert_eq!(cell.records[0].4, vec!["KST6211", "overlaat"]);
+        assert_eq!(String::from_utf8(super::super::to_vec(&cell).unwrap()).unwrap(), CELL);
+    }
+
+    #[test]
+    fn an_index_from_before_a_field_still_reads() {
+        let index = parse_index(r#"{"feeds":[{"id":"nzv-stuwen","name":"Stuwen"}]}"#).unwrap();
+        assert_eq!(index.feeds[0].name, "Stuwen");
+        assert!(index.feeds[0].values.is_empty());
+    }
+}
diff --git a/crates/geo/src/formats/mod.rs b/crates/geo/src/formats/mod.rs
index c529df67..4c2b9c03 100644
--- a/crates/geo/src/formats/mod.rs
+++ b/crates/geo/src/formats/mod.rs
@@ -35,6 +35,7 @@ pub mod brp;
 pub mod coverage;
 pub mod decks;
 pub mod dikes;
+pub mod feeds;
 pub mod facades;
 pub mod galaxies;
 pub mod lod22;