ezu-cli 0.13.1

Command-line renderer for the Ezu Style Spec
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
//! axum handlers for `ezu serve`.

use std::sync::Arc;

use axum::{
    body::Body,
    extract::{Path, Query, State},
    http::{header, StatusCode},
    response::{
        sse::{Event, KeepAlive, Sse},
        Html, Response,
    },
    routing::get,
    Json, Router,
};
use ezu::core::TileId as CoreTileId;
use ezu::features::mvt;
use ezu::renderer::{OutputFormat, RenderOptions};
use futures::stream::{self, Stream};
use serde_json::json;
use std::collections::HashMap;
use std::time::Duration;
use tokio::sync::broadcast;

use super::state::{validate_text, AppState, StyleSnapshot};
use crate::render::MissingTile;
use crate::source::{FeatureSource, SourceError};

pub fn router() -> Router<AppState> {
    Router::new()
        .route("/", get(index))
        .route("/style", get(get_style).put(put_style))
        .route("/style/params", get(get_params_schema))
        .route("/style/attribution", get(get_attribution))
        .route("/config", get(get_config))
        .route("/style/validate", axum::routing::post(post_validate))
        .route("/style/fetch", get(get_style_fetch))
        .route("/style/events", get(get_style_events))
        .route("/schemas/ezu-style.json", get(get_schema))
        .route("/tiles/{z}/{x}/{y_ext}", get(get_tile))
        .route("/mvt/{z}/{x}/{y}", get(get_mvt))
        .route("/mvt-meta/{z}/{x}/{y}", get(get_mvt_meta))
}

async fn index() -> Html<&'static str> {
    Html(include_str!("editor.html"))
}

/// Zoom the editor should stop requesting tiles at when the source
/// declares its own depth. A source that stays quiet about it (a bare
/// `{z}/{x}/{y}` template) gets [`ABSOLUTE_MAXZOOM`] instead — the
/// renderer is happy to draw whatever the fetcher hands it, so an
/// unknown depth is no reason to fence the map in.
const ABSOLUTE_MAXZOOM: u8 = 22;

/// Server-side knobs the editor needs to configure its map. Kept as one
/// endpoint so the front end never has to guess at CLI defaults.
async fn get_config(State(s): State<AppState>) -> Json<serde_json::Value> {
    // The deepest any source goes, when every one of them says.
    let data_maxzoom = s
        .feature_sources
        .iter()
        .map(|src| src.max_zoom())
        .collect::<Option<Vec<u8>>>()
        .and_then(|zooms| zooms.into_iter().max());
    // Past the source's own depth the tile handler reprojects ancestor
    // tiles, `overzoom_levels` of them, so that is exactly how much
    // deeper than the data the editor can still ask for.
    let overzoom_levels = s.sources.overzoom_levels;
    let raster_maxzoom = match data_maxzoom {
        Some(z) => z.saturating_add(overzoom_levels).min(ABSOLUTE_MAXZOOM),
        None => ABSOLUTE_MAXZOOM,
    };
    Json(serde_json::json!({
        "overzoomLevels": overzoom_levels,
        "dataMaxzoom": data_maxzoom,
        "rasterMaxzoom": raster_maxzoom,
    }))
}

async fn get_style(State(s): State<AppState>) -> Response {
    let snap = s.style.read().await;
    Response::builder()
        .header(header::CONTENT_TYPE, "application/json; charset=utf-8")
        .header(header::CACHE_CONTROL, "no-store")
        .body(Body::from(snap.text.clone()))
        .expect("response builder with valid headers + body never fails")
}

async fn put_style(
    State(s): State<AppState>,
    body: String,
) -> Result<Json<serde_json::Value>, (StatusCode, String)> {
    let next_version = { s.style.read().await.version + 1 };
    let snap = StyleSnapshot::build(body, next_version, &s.sources)
        .await
        .map_err(|e| (StatusCode::BAD_REQUEST, e.to_string()))?;
    let version = snap.version;
    *s.style.write().await = snap;
    Ok(Json(json!({ "version": version })))
}

/// JSON Schema for the current style's parameter values — what the
/// tile endpoint accepts as query-string overrides. Editor UIs can
/// build sliders / color pickers / toggles straight off this.
async fn get_params_schema(State(s): State<AppState>) -> Json<serde_json::Value> {
    let snap = s.style.read().await;
    Json(snap.doc.params_schema())
}

