martin-core 0.16.0

Basic building blocks of MapLibre's Martin tile server.
Documentation
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
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
use std::num::{NonZeroU8, NonZeroU32, NonZeroUsize};
use std::panic::{self, AssertUnwindSafe};
use std::path::PathBuf;
use std::sync::Arc;
use std::thread::{self, JoinHandle};

use maplibre_native::{
    CameraUpdate, Image, ImageRenderer, ImageRendererBuilder, LatLng, ResourceOptions, Static, Tile,
};
use tokio::sync::oneshot;
use tracing::{error, info};

use crate::overlay::{AppliedOverlay, OverlaySpec, apply_to_style};
use crate::resources::styles::{StyleError, TileSize};

/// A style to render: a file, or a style document already in memory.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RenderStyle {
    /// A style JSON file.
    Path(PathBuf),
    /// A style JSON document.
    Json(Arc<str>),
}

impl From<PathBuf> for RenderStyle {
    fn from(path: PathBuf) -> Self {
        Self::Path(path)
    }
}

impl RenderStyle {
    /// Loads this style into `renderer`, waiting until it has loaded.
    fn load<S>(&self, renderer: &mut ImageRenderer<S>) -> Result<(), StyleError> {
        match self {
            Self::Path(path) => renderer.load_style_from_path(path)?.wait()?,
            Self::Json(json) => renderer.load_style_from_json_str(json.as_ref()).wait()?,
        }
        Ok(())
    }
}

/// Parameters for a free-camera (static) map render.
///
/// ```no_run
/// # use std::num::NonZeroU8;
/// # use std::path::PathBuf;
/// # use martin_core::styles::RenderParams;
/// let retina = NonZeroU8::new(2).expect("non-zero");
/// RenderParams::new(PathBuf::from("style.json"), 0.0, 0.0, 2.0)
///     .with_size(800, 600, retina)
///     .with_orientation(45.0, 30.0);
/// ```
#[derive(Debug, Clone)]
pub struct RenderParams {
    /// Style to render.
    style: RenderStyle,
    /// Camera target latitude in degrees (WGS84).
    lat: f64,
    /// Camera target longitude in degrees (WGS84).
    lon: f64,
    /// Map zoom level.
    zoom: f64,
    /// Logical output width in pixels.
    width: u32,
    /// Logical output height in pixels.
    height: u32,
    /// Pixel density ratio (1 = standard, 2 = retina). Multiplies the
    /// renderer's internal output by `pixel_ratio`.
    pixel_ratio: NonZeroU8,
    /// Bearing in degrees, clockwise from north (0 = north-up).
    bearing: f64,
    /// Pitch in degrees away from straight-down (0 = flat top-down view).
    pitch: f64,
    /// Overlay spec to composite for this render. An empty spec (no features)
    /// is the canonical "nothing to draw" and short-circuits to a plain render.
    overlays: Arc<OverlaySpec>,
}

impl RenderParams {
    /// Start a render request at `(lat, lon, zoom)` against `style`.
    /// Size defaults to 512×512×1; orientation defaults to north-up flat.
    #[must_use]
    pub fn new(style: impl Into<RenderStyle>, lat: f64, lon: f64, zoom: f64) -> Self {
        Self {
            style: style.into(),
            lat,
            lon,
            zoom,
            width: 512,
            height: 512,
            pixel_ratio: NonZeroU8::MIN,
            bearing: 0.0,
            pitch: 0.0,
            overlays: Arc::new(OverlaySpec::default()),
        }
    }

    /// Override output dimensions and pixel density.
    #[must_use]
    pub const fn with_size(mut self, width: u32, height: u32, pixel_ratio: NonZeroU8) -> Self {
        self.width = width;
        self.height = height;
        self.pixel_ratio = pixel_ratio;
        self
    }

    /// Override camera bearing (degrees clockwise from north) and pitch
    /// (degrees away from straight-down).
    #[must_use]
    pub const fn with_orientation(mut self, bearing: f64, pitch: f64) -> Self {
        self.bearing = bearing;
        self.pitch = pitch;
        self
    }

