taxa-server 0.1.0

axum web server for taxa: reproduces the HTTP contract + serves the embedded D3 frontend.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
//! Geo-view layer registry: the typed contract for the sidebar's *Geography*
//! selector, plus serving consumer-provided geo assets from a `--geo-dir`.
//!
//! taxa ships the geo *mechanism*, never domain *data*. The built-in
//! states/counties/countries maps come from generic atlases embedded in
//! `web/vendor/`; sub-county / custom layers (their TopoJSON + per-metric value
//! files + a `registry.json`) are DATA a consumer supplies via `--geo-dir`.
//! The server serves `/static/vendor/geo/*` from that dir, and validates the
//! registry at boot so a hand-edited or freshly built one fails loudly here
//! rather than rendering a silently-broken selector.
//!
//! This `Registry` model is also the parse the `/api/geo` static-layer path
//! (improvement plan 4.2) builds on: one typed view of what a layer is.

use std::path::{Path, PathBuf};

use axum::{
    http::{header, HeaderMap, StatusCode},
    response::{IntoResponse, Response},
};
use serde::Deserialize;

/// Renderers the frontend can actually draw today. A geography asking for any
/// other renderer is greyed out (it can ship later without a registry change).
const SHIPPED_RENDERERS: &[&str] = &["svg"];
/// Built-in map ids the server injects (see `make_app`'s geo view). A `builtin`
/// registry row must name one of these — otherwise its `map` points at nothing.
const BUILTIN_MAPS: &[&str] = &["states", "counties", "countries"];

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Registry {
    pub version: u32,
    pub geographies: Vec<Geography>,
}

/// One row of the Geography selector. `builtin` rows carry `map`; `static` rows
/// carry the geometry/metric module fields. A flat struct (optionals for the
/// kind-specific fields) keeps the (de)serialization trivial; `validate()`
/// enforces the per-kind invariants the loose shape can't.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Geography {
    pub id: String,
    pub label: String,
    pub group: String,
    pub kind: String, // "builtin" | "static"
    #[serde(default)]
    pub us: bool,
    pub available: bool,
    #[serde(default)]
    pub note: String,
    // builtin only:
    #[serde(default)]
    pub map: Option<String>,
    // static only:
    #[serde(default)]
    pub renderer: Option<String>,
    #[serde(default)]
    pub object: Option<String>,
    #[serde(default)]
    pub key_kind: Option<String>,
    #[serde(default)]
    pub features: Option<u64>,
    #[serde(default)]
    pub topojson: Option<String>,
    #[serde(default)]
    pub families: Vec<Family>,
}

/// A metric module: a `<geo>__<family>.json` values file the choropleth paints.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Family {
    pub id: String,
    pub label: String,
    pub file: String,
}

impl Registry {
    /// Parse + validate in one step (the only way a caller should obtain one).
    pub fn parse(bytes: &[u8]) -> Result<Registry, String> {
        let reg: Registry = serde_json::from_slice(bytes)
            .map_err(|e| format!("registry is not valid JSON: {e}"))?;
        match reg.validate() {
            Ok(()) => Ok(reg),
            Err(errs) => Err(format!("invalid registry:\n  - {}", errs.join("\n  - "))),
        }
    }