/// Effective attribution for the current style: the document's own
/// declarations merged with upstream metadata (TileJSON `attribution`,
/// PMTiles archive metadata) inherited by sources that declare none.
/// The editor feeds this to the MapLibre attribution control.
async fn get_attribution(State(s): State<AppState>) -> Json<serde_json::Value> {
    let snap = s.style.read().await;
    let mut list: Vec<String> = snap
        .doc
        .attributions()
        .iter()
        .map(|a| a.to_string())
        .collect();
    let mut push = |a: String| {
        if !a.is_empty() && !list.contains(&a) {
            list.push(a);
        }
    };
    // DEM sources first, then imagery, each inheriting upstream metadata
    // only when the document's own entry declares no attribution.
    let pyramids = snap.tiles.pyramids();
    for dem in [true, false] {
        for src in pyramids.iter().filter(|p| p.is_dem == dem) {
            let declares = snap
                .doc
                .sources
                .get(&*src.name)
                .is_some_and(|d| d.attribution().is_some());
            if declares {
                continue;
            }
            if let Some(a) = src.attribution().await {
                push(a);
            }
        }
    }
    // Each MVT/PMTiles feature source inherits upstream metadata only
    // when the document's own entry doesn't declare attribution.
    for src in s.feature_sources.iter() {
        let declares = snap
            .doc
            .sources
            .get(&*src.name)
            .is_some_and(|d| d.attribution().is_some());
        if !declares {
            if let Some(a) = src.attribution() {
                push(a.to_string());
            }
        }
    }
    Json(json!({ "attributions": list, "attribution": list.join(" | ") }))
}

/// Dry-run the parse + graph-build pipeline `PUT /style` would run,
/// without prefetching URL assets or swapping the live snapshot. The
/// live editor pings this on every keystroke (debounced), so it has
/// to be cheap.
async fn post_validate(body: String) -> Result<Json<serde_json::Value>, (StatusCode, String)> {
    validate_text(&body).map_err(|e| (StatusCode::BAD_REQUEST, e.to_string()))?;
    Ok(Json(json!({ "ok": true })))
}

/// Fetch a remote style document on behalf of the editor. Limited to
/// http(s) URLs so this can't be coaxed into serving arbitrary local
/// files via the browser. Used by the "Open URL" button.
async fn get_style_fetch(
    Query(q): Query<HashMap<String, String>>,
) -> Result<Response, (StatusCode, String)> {
    let url = q.get("url").ok_or((
        StatusCode::BAD_REQUEST,
        "missing url query parameter".into(),
    ))?;
    if !(url.starts_with("http://") || url.starts_with("https://")) {
        return Err((
            StatusCode::BAD_REQUEST,
            "only http(s) URLs are allowed".into(),
        ));
    }
    let text = crate::fetch_text(url)
        .await
        .map_err(|e| (StatusCode::BAD_GATEWAY, e.to_string()))?;
    Ok(Response::builder()
        .header(header::CONTENT_TYPE, "application/json; charset=utf-8")
        .header(header::CACHE_CONTROL, "no-store")
        .body(Body::from(text))
        .expect("response builder with valid headers + body never fails"))
}

/// Server-Sent Events stream of style-reload notifications. Fires
/// whenever the local style file watched by `ezu serve <file>` changes
/// on disk and the server successfully rebuilt the snapshot. The
/// editor listens to this and either silently swaps the buffer (clean
/// editor) or surfaces a banner (when the user has unsaved edits).
async fn get_style_events(
    State(s): State<AppState>,
) -> Sse<impl Stream<Item = Result<Event, std::convert::Infallible>>> {
    let rx = s.events.subscribe();
    let stream = stream::unfold(rx, |mut rx| async move {
        loop {
            match rx.recv().await {
                Ok(ev) => {
                    let event = Event::default()
                        .event("reload")
                        .json_data(&ev)
                        .unwrap_or_else(|_| Event::default());
                    return Some((Ok(event), rx));
                }
                // Skip lagged events; an editor missing a couple of
                // mid-flight reloads just sees the latest one next.
                Err(broadcast::error::RecvError::Lagged(_)) => continue,
                Err(broadcast::error::RecvError::Closed) => return None,
            }
        }
    });
    Sse::new(stream).keep_alive(KeepAlive::new().interval(Duration::from_secs(15)))
}