    /// Apply `spec` as ephemeral sources+layers for this render only.
    ///
    /// `Arc` because `RenderParams` is `Clone` and travels through the worker
    /// channel; the `GeoJSON` payload could be large.
    #[must_use]
    pub fn with_overlays(mut self, spec: Arc<OverlaySpec>) -> Self {
        self.overlays = spec;
        self
    }
}

/// The tile and static render pools.
///
/// Tile and static rendering share no renderer state, so each gets its own pool
/// with its own worker threads and request queue. The two are bundled here only
/// so [`StyleSources`](crate::styles::StyleSources) can enable or disable both at once.
#[derive(Debug, Clone)]
pub struct RenderPools {
    tile: RenderPool<TileWorker>,
    tile_size: TileSize,
    free: RenderPool<StaticWorker>,
}

impl RenderPools {
    /// Spawn both pools, each with `workers` threads, rendering tiles of `tile_size`.
    /// See [`RenderPool::new`].
    ///
    /// Each tile worker keeps up to `renderers_per_worker` renderers loaded, one per style
    /// and tile geometry.
    ///
    /// `ambient_cache_bytes` caps `MapLibre`'s cache of the resources renderers fetch
    /// over the network; `Some(0)` disables it and `None` keeps `MapLibre`'s default.
    ///
    /// # Errors
    ///
    /// Returns the OS error from [`thread::Builder::spawn`] if a worker thread
    /// cannot be started.
    pub fn new(
        workers: Option<NonZeroUsize>,
        tile_size: TileSize,
        renderers_per_worker: NonZeroUsize,
        ambient_cache_bytes: Option<u64>,
    ) -> Result<Self, std::io::Error> {
        Ok(Self {
            tile: RenderPool::new(workers, move || {
                TileWorker::new(renderers_per_worker).with_ambient_cache(ambient_cache_bytes)
            })?,
            tile_size,
            free: RenderPool::new(workers, move || StaticWorker::new(ambient_cache_bytes))?,
        })
    }

    /// Render a slippy tile of the pool's [`TileSize`] asynchronously.
    pub async fn render_tile(&self, style: impl Into<RenderStyle>, z: u8, x: u32, y: u32) -> Result<Image, StyleError> {
        self.render_tile_with_pixel_ratio(style, z, x, y, NonZeroU8::MIN).await
    }

    /// Render a slippy tile asynchronously at `pixel_ratio` times the pixels of [`Self::render_tile`].
    pub async fn render_tile_with_pixel_ratio(
        &self,
        style: impl Into<RenderStyle>,
        z: u8,
        x: u32,
        y: u32,
        pixel_ratio: NonZeroU8,
    ) -> Result<Image, StyleError> {
        self.render_tile_of_size(style, z, x, y, self.tile_size, pixel_ratio)
            .await
    }

    /// Render a slippy tile of `tile_size` instead of the pool's [`TileSize`], at `pixel_ratio` times its pixels.
    pub async fn render_tile_of_size(
        &self,
        style: impl Into<RenderStyle>,
        z: u8,
        x: u32,
        y: u32,
        tile_size: TileSize,
        pixel_ratio: NonZeroU8,
    ) -> Result<Image, StyleError> {
        self.tile
            .render(TileRequest {
                style: style.into(),
                z,
                x,
                y,
                tile_size,
                pixel_ratio,
            })
            .await
    }

    /// Render a free-camera image asynchronously.
    pub async fn render_static(&self, params: RenderParams) -> Result<Image, StyleError> {
        self.free.render(params).await
    }
}

/// A pool of worker threads that each own one [`Worker`].
///
/// Requests are dispatched over a bounded channel to whichever worker is free.
/// `Arc`-shared so the pool stays [`Clone`]; the last clone's `Drop` joins the
/// worker threads.
struct RenderPool<W: Worker> {
    inner: Arc<Inner<W::Request>>,
}

impl<W: Worker> Clone for RenderPool<W> {
    fn clone(&self) -> Self {
        Self {
            inner: Arc::clone(&self.inner),
        }
    }
}