    /// Every structural invariant the loose `Geography` shape can't express.
    /// Returns ALL violations (not just the first) so a broken hand-edit is one
    /// fix-it pass, not a guessing game.
    pub fn validate(&self) -> Result<(), Vec<String>> {
        let mut errs = Vec::new();
        if self.version != 1 {
            errs.push(format!(
                "unknown registry version {} (expected 1)",
                self.version
            ));
        }
        let mut seen = std::collections::HashSet::new();
        for g in &self.geographies {
            let id = &g.id;
            if !seen.insert(id) {
                errs.push(format!("duplicate geography id {id:?}"));
            }
            match g.kind.as_str() {
                "builtin" => {
                    match &g.map {
                        Some(m) if BUILTIN_MAPS.contains(&m.as_str()) => {}
                        Some(m) => errs.push(format!(
                            "{id:?}: builtin map {m:?} is not one the server injects {BUILTIN_MAPS:?}"
                        )),
                        None => errs.push(format!("{id:?}: builtin geography needs a \"map\"")),
                    }
                    if !g.available {
                        errs.push(format!("{id:?}: builtin maps are always available"));
                    }
                }
                "static" => {
                    if g.object.is_none() {
                        errs.push(format!("{id:?}: static geography needs an \"object\""));
                    }
                    if g.key_kind.is_none() {
                        errs.push(format!("{id:?}: static geography needs a \"key_kind\""));
                    }
                    match &g.renderer {
                        Some(_) => {}
                        None => errs.push(format!("{id:?}: static geography needs a \"renderer\"")),
                    }
                    // The crux: an AVAILABLE static layer must actually be drawable —
                    // a shipped renderer, geometry present, and ≥1 metric family.
                    // (This is the check that turns the "greyed when it shouldn't be /
                    // live when it can't draw" class of bug into a boot error.)
                    if g.available {
                        if let Some(r) = &g.renderer {
                            if !SHIPPED_RENDERERS.contains(&r.as_str()) {
                                errs.push(format!(
                                    "{id:?}: available but renderer {r:?} isn't shipped {SHIPPED_RENDERERS:?}"
                                ));
                            }
                        }
                        if g.topojson.is_none() {
                            errs.push(format!(
                                "{id:?}: available static layer has no \"topojson\""
                            ));
                        }
                        if g.families.is_empty() {
                            errs.push(format!(
                                "{id:?}: available static layer has no metric families"
                            ));
                        }
                    }
                }
                other => errs.push(format!("{id:?}: unknown kind {other:?} (builtin|static)")),
            }
        }
        if errs.is_empty() {
            Ok(())
        } else {
            Err(errs)
        }
    }

    /// One-line-per-layer summary for the boot banner.
    pub fn summary(&self) -> String {
        let (live, grey): (Vec<_>, Vec<_>) = self.geographies.iter().partition(|g| g.available);
        format!(
            "geo registry: {} live ({}), {} greyed",
            live.len(),
            live.iter()
                .map(|g| g.id.as_str())
                .collect::<Vec<_>>()
                .join(", "),
            grey.len()
        )
    }
}

// ── serving consumer geo assets from --geo-dir ───────────────────────────────

/// Geo asset dir, resolved at most once: an explicit `set_geo_dir` (the CLI's
/// `--geo-dir`) wins; otherwise the `TAXA_GEO_DIR` env var.
static GEO_DIR: std::sync::OnceLock<Option<PathBuf>> = std::sync::OnceLock::new();

fn geo_dir() -> Option<&'static Path> {
    GEO_DIR
        .get_or_init(|| std::env::var_os("TAXA_GEO_DIR").map(Into::into))
        .as_deref()
}

/// Serve `/static/vendor/geo/*` (registry + TopoJSON + metric files) from this
/// directory instead of the embedded bundle. taxa ships no geo DATA; a consumer
/// points this at their built layers. Call before serving.
pub fn set_geo_dir(dir: impl Into<PathBuf>) {
    let _ = GEO_DIR.set(Some(dir.into()));
}

/// The resolved geo dir (for the boot banner), or None if none is configured.
pub fn geo_dir_path() -> Option<&'static Path> {
    geo_dir()
}

/// If a geo dir is configured and `rel` is `vendor/geo/<file>`, serve `<file>`
/// from it. Returns None so `h_asset` can fall through to the embedded bundle
/// (no geo dir, traversal attempt, or missing file).
///
/// Large layer files (TopoJSON runs to tens of MB) get a WEAK ETag derived from
/// length+mtime — a 304 round-trip without re-hashing the file on every request.
pub(crate) fn serve_geo_asset(rel: &str, req_headers: &HeaderMap) -> Option<Response> {
    read_geo_asset(geo_dir()?, rel, req_headers)
}