async fn get_schema(State(s): State<AppState>) -> Response {
    // Schema is derived from the live node registry so it always matches
    // the ops the server can actually evaluate.
    let body = serde_json::to_vec_pretty(&*s.schema).unwrap_or_default();
    Response::builder()
        .header(header::CONTENT_TYPE, "application/schema+json")
        .header(header::CACHE_CONTROL, "no-store")
        .body(Body::from(body))
        .expect("response builder with valid headers + body never fails")
}

#[derive(Clone, Copy)]
enum TileFormat {
    Png,
    Webp,
}

impl TileFormat {
    fn content_type(self) -> &'static str {
        match self {
            TileFormat::Png => "image/png",
            TileFormat::Webp => "image/webp",
        }
    }

    fn encoding(self) -> OutputFormat {
        match self {
            TileFormat::Png => OutputFormat::Png,
            TileFormat::Webp => OutputFormat::Webp,
        }
    }
}

/// The status a failed tile answers with: 404 when the style asked for a
/// missing source tile to fail the render (`on-missing: error`), 502 when a
/// source could not be fetched or sent a DEM or imagery tile that does not
/// decode, and 500 when the render itself failed.
fn status_of(e: &(dyn std::error::Error + 'static)) -> StatusCode {
    use ezu::renderer::{Error, ErrorKind};
    if e.downcast_ref::<MissingTile>().is_some() {
        StatusCode::NOT_FOUND
    } else if e.downcast_ref::<SourceError>().is_some()
        || e.downcast_ref::<Error>()
            .is_some_and(|e| matches!(e.kind(), ErrorKind::DemDecode | ErrorKind::RasterDecode))
    {
        StatusCode::BAD_GATEWAY
    } else {
        StatusCode::INTERNAL_SERVER_ERROR
    }
}

/// The pixel density a tile URL's `@Nx` asks for, `N` from 1 to 4: the
/// MapLibre and XYZ spelling of a hi-DPI tile.
fn density(factor: &str) -> Result<u32, (StatusCode, String)> {
    factor
        .strip_suffix('x')
        .and_then(|n| n.parse::<u32>().ok())
        .filter(|n| (1..=4).contains(n))
        .ok_or_else(|| {
            (
                StatusCode::BAD_REQUEST,
                format!("`@{factor}`: expected @1x, @2x, @3x or @4x"),
            )
        })
}

async fn get_tile(
    State(s): State<AppState>,
    Path((z, x, y_ext)): Path<(u8, u32, String)>,
    Query(q): Query<HashMap<String, String>>,
) -> Result<Response, (StatusCode, String)> {
    // Sniff the output format off the extension. Default is PNG so the
    // legacy `/tiles/{z}/{x}/{y}` (no suffix) and `.png` keep working.
    let (y_str, format) = if let Some(s) = y_ext.strip_suffix(".webp") {
        (s, TileFormat::Webp)
    } else if let Some(s) = y_ext.strip_suffix(".png") {
        (s, TileFormat::Png)
    } else {
        (y_ext.as_str(), TileFormat::Png)
    };
    let (y_str, scale) = match y_str.split_once('@') {
        Some((y, factor)) => (y, Some(density(factor)?)),
        None => (y_str, None),
    };
    let y: u32 = y_str
        .parse()
        .map_err(|_| (StatusCode::BAD_REQUEST, "bad y".into()))?;
    let tile = CoreTileId::new(z, x, y);

    // Take only what we need from the snapshot to keep the lock window
    // short. Query-string parameter overrides are validated against
    // the document's `params` declarations while we hold the lock.
    let png_compression = s.sources.png_compression;
    let (tiles, params) = {
        let snap = s.style.read().await;
        let mut params = Vec::new();
        for (name, raw) in &q {
            // `v` is reserved as the editor's cache-busting version key.
            if name == "v" {
                continue;
            }
            ezu::graph::parse_param_value(&snap.doc.params, name, raw)
                .map_err(|e| (StatusCode::BAD_REQUEST, e))?;
            params.push((name.clone(), raw.clone()));
        }
        (Arc::clone(&snap.tiles), params)
    };
    // `@Nx` draws the same map at N times the density, as a hi-DPI map
    // client asks for it; without it the server's own ratio holds.
    let pixel_ratio = scale.map(|n| n as f32);

    let bytes = tiles
        .render(tile, move |r, set, opts| {
            let opts = RenderOptions {
                format: format.encoding(),
                params,
                pixel_ratio: pixel_ratio.unwrap_or(opts.pixel_ratio),
                png_compression,
                ..opts
            };
            r.render_tile_with(tile.z, tile.x, tile.y, set, opts)
        })
        .await
        .map_err(|e| {
            tracing::error!("tile {z}/{x}/{}: {e}", tile.y);
            (status_of(e.as_ref()), e.to_string())
        })?;

    Ok(Response::builder()
        .header(header::CONTENT_TYPE, format.content_type())
        .header(header::CACHE_CONTROL, "no-store")
        .body(Body::from(bytes))
        .expect("response builder with valid headers + body never fails"))
}

/// The feature source a raw-MVT request names with `?source=`, or the
/// style's first one.
fn requested_source<'s>(
    s: &'s AppState,
    q: &HashMap<String, String>,
) -> Result<Option<&'s FeatureSource>, (StatusCode, String)> {
    match q.get("source") {
        Some(name) => s
            .feature_sources
            .get(Some(name))
            .map(Some)
            .ok_or((StatusCode::NOT_FOUND, format!("no feature source `{name}`"))),
        None => Ok(s.feature_sources.get(None)),
    }
}