impl<W: Worker> std::fmt::Debug for RenderPool<W> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RenderPool")
            .field("kind", &W::NAME)
            .finish_non_exhaustive()
    }
}

struct Inner<R> {
    requests: flume::Sender<Msg<R>>,
    workers: Vec<JoinHandle<()>>,
}

impl<R> Drop for Inner<R> {
    fn drop(&mut self) {
        for _ in 0..self.workers.len() {
            let _ = self.requests.send(Msg::Shutdown);
        }
        for handle in self.workers.drain(..) {
            let _ = handle.join();
        }
    }
}

enum Msg<R> {
    Render(R, oneshot::Sender<Result<Image, StyleError>>),
    Shutdown,
}

/// Per-worker queue depth.
/// Bounded so a stalled worker cannot accumulate unbounded latency.
///
/// Sized so that we have 2-4s of work remaining, depending on hardware.
const WORKER_QUEUE_DEPTH: usize = 512;

impl<W: Worker> RenderPool<W> {
    /// Spawn a pool with `workers` threads.
    ///
    /// `Some(n)` is used as-is with no upper cap. `None` uses the logical CPU
    /// count clamped to 2..=8.
    fn new<F>(workers: Option<NonZeroUsize>, new_worker: F) -> Result<Self, std::io::Error>
    where
        F: Fn() -> W + Clone + Send + 'static,
    {
        let workers = workers.unwrap_or_else(default_worker_count);
        let (requests, rx) = flume::bounded::<Msg<W::Request>>(workers.get() * WORKER_QUEUE_DEPTH);
        let mut handles = Vec::with_capacity(workers.get());
        for i in 0..workers.get() {
            let rx = rx.clone();
            let new_worker = new_worker.clone();
            let handle = thread::Builder::new()
                .name(format!("render-{}-{i}", W::NAME))
                .spawn(move || worker_loop(&rx, &new_worker))?;
            handles.push(handle);
        }

        info!(workers = workers.get(), kind = W::NAME, "Started style render pool");

        Ok(Self {
            inner: Arc::new(Inner {
                requests,
                workers: handles,
            }),
        })
    }

    /// Dispatch a request to a worker and await its rendered image.
    async fn render(&self, request: W::Request) -> Result<Image, StyleError> {
        let (response_tx, response_rx) = oneshot::channel();

        // Bounded channel: async send awaits when full instead of blocking the runtime.
        self.inner
            .requests
            .send_async(Msg::Render(request, response_tx))
            .await
            .map_err(|_err| StyleError::FailedToSendRequest)?;

        response_rx.await.map_err(|_err| StyleError::FailedToReceiveResponse)?
    }
}

fn default_worker_count() -> NonZeroUsize {
    const MIN: NonZeroUsize = NonZeroUsize::new(2).expect("2 != 0");
    const MAX: NonZeroUsize = NonZeroUsize::new(8).expect("8 != 0");
    thread::available_parallelism().unwrap_or(MIN).clamp(MIN, MAX)
}

fn worker_loop<W: Worker>(rx: &flume::Receiver<Msg<W::Request>>, new_worker: &dyn Fn() -> W) {
    let mut worker = new_worker();
    while let Ok(msg) = rx.recv() {
        match msg {
            Msg::Render(request, response) => {
                // A panic would take the worker with it and the pool never spawns another.
                // The renderer is rebuilt afterwards, which is what makes the unwind safe to catch.
                let result = match panic::catch_unwind(AssertUnwindSafe(|| worker.render(request))) {
                    Ok(result) => result,
                    Err(payload) => {
                        let message = payload
                            .downcast_ref::<&str>()
                            .copied()
                            .or_else(|| payload.downcast_ref::<String>().map(String::as_str))
                            .unwrap_or("non-string panic payload");
                        error!(
                            kind = W::NAME,
                            panic = message,
                            "Render worker panicked, replacing its renderer"
                        );
                        worker = new_worker();
                        Err(StyleError::RenderingPanicked)
                    }
                };
                let _ = response.send(result);
            }
            Msg::Shutdown => break,
        }
    }
}