/// Dir-parameterized core (testable without the process-global `geo_dir()`).
fn read_geo_asset(dir: &Path, rel: &str, req_headers: &HeaderMap) -> Option<Response> {
    let file = rel.strip_prefix("vendor/geo/")?;
    if file.is_empty() || file.split('/').any(|s| s == ".." || s.is_empty()) {
        return None; // no traversal; geo dir is flat
    }
    let path = dir.join(file);
    let meta = std::fs::metadata(&path).ok()?;
    if !meta.is_file() {
        return None;
    }
    let etag = weak_etag(&meta);
    let inm = req_headers
        .get(header::IF_NONE_MATCH)
        .and_then(|v| v.to_str().ok());
    if inm.is_some_and(|v| crate::etag_matches(v, &etag)) {
        return Some((StatusCode::NOT_MODIFIED, [(header::ETAG, etag)]).into_response());
    }
    let bytes = std::fs::read(&path).ok()?;
    let mime = mime_guess::from_path(&path).first_or_octet_stream();
    Some(
        (
            [
                (header::CONTENT_TYPE, mime.as_ref()),
                (header::CACHE_CONTROL, "no-cache"),
                (header::ETAG, &etag),
            ],
            bytes,
        )
            .into_response(),
    )
}

/// `W/"<len>-<mtime_secs>"` — cheap revalidation validator for a disk file.
fn weak_etag(meta: &std::fs::Metadata) -> String {
    let mtime = meta
        .modified()
        .ok()
        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
        .map(|d| d.as_secs())
        .unwrap_or(0);
    format!("W/\"{}-{}\"", meta.len(), mtime)
}