/// Return raw decompressed MVT bytes for `(z, x, y)` from the feature
/// source named by `?source=` (default: the first). Used by the WASM demo,
/// which does its own decoding + rendering client-side.
async fn get_mvt(
    State(s): State<AppState>,
    Path((z, x, y)): Path<(u8, u32, u32)>,
    Query(q): Query<HashMap<String, String>>,
) -> Result<Response, (StatusCode, String)> {
    let tile = CoreTileId::new(z, x, y);
    let Some(source) = requested_source(&s, &q)? else {
        return Err((StatusCode::NOT_FOUND, "tile not in source".into()));
    };
    // This endpoint serves native MVT bytes that callers expect to
    // decode at the requested tile's coordinate frame, so a parent
    // fallback (different coords) would be wrong. Treat overzoom hits
    // as misses here.
    let Some((bytes, src)) = fetch_mvt(&s, source, tile).await? else {
        return Err((StatusCode::NOT_FOUND, "tile not in source".into()));
    };
    if src != tile {
        return Err((StatusCode::NOT_FOUND, "tile not in source".into()));
    }
    Ok(Response::builder()
        .header(header::CONTENT_TYPE, "application/vnd.mapbox-vector-tile")
        .header(header::CACHE_CONTROL, "public, max-age=300")
        .body(Body::from(bytes.to_vec()))
        .expect("response builder with valid headers + body never fails"))
}

/// Decode the MVT for `(z, x, y)` and report which layers it contains.
/// Used by the editor's inspect panel to populate per-layer toggles
/// without having to re-decode MVTs in the browser.
async fn get_mvt_meta(
    State(s): State<AppState>,
    Path((z, x, y)): Path<(u8, u32, u32)>,
    Query(q): Query<HashMap<String, String>>,
) -> Result<Json<serde_json::Value>, (StatusCode, String)> {
    let tile = CoreTileId::new(z, x, y);
    let Some(source) = requested_source(&s, &q)? else {
        return Ok(Json(json!({ "layers": [] })));
    };
    // Layer names + geometry kinds don't change under overzoom, so it's
    // fine if the bytes came from an ancestor — no clipping needed.
    let Some((bytes, _src)) = fetch_mvt(&s, source, tile).await? else {
        return Ok(Json(json!({ "layers": [] })));
    };
    let decoded =
        mvt::decode(&bytes).map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
    let layers: Vec<_> = decoded
        .layers
        .iter()
        .map(|l| {
            let (mut p, mut ln, mut pg) = (false, false, false);
            for f in &l.features {
                if !f.geometry.points.is_empty() {
                    p = true;
                }
                if !f.geometry.lines.is_empty() {
                    ln = true;
                }
                if !f.geometry.polygons.is_empty() {
                    pg = true;
                }
            }
            let mut geoms: Vec<&str> = Vec::new();
            if p {
                geoms.push("point");
            }
            if ln {
                geoms.push("line");
            }
            if pg {
                geoms.push("polygon");
            }
            json!({
                "name": l.name,
                "geometry_types": geoms,
                "features": l.features.len(),
            })
        })
        .collect();
    Ok(Json(json!({ "layers": layers })))
}