/// A render backend bound to a single worker thread.
///
/// A [`RenderPool`] builds one `Worker` per thread (with its constructor) and feeds it
/// requests. Implementors own a `MapLibre` renderer, which is `!Send`, so it is
/// created on - and never leaves - its worker thread.
trait Worker: 'static {
    /// Short name for thread names and log fields (e.g. `tile`, `static`).
    const NAME: &'static str;
    /// The request payload this worker renders.
    type Request: Send + 'static;

    /// Render one request to an image.
    fn render(&mut self, request: Self::Request) -> Result<Image, StyleError>;
}

/// A slippy-tile render request.
struct TileRequest {
    style: RenderStyle,
    z: u8,
    x: u32,
    y: u32,
    tile_size: TileSize,
    pixel_ratio: NonZeroU8,
}

/// The output a tile renderer is built for. Each geometry needs its own renderer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Geometry {
    Tile(TileSize, NonZeroU8),
    /// `MapLibre` cannot zoom out below 0 (`RenderingError::TileZoomTooLow`), so the
    /// 256 px world tile is the 512 px one drawn at half the pixel ratio.
    World256(NonZeroU8),
}

impl Geometry {
    fn of(req: &TileRequest) -> Self {
        if req.z == 0 && req.tile_size == TileSize::Px256 {
            Self::World256(req.pixel_ratio)
        } else {
            Self::Tile(req.tile_size, req.pixel_ratio)
        }
    }

    fn renderer(self, ambient_cache_bytes: Option<u64>) -> ImageRenderer<Tile> {
        let (size, pixel_ratio) = match self {
            Self::Tile(size, ratio) => (size, f32::from(ratio.get())),
            Self::World256(ratio) => (TileSize::Px512, f32::from(ratio.get()) / 2.0),
        };
        renderer_builder(ambient_cache_bytes)
            .with_size(size.px(), size.px())
            .with_pixel_ratio(pixel_ratio)
            .build_tile_renderer()
    }
}

/// A renderer builder whose ambient cache holds up to `ambient_cache_bytes`
/// (`None` keeps `MapLibre`'s default, `Some(0)` disables it).
fn renderer_builder(ambient_cache_bytes: Option<u64>) -> ImageRendererBuilder {
    let builder = ImageRendererBuilder::default();
    match ambient_cache_bytes {
        Some(bytes) => builder.with_resource_options(ResourceOptions::default().with_maximum_cache_size(bytes)),
        None => builder,
    }
}

/// How many renderers a tile worker keeps loaded when none is configured.
pub const DEFAULT_RENDERERS_PER_WORKER: NonZeroUsize = NonZeroUsize::new(8).expect("8 != 0");

/// A tile renderer for one geometry with a style loaded.
struct TileSlot {
    style: RenderStyle,
    geometry: Geometry,
    renderer: ImageRenderer<Tile>,
}

/// Worker that renders slippy tiles via the tile renderer.
///
/// Keeps up to `capacity` renderers, one per style and geometry, most recently used first,
/// so mixed traffic does not reload a style on every request.
struct TileWorker {
    capacity: NonZeroUsize,
    ambient_cache_bytes: Option<u64>,
    slots: Vec<TileSlot>,
}

impl TileWorker {
    fn new(capacity: NonZeroUsize) -> Self {
        Self {
            capacity,
            ambient_cache_bytes: None,
            slots: Vec::new(),
        }
    }

    fn with_ambient_cache(mut self, ambient_cache_bytes: Option<u64>) -> Self {
        self.ambient_cache_bytes = ambient_cache_bytes;
        self
    }