/// Boot check: if `--geo-dir/registry.json` exists, parse + validate it. Ok with
/// a summary string, or Err with all violations. A missing registry is Ok(None)
/// (the geo view falls back to built-in maps — a valid, common configuration).
pub fn check_registry(dir: &Path) -> Result<Option<String>, String> {
    let path = dir.join("registry.json");
    match std::fs::read(&path) {
        Ok(bytes) => Registry::parse(&bytes).map(|r| Some(r.summary())),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(e) => Err(format!("cannot read {}: {e}", path.display())),
    }
}

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

    fn parse(v: serde_json::Value) -> Result<Registry, String> {
        Registry::parse(v.to_string().as_bytes())
    }

    fn good_static() -> serde_json::Value {
        json!({
            "id": "tracts", "label": "Census tracts", "group": "High-resolution",
            "kind": "static", "us": true, "renderer": "svg", "object": "tracts",
            "key_kind": "geoid11", "features": 85000,
            "topojson": "/static/vendor/geo/tracts.json",
            "families": [{"id": "acs", "label": "ACS", "file": "/static/vendor/geo/tracts__acs.json"}],
            "available": true, "note": ""
        })
    }

    #[test]
    fn accepts_a_well_formed_registry() {
        let reg = parse(json!({
            "version": 1,
            "geographies": [
                {"id": "counties", "label": "Counties", "group": "National",
                 "kind": "builtin", "map": "counties", "us": true, "available": true},
                good_static(),
                // A greyed webgl layer: available=false, so its missing geometry
                // and unshipped renderer are fine.
                {"id": "blocks", "label": "Blocks", "group": "High-resolution",
                 "kind": "static", "us": true, "renderer": "webgl", "object": "blocks",
                 "key_kind": "geoid15", "features": 8100000, "topojson": null,
                 "families": [], "available": false, "note": "needs WebGL"}
            ]
        }))
        .expect("valid registry");
        assert_eq!(reg.geographies.len(), 3);
    }

    #[test]
    fn rejects_unknown_fields() {
        // A typo'd field (the silent-drift class) is caught, not ignored.
        let err = parse(json!({
            "version": 1,
            "geographies": [{"id": "counties", "label": "C", "group": "N",
                "kind": "builtin", "map": "counties", "available": true, "avaliable": true}]
        }))
        .unwrap_err();
        assert!(
            err.contains("avaliable") || err.contains("unknown field"),
            "{err}"
        );
    }

    #[test]
    fn rejects_available_static_without_geometry_or_families() {
        let mut g = good_static();
        g["topojson"] = json!(null);
        g["families"] = json!([]);
        let err = parse(json!({"version": 1, "geographies": [g]})).unwrap_err();
        assert!(err.contains("no \"topojson\""), "{err}");
        assert!(err.contains("no metric families"), "{err}");
    }

    #[test]
    fn rejects_available_layer_with_unshipped_renderer() {
        let mut g = good_static();
        g["renderer"] = json!("webgl");
        let err = parse(json!({"version": 1, "geographies": [g]})).unwrap_err();
        assert!(err.contains("isn't shipped"), "{err}");
    }

    #[test]
    fn rejects_duplicate_ids_and_bad_kinds_and_bad_builtin_map() {
        let err = parse(json!({
            "version": 1,
            "geographies": [
                {"id": "x", "label": "X", "group": "G", "kind": "builtin", "map": "nope", "available": true},
                {"id": "x", "label": "X2", "group": "G", "kind": "weird", "available": true}
            ]
        }))
        .unwrap_err();
        assert!(err.contains("duplicate geography id"), "{err}");
        assert!(err.contains("not one the server injects"), "{err}");
        assert!(err.contains("unknown kind"), "{err}");
    }

    #[test]
    fn serves_geo_file_with_weak_etag_and_304() {
        use axum::http::HeaderValue;
        // A flat geo dir under the system temp dir (no tempfile dep).
        let dir = std::env::temp_dir().join("taxa_geo_test_serve");
        let _ = std::fs::create_dir_all(&dir);
        std::fs::write(
            dir.join("registry.json"),
            br#"{"version":1,"geographies":[]}"#,
        )
        .unwrap();

        // First GET: 200 + a weak ETag + no-cache.
        let resp = read_geo_asset(&dir, "vendor/geo/registry.json", &HeaderMap::new()).unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let etag = resp
            .headers()
            .get(header::ETAG)
            .unwrap()
            .to_str()
            .unwrap()
            .to_string();
        assert!(etag.starts_with("W/\""), "weak validator: {etag}");
        assert_eq!(
            resp.headers().get(header::CACHE_CONTROL).unwrap(),
            "no-cache"
        );

        // Conditional GET with that weak ETag → 304 (this is the regression the
        // boot smoke-test caught: weak `W/` validators must match on both sides).
        let mut h = HeaderMap::new();
        h.insert(header::IF_NONE_MATCH, HeaderValue::from_str(&etag).unwrap());
        let resp = read_geo_asset(&dir, "vendor/geo/registry.json", &h).unwrap();
        assert_eq!(resp.status(), StatusCode::NOT_MODIFIED);

        // Path traversal and missing files fall through to None (→ embedded).
        assert!(read_geo_asset(&dir, "vendor/geo/../secrets", &HeaderMap::new()).is_none());
        assert!(read_geo_asset(&dir, "vendor/geo/nope.json", &HeaderMap::new()).is_none());
        // Non-geo paths aren't ours.
        assert!(read_geo_asset(&dir, "viz/app.js", &HeaderMap::new()).is_none());
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn reports_all_violations_at_once() {
        // Two independent problems → both surfaced in one pass.
        let err = parse(json!({
            "version": 2,
            "geographies": [{"id": "t", "label": "T", "group": "G", "kind": "static",
                "renderer": "svg", "available": false}]
        }))
        .unwrap_err();
        assert!(err.contains("version"), "{err}");
        assert!(err.contains("needs an \"object\""), "{err}");
    }
}