/// Fetch `source`'s MVT for `tile`: nothing below the source's
/// `min-zoom`, the covering ancestor past its `max-zoom`, and on a miss
/// up to `overzoom_levels` parents further. The returned `CoreTileId`
/// identifies which tile the bytes actually came from — equal to `tile`
/// on a direct hit, an ancestor on overzoom. Callers that need the raw
/// native bytes (the `/mvt` endpoint) should treat a non-matching ID as a
/// miss.
async fn fetch_mvt(
    s: &AppState,
    source: &FeatureSource,
    tile: CoreTileId,
) -> Result<Option<(bytes::Bytes, CoreTileId)>, (StatusCode, String)> {
    source
        .fetch(tile, s.sources.overzoom_levels)
        .await
        .map_err(|e| (StatusCode::BAD_GATEWAY, e.to_string()))
}

#[cfg(test)]
mod tests {
    use std::path::{Path as FsPath, PathBuf};

    use axum::http::Request;
    use tower::ServiceExt;

    use super::*;
    use crate::serve::state::Sources;
    use crate::source::{FeatureSources, TileByteCache};

    fn testdata(name: &str) -> Vec<u8> {
        let path = FsPath::new(env!("CARGO_MANIFEST_DIR"))
            .join("../../go/testdata")
            .join(name);
        std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()))
    }

    /// A fresh directory for one test's tiles.
    fn scratch(name: &str) -> PathBuf {
        let root = std::env::temp_dir().join(format!("ezu-serve-{name}-{}", std::process::id()));
        std::fs::remove_dir_all(&root).ok();
        std::fs::create_dir_all(&root).unwrap();
        root
    }

    fn write_tile(root: &FsPath, dir: &str, (z, x, y): (u8, u32, u32), ext: &str, bytes: &[u8]) {
        let d = root.join(dir).join(z.to_string()).join(x.to_string());
        std::fs::create_dir_all(&d).unwrap();
        std::fs::write(d.join(format!("{y}.{ext}")), bytes).unwrap();
    }

    /// What `ezu serve` holds for `style`, its files under `root`.
    async fn serve(style: &str, root: &FsPath) -> Result<AppState, String> {
        serve_at(style, root, None, 1.0).await
    }

    /// [`serve`], with `--tile-size` and `--pixel-ratio`.
    async fn serve_at(
        style: &str,
        root: &FsPath,
        tile_size: Option<u32>,
        pixel_ratio: f32,
    ) -> Result<AppState, String> {
        let doc = ezu::style::Document::from_json(style).map_err(|e| e.to_string())?;
        let byte_cache = Arc::new(TileByteCache::new(1 << 20));
        let feature_sources = FeatureSources::open(&doc, None, root)
            .await
            .map_err(|e| e.to_string())?
            .with_byte_cache(&byte_cache, true);
        let sources = Sources {
            assets_dir: root.to_path_buf(),
            feature_sources: Arc::new(feature_sources),
            overzoom_levels: 0,
            byte_cache,
            tile_size,
            pixel_ratio,
            pad: None,
            png_compression: Default::default(),
        };
        let snapshot = StyleSnapshot::build(style.to_string(), 1, &sources)
            .await
            .map_err(|e| e.to_string())?;
        Ok(AppState::new(sources, snapshot))
    }

    async fn request(
        state: &AppState,
        method: &str,
        uri: &str,
        body: &str,
    ) -> (StatusCode, Vec<u8>) {
        let response = router()
            .with_state(state.clone())
            .oneshot(
                Request::builder()
                    .method(method)
                    .uri(uri)
                    .body(Body::from(body.to_string()))
                    .unwrap(),
            )
            .await
            .unwrap();
        let status = response.status();
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        (status, bytes.to_vec())
    }

    /// Water stitched across tile borders, so the graph reads the
    /// neighbours.
    const STITCHED: &str = r##"{
      "name": "stitched",
      "tile-size": 64,
      "sources": { "bg": { "type": "mvt", "url": "file:bg/{z}/{x}/{y}.mvt" } },
      "nodes": {
        "f": { "op": "features", "source": "bg", "layer": "water", "stitch": "merge" },
        "fill": { "op": "fill-solid", "features": "@f", "fill": "#204080" },
        "out": { "op": "blur", "input": "@fill", "sigma": 3.0 }
      },
      "output": "@out"
    }"##;

    #[tokio::test]
    async fn a_neighbour_that_does_not_decode_is_left_out() {
        let root = scratch("neighbour");
        let centre = (14, 14554, 6454);
        write_tile(
            &root,
            "bg",
            centre,
            "mvt",
            &testdata("basemap-14-14554-6454.mvt"),
        );
        let state = serve(STITCHED, &root).await.unwrap();
        let uri = "/tiles/14/14554/6454.png";

        let (status, alone) = request(&state, "GET", uri, "").await;
        assert_eq!(status, StatusCode::OK);
        // A broken neighbour draws as a missing one.
        write_tile(&root, "bg", (14, 14555, 6454), "mvt", b"not a tile");
        let (status, beside) = request(&state, "GET", uri, "").await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(alone, beside);
        // A broken centre still fails the tile.
        write_tile(&root, "bg", centre, "mvt", b"not a tile either");
        let (status, _) = request(&state, "GET", uri, "").await;
        assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
        std::fs::remove_dir_all(&root).ok();
    }

    fn png_size(bytes: &[u8]) -> (u32, u32) {
        let p = tiny_skia::Pixmap::decode_png(bytes).expect("a PNG");
        (p.width(), p.height())
    }

    /// `@2x` is the retina tile: twice the tile size with the style's pixel
    /// sizes doubled — what a server started with `--pixel-ratio 2` draws,
    /// and not the plain tile of twice the size, whose blur stays narrow.
    #[tokio::test]
    async fn an_at_2x_tile_is_the_tile_at_twice_the_density() {
        let root = scratch("density");
        write_tile(
            &root,
            "bg",
            (14, 14554, 6454),
            "mvt",
            &testdata("basemap-14-14554-6454.mvt"),
        );
        let state = serve(STITCHED, &root).await.unwrap();
        let (status, plain) = request(&state, "GET", "/tiles/14/14554/6454.png", "").await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(png_size(&plain), (64, 64));
        let (status, one) = request(&state, "GET", "/tiles/14/14554/6454@1x.png", "").await;
        assert_eq!((status, &one), (StatusCode::OK, &plain));
        let (status, double) = request(&state, "GET", "/tiles/14/14554/6454@2x.png", "").await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(png_size(&double), (128, 128));

        let retina = serve_at(STITCHED, &root, None, 2.0).await.unwrap();
        let (_, at_ratio) = request(&retina, "GET", "/tiles/14/14554/6454.png", "").await;
        assert!(
            double == at_ratio,
            "@2x differs from a --pixel-ratio 2 tile"
        );
        // A URL's own density wins over the server's.
        let (_, back) = request(&retina, "GET", "/tiles/14/14554/6454@1x.png", "").await;
        assert!(
            back == plain,
            "@1x on a --pixel-ratio 2 server is not the plain tile"
        );

        let big = serve_at(STITCHED, &root, Some(128), 1.0).await.unwrap();
        let (_, at_128) = request(&big, "GET", "/tiles/14/14554/6454.png", "").await;
        assert!(double != at_128, "@2x drew what a 128 px tile draws");
        // The density multiplies the size the server renders at.
        let (_, quad) = request(&big, "GET", "/tiles/14/14554/6454@2x.webp", "").await;
        let quad = ezu::paint::host::decode_image_bytes(&quad).expect("a WebP");
        assert_eq!((quad.width, quad.height), (256, 256));

        for bad in ["@0x", "@5x", "@2", "@x", "@1.5x"] {
            let uri = format!("/tiles/14/14554/6454{bad}.png");
            assert_eq!(
                request(&state, "GET", &uri, "").await.0,
                StatusCode::BAD_REQUEST,
                "{uri}"
            );
        }
        std::fs::remove_dir_all(&root).ok();
    }

    /// A string param reaches a tile through the query string, and its
    /// `enum` is checked there and published with the params schema.
    #[tokio::test]
    async fn a_string_param_rides_the_query_string() {
        let root = scratch("string-param");
        let style = r##"{
          "name": "modes",
          "tile-size": 16,
          "params": {
            "mode": { "type": "string", "enum": ["multiply", "screen"], "default": "multiply" }
          },
          "nodes": {
            "base": { "op": "solid", "color": "#808080" },
            "over": { "op": "solid", "color": "#ff4020" },
            "out":  { "op": "blend", "base": "@base", "over": "@over", "mode": "$mode" }
          },
          "output": "@out"
        }"##;
        let state = serve(style, &root).await.unwrap();
        let (status, schema) = request(&state, "GET", "/style/params", "").await;
        assert_eq!(status, StatusCode::OK);
        let schema: serde_json::Value = serde_json::from_slice(&schema).unwrap();
        assert_eq!(
            schema["properties"]["mode"]["enum"],
            serde_json::json!(["multiply", "screen"])
        );

        let (status, plain) = request(&state, "GET", "/tiles/3/1/2.png", "").await;
        assert_eq!(status, StatusCode::OK);
        let (status, same) = request(&state, "GET", "/tiles/3/1/2.png?mode=multiply", "").await;
        assert_eq!((status, &same), (StatusCode::OK, &plain));
        let (status, screen) = request(&state, "GET", "/tiles/3/1/2.png?mode=screen", "").await;
        assert_eq!(status, StatusCode::OK);
        assert_ne!(screen, plain);
        let (status, body) = request(&state, "GET", "/tiles/3/1/2.png?mode=overlay", "").await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        assert!(
            String::from_utf8_lossy(&body).contains("not one of"),
            "{}",
            String::from_utf8_lossy(&body)
        );
        std::fs::remove_dir_all(&root).ok();
    }

    fn dem_style(url: &str, read: bool) -> String {
        let out = if read {
            r#""dem": { "op": "dem", "source": "terrain" },
               "out": { "op": "hillshade", "field": "@dem" }"#
        } else {
            r##""out": { "op": "solid", "color": "#336699" }"##
        };
        format!(
            r##"{{
              "name": "dem",
              "tile-size": 64,
              "sources": {{ "terrain": {{ "type": "dem", "url": "{url}", "encoding": "terrarium" }} }},
              "nodes": {{ {out} }},
              "output": "@out"
            }}"##
        )
    }

    #[tokio::test]
    async fn a_dem_tile_that_does_not_decode_is_a_bad_gateway() {
        let root = scratch("dem-decode");
        let tile = (10, 909, 402);
        write_tile(
            &root,
            "dem",
            tile,
            "webp",
            &testdata("terrain-10-909-402.webp"),
        );
        let state = serve(&dem_style("file:dem/{z}/{x}/{y}.webp", true), &root)
            .await
            .unwrap();
        let uri = "/tiles/10/909/402.png";
        assert_eq!(request(&state, "GET", uri, "").await.0, StatusCode::OK);
        write_tile(&root, "dem", tile, "webp", b"not an image");
        assert_eq!(
            request(&state, "GET", uri, "").await.0,
            StatusCode::BAD_GATEWAY
        );
        std::fs::remove_dir_all(&root).ok();
    }

    /// A `dem` source opens when a tile first reads it: one no node reads
    /// is never opened, and one that cannot be reached fails its tiles,
    /// not the style.
    #[tokio::test]
    async fn a_dem_source_opens_only_when_a_tile_reads_it() {
        let root = scratch("dem-lazy");
        // Nothing listens on the discard port, so opening either fails.
        let unreachable = [
            "http://127.0.0.1:9/terrain.json",
            "http://127.0.0.1:9/terrain.pmtiles",
        ];
        for url in unreachable {
            let state = serve(&dem_style(url, false), &root)
                .await
                .unwrap_or_else(|e| panic!("{url}: the style failed to load: {e}"));
            let (status, _) = request(&state, "GET", "/tiles/3/1/2.png", "").await;
            assert_eq!(status, StatusCode::OK, "{url}");
            let snap = state.style.read().await;
            assert!(
                snap.tiles.pyramids().iter().all(|p| !p.is_open()),
                "{url}: a source no node reads was opened"
            );
            drop(snap);

            // A new style that reads it loads too, and its tiles fail.
            let (status, body) = request(&state, "PUT", "/style", &dem_style(url, true)).await;
            assert_eq!(
                status,
                StatusCode::OK,
                "{url}: {}",
                String::from_utf8_lossy(&body)
            );
            let (status, _) = request(&state, "GET", "/tiles/3/1/2.png", "").await;
            assert_eq!(status, StatusCode::BAD_GATEWAY, "{url}");
        }
        std::fs::remove_dir_all(&root).ok();
    }
}