    /// Moves the renderer for `style` and `geometry` to the front, loading it if needed.
    fn slot(&mut self, style: &RenderStyle, geometry: Geometry) -> Result<&mut TileSlot, StyleError> {
        if let Some(i) = self
            .slots
            .iter()
            .position(|s| s.geometry == geometry && &s.style == style)
        {
            // Move the hit to the front, keeping the others in most-recently-used order,
            // so the `truncate` below always drops the least recently used renderer.
            self.slots[..=i].rotate_right(1);
        } else {
            let mut renderer = geometry.renderer(self.ambient_cache_bytes);
            style.load(&mut renderer)?;
            self.slots.truncate(self.capacity.get() - 1);
            self.slots.insert(
                0,
                TileSlot {
                    style: style.clone(),
                    geometry,
                    renderer,
                },
            );
        }
        Ok(&mut self.slots[0])
    }
}

impl Worker for TileWorker {
    const NAME: &'static str = "tile";
    type Request = TileRequest;

    fn render(&mut self, req: TileRequest) -> Result<Image, StyleError> {
        self.slot(&req.style, Geometry::of(&req))?
            .renderer
            .render_tile(req.z, req.x, req.y)
            .map_err(StyleError::RenderingError)
    }
}

/// Worker that renders free-camera images via the static renderer.
#[derive(Default)]
struct StaticWorker {
    /// Rebuilt whenever the requested output geometry changes.
    current: Option<StaticRenderer>,
    ambient_cache_bytes: Option<u64>,
}

impl StaticWorker {
    fn new(ambient_cache_bytes: Option<u64>) -> Self {
        Self {
            current: None,
            ambient_cache_bytes,
        }
    }
}

impl Worker for StaticWorker {
    const NAME: &'static str = "static";
    type Request = RenderParams;

    fn render(&mut self, params: RenderParams) -> Result<Image, StyleError> {
        if !self.current.as_ref().is_some_and(|r| r.matches(&params)) {
            self.current = Some(StaticRenderer::new(
                params.width,
                params.height,
                params.pixel_ratio,
                self.ambient_cache_bytes,
            ));
        }
        self.current.as_mut().expect("just built").render(&params)
    }
}

/// Loads `style` into `renderer`, skipping the load if it is already the cached style.
///
/// `MapLibre` drops the active style the moment a new load begins, so a failed load
/// here (early `?` return) must leave the cache empty.
/// Otherwise the next request for the previously-loaded style would skip reloading
/// and render against the now-missing style.
fn load_style_cached<S>(
    renderer: &mut ImageRenderer<S>,
    cached: &mut Option<RenderStyle>,
    style: &RenderStyle,
) -> Result<(), StyleError> {
    if cached.as_ref() == Some(style) {
        return Ok(());
    }
    *cached = None;
    style.load(renderer)?;
    *cached = Some(style.clone());
    Ok(())
}

/// Applies an overlay to the renderer's style and removes it again on drop --
/// even on an early return or panic -- so the cached style returns to a clean
/// base for the next request.
struct RendererWithOverlay<'r> {
    renderer: &'r mut ImageRenderer<Static>,
    applied: Option<AppliedOverlay>,
}

impl<'r> RendererWithOverlay<'r> {
    /// Apply `spec` to `renderer`'s style. The overlay lives until the returned
    /// guard drops.
    fn apply(renderer: &'r mut ImageRenderer<Static>, spec: &OverlaySpec) -> Result<Self, StyleError> {
        let applied = {
            let mut style = renderer.style();
            apply_to_style(spec, &mut style).map_err(StyleError::OverlayApply)?
        };
        Ok(Self {
            renderer,
            applied: Some(applied),
        })
    }

    /// The renderer carrying the applied overlay, for issuing render calls.
    const fn renderer(&mut self) -> &mut ImageRenderer<Static> {
        self.renderer
    }
}

impl Drop for RendererWithOverlay<'_> {
    fn drop(&mut self) {
        if let Some(applied) = self.applied.take() {
            let mut style = self.renderer.style();
            applied.remove_from(&mut style);
        }
    }
}

/// A free-camera renderer pinned to a fixed output geometry, with its cached style.
struct StaticRenderer {
    renderer: ImageRenderer<Static>,
    width: u32,
    height: u32,
    pixel_ratio: NonZeroU8,
    loaded_style: Option<RenderStyle>,
}

impl StaticRenderer {
    fn new(width: u32, height: u32, pixel_ratio: NonZeroU8, ambient_cache_bytes: Option<u64>) -> Self {
        let w = NonZeroU32::new(width).unwrap_or(NonZeroU32::MIN);
        let h = NonZeroU32::new(height).unwrap_or(NonZeroU32::MIN);
        Self {
            renderer: renderer_builder(ambient_cache_bytes)
                .with_pixel_ratio(f32::from(pixel_ratio.get()))
                .with_size(w, h)
                .build_static_renderer(),
            width,
            height,
            pixel_ratio,
            loaded_style: None,
        }
    }

    /// Whether this renderer's build-time geometry matches `params`.
    fn matches(&self, params: &RenderParams) -> bool {
        self.width == params.width && self.height == params.height && self.pixel_ratio == params.pixel_ratio
    }

    fn render(&mut self, params: &RenderParams) -> Result<Image, StyleError> {
        load_style_cached(&mut self.renderer, &mut self.loaded_style, &params.style)?;
        let camera = CameraUpdate::new()
            .center(LatLng {
                lat: params.lat,
                lng: params.lon,
            })
            .zoom(params.zoom)
            .bearing(params.bearing)
            .pitch(params.pitch);

        let render_once = |r: &mut ImageRenderer<Static>| r.render_static(&camera).map_err(StyleError::RenderingError);

        if params.overlays.is_empty() {
            // No overlay: a single render captures the fully-tiled frame.
            return render_once(&mut self.renderer);
        }

        // The overlay's GeoJSON source only tiles once the pipeline has rendered
        // at least once; adding it before any render leaves it blank.
        let _ = render_once(&mut self.renderer);

        let mut overlay = RendererWithOverlay::apply(&mut self.renderer, &params.overlays)?;
        let renderer = overlay.renderer();

        // The source tiles synchronously, so this first render after `add_source`
        // already captures the overlay.
        render_once(renderer)
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};

    use rstest::rstest;

    use super::*;

    const POLY_STYLE: &str = r##"{
        "version": 8,
        "sources": {
            "poly": {
                "type": "geojson",
                "data": {
                    "type": "Feature",
                    "properties": {},
                    "geometry": {
                        "type": "Polygon",
                        "coordinates": [[[-10, -10], [10, -10], [10, 10], [-10, 10], [-10, -10]]]
                    }
                }
            }
        },
        "layers": [
            {"id": "bg", "type": "background", "paint": {"background-color": "#ffffff"}},
            {"id": "poly", "type": "fill", "source": "poly", "paint": {"fill-color": "#ff0000"}}
        ]
    }"##;

    fn write_style() -> tempfile::NamedTempFile {
        let style_file = tempfile::Builder::new()
            .suffix(".json")
            .tempfile()
            .expect("create style tempfile");
        std::fs::write(style_file.path(), POLY_STYLE).expect("write style");
        style_file
    }

    #[tokio::test]
    async fn concurrent_tile_renders_all_succeed() {
        let style_file = write_style();
        let pool = Arc::new(
            RenderPool::new(NonZeroUsize::new(4), || TileWorker::new(DEFAULT_RENDERERS_PER_WORKER))
                .expect("spawn render pool"),
        );
        let style = style_file.path().to_path_buf();

        let mut handles = Vec::new();
        for _ in 0..16 {
            let pool = Arc::clone(&pool);
            let style = style.clone();
            handles.push(tokio::spawn(async move {
                // The zoom-0 world tile always contains the origin polygon, so
                // every concurrent render produces the same non-blank image.
                pool.render(TileRequest {
                    style: style.into(),
                    z: 0,
                    x: 0,
                    y: 0,
                    tile_size: TileSize::Px512,
                    pixel_ratio: NonZeroU8::MIN,
                })
                .await
            }));
        }

        for h in handles {
            let image = h.await.expect("task").expect("render");
            let img = image.as_image();
            assert_eq!((img.width(), img.height()), (512, 512));
            let unique: std::collections::HashSet<_> = img.pixels().copied().collect();
            assert!(unique.len() > 1, "image is blank");
        }
    }

    #[tokio::test]
    async fn one_worker_renders_each_pixel_ratio_at_its_own_size() {
        let style_file = write_style();
        let pool = RenderPool::new(NonZeroUsize::new(1), || TileWorker::new(DEFAULT_RENDERERS_PER_WORKER))
            .expect("spawn render pool");
        let style = style_file.path().to_path_buf();

        for (pixel_ratio, px) in [(1, 512), (2, 1024), (1, 512), (3, 1536), (2, 1024)] {
            let image = pool
                .render(TileRequest {
                    style: style.clone().into(),
                    z: 0,
                    x: 0,
                    y: 0,
                    tile_size: TileSize::Px512,
                    pixel_ratio: NonZeroU8::new(pixel_ratio).expect("non-zero"),
                })
                .await
                .expect("render");
            let img = image.as_image();
            assert_eq!((img.width(), img.height()), (px, px), "@{pixel_ratio}x");
        }
    }

    #[tokio::test]
    async fn static_worker_renders_each_pixel_ratio_at_its_own_size() {
        let style_file = write_style();
        let pool = RenderPool::new(NonZeroUsize::new(1), || StaticWorker::new(None)).expect("spawn render pool");

        for (ratio, px) in [(1, 100), (1, 100), (2, 200), (1, 100)] {
            let pixel_ratio = NonZeroU8::new(ratio).expect("non-zero");
            let params =
                RenderParams::new(style_file.path().to_path_buf(), 0.0, 0.0, 0.0).with_size(100, 100, pixel_ratio);
            let image = pool.render(params).await.expect("render");
            let img = image.as_image();
            assert_eq!((img.width(), img.height()), (px, px), "@{pixel_ratio}x");
        }
    }

    #[rstest]
    #[case::px512_world(TileSize::Px512, 1, 0, 512)]
    #[case::px512_at_2x(TileSize::Px512, 2, 1, 1024)]
    #[case::px256(TileSize::Px256, 1, 1, 256)]
    #[case::px256_at_2x(TileSize::Px256, 2, 1, 512)]
    #[case::px256_world(TileSize::Px256, 1, 0, 256)]
    #[case::px256_world_at_3x(TileSize::Px256, 3, 0, 768)]
    #[tokio::test]
    async fn a_tile_is_its_size_times_its_pixel_ratio(
        #[case] tile_size: TileSize,
        #[case] pixel_ratio: u8,
        #[case] z: u8,
        #[case] px: u32,
    ) {
        let style_file = write_style();
        let pool = RenderPool::new(NonZeroUsize::new(1), || TileWorker::new(DEFAULT_RENDERERS_PER_WORKER))
            .expect("spawn render pool");

        let image = pool
            .render(TileRequest {
                style: style_file.path().to_path_buf().into(),
                z,
                x: 0,
                y: 0,
                tile_size,
                pixel_ratio: NonZeroU8::new(pixel_ratio).expect("non-zero"),
            })
            .await
            .expect("render");

        let img = image.as_image();
        assert_eq!((img.width(), img.height()), (px, px));
    }

    const PX512: Geometry = Geometry::Tile(TileSize::Px512, NonZeroU8::MIN);

    #[rstest]
    #[case::a_new_style_goes_first(&[0, 1], &[1, 0])]
    #[case::a_hit_moves_to_the_front(&[0, 1, 0], &[0, 1])]
    #[case::the_least_recently_used_is_dropped(&[0, 1, 2], &[2, 1])]
    #[case::a_hit_outlives_an_older_style(&[0, 1, 0, 2], &[2, 0])]
    fn a_full_worker_keeps_the_most_recently_used_styles(#[case] requested: &[usize], #[case] kept: &[usize]) {
        let styles: [_; 3] = std::array::from_fn(|_| write_style());
        let mut worker = TileWorker::new(NonZeroUsize::new(2).expect("2 != 0"));

        for &i in requested {
            worker
                .slot(&styles[i].path().to_path_buf().into(), PX512)
                .expect("load style");
        }

        let loaded: Vec<_> = worker.slots.iter().map(|s| s.style.clone()).collect();
        let expected: Vec<RenderStyle> = kept.iter().map(|&i| styles[i].path().to_path_buf().into()).collect();
        assert_eq!(loaded, expected);
    }

    #[test]
    fn each_geometry_of_a_style_has_its_own_renderer() {
        let style = write_style();
        let mut worker = TileWorker::new(DEFAULT_RENDERERS_PER_WORKER);
        let two_x = Geometry::Tile(TileSize::Px512, NonZeroU8::new(2).expect("2 != 0"));

        let style = style.path().to_path_buf().into();
        worker.slot(&style, PX512).expect("load style");
        worker.slot(&style, two_x).expect("load style");

        let geometries: Vec<_> = worker.slots.iter().map(|s| s.geometry).collect();
        assert_eq!(geometries, [two_x, PX512]);
    }

    #[test]
    fn a_style_that_fails_to_load_takes_no_slot() {
        let mut worker = TileWorker::new(DEFAULT_RENDERERS_PER_WORKER);

        let result = worker.slot(&PathBuf::from("/nonexistent/style.json").into(), PX512);

        assert!(result.is_err());
        assert!(worker.slots.is_empty());
    }

    struct FlakyWorker;

    impl Default for FlakyWorker {
        fn default() -> Self {
            WORKERS_BUILT.fetch_add(1, Ordering::SeqCst);
            Self
        }
    }

    static WORKERS_BUILT: AtomicUsize = AtomicUsize::new(0);

    impl Worker for FlakyWorker {
        const NAME: &'static str = "flaky";
        type Request = bool;

        #[expect(clippy::panic_in_result_fn, reason = "the panic is what this worker is for")]
        fn render(&mut self, should_panic: bool) -> Result<Image, StyleError> {
            assert!(!should_panic, "renderer blew up");
            Err(StyleError::RenderingIsDisabled)
        }
    }

    #[tokio::test]
    async fn a_panicking_request_does_not_take_the_worker_with_it() {
        let pool = RenderPool::new(NonZeroUsize::new(1), FlakyWorker::default).expect("spawn render pool");
        let first = pool.render(false).await;
        assert!(matches!(first, Err(StyleError::RenderingIsDisabled)), "{first:?}");
        let before = WORKERS_BUILT.load(Ordering::SeqCst);

        let panicked = pool.render(true).await;
        assert!(matches!(panicked, Err(StyleError::RenderingPanicked)), "{panicked:?}");

        let after = pool.render(false).await;
        assert!(matches!(after, Err(StyleError::RenderingIsDisabled)), "{after:?}");
        assert_eq!(WORKERS_BUILT.load(Ordering::SeqCst), before + 1);
    }

    #[tokio::test]
    async fn static_render_honours_custom_size() {
        let style_file = write_style();
        let pool = RenderPool::new(NonZeroUsize::new(1), StaticWorker::default).expect("spawn render pool");
        let style = style_file.path().to_path_buf();

        let params = RenderParams::new(style, 0.0, 0.0, 2.0).with_size(256, 384, NonZeroU8::MIN);
        let image = pool.render(params).await.expect("render");

        let img = image.as_image();
        assert_eq!((img.width(), img.height()), (256, 384));
        let unique: std::collections::HashSet<_> = img.pixels().copied().collect();
        assert!(unique.len() > 1, "image is blank");
    }

    #[tokio::test]
    async fn a_style_in_memory_renders_as_its_file_does() {
        let style_file = write_style();
        let pool = RenderPool::new(NonZeroUsize::new(1), StaticWorker::default).expect("spawn render pool");

        let from_file = pool
            .render(RenderParams::new(style_file.path().to_path_buf(), 0.0, 0.0, 2.0))
            .await
            .expect("render the file");
        let in_memory = pool
            .render(RenderParams::new(RenderStyle::Json(POLY_STYLE.into()), 0.0, 0.0, 2.0))
            .await
            .expect("render the document");

        assert_eq!(in_memory.as_image(), from_file.as_image());
    }
}