mln-rs-engine 0.0.23

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
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
// The downloads of a database's offline regions live with the database, on
// the thread that owns both (the database's worker): `Downloads` keeps one
// `OfflineDownload` per region, which works on the database it's handed.
// What a download sets off comes back as a task on that thread (`Post`),
// which names the region and the request: a request's response, or the
// queued check of a resource the region may hold. A request dropped from the
// download, as a pause drops them all, finds nothing when its task comes.
//
// The observer is called while the download works; it reaches the download
// again only through a task.

use std::collections::VecDeque;
use std::collections::hash_map::Entry;
use std::sync::Arc;

use geo_types::Geometry;
use mln_style::Parser;
use mln_style::collections::VecMap;
use mln_style::crs::{WorldBox, WorldMapping};
use mln_style::feature::Feature;
use mln_style::hash::{HashMap, HashSet};
use mln_style::i18n::glyph_range_is_entirely_locally_generated;
use mln_style::layer::SourceKind;
use mln_style::range::Range;
use mln_style::source::SourceTypeInfo;
use mln_style::sources::geojson::features_to_world;
use mln_style::tile_id::CanonicalTileID;
use mln_style::tileset::{Tileset, VectorEncoding};

use crate::registry::Registry;
use crate::source::OfflineResources;
use crate::storage::chrono::now;
use crate::storage::constants::DEFAULT_MAXIMUM_CONCURRENT_REQUESTS;
use crate::storage::offline::{
    OfflineRegionDefinition, OfflineRegionDownloadState, OfflineRegionObserver, OfflineRegionStatus,
};
use crate::storage::offline_database::{DatabaseError, OfflineDatabase};
use crate::storage::resource::{Priority, TileAddressing, TileFormat, Usage};
use crate::storage::response::{Caching, Reason, ResourceError};
use crate::storage::{FileSource, Kind, LoadingMethod, Request, Resource, Response};
use crate::text::glyph::{
    GLYPH_RANGES_PER_FONT_STACK, GLYPHS_PER_GLYPH_RANGE, GlyphID, NON_IDEOGRAPH_GLYPH_RANGES_PER_FONT_STACK,
    glyph_range,
};
use crate::tile::tile_range::TileRange;
use crate::tile_store::tile_cover::{TileCover, covering_zoom_level, tile_count_bounds, tile_count_geometry};

const RESOURCES_BATCH_SIZE: usize = 64;
const MARK_BATCH_SIZE: usize = 200;

// Generic functions

fn covering_zoom_range(
    definition: &OfflineRegionDefinition,
    round_zoom: bool,
    tile_size: u16,
    zoom_range: Range<u8>,
) -> Range<u8> {
    let min_z = covering_zoom_level(definition.min_zoom(), round_zoom, tile_size).max(i32::from(zoom_range.min));
    let max_z = covering_zoom_level(definition.max_zoom(), round_zoom, tile_size).min(i32::from(zoom_range.max));

    debug_assert!((0..i32::from(u8::MAX)).contains(&min_z));
    debug_assert!((0..i32::from(u8::MAX)).contains(&max_z));
    Range::new(min_z as u8, max_z as u8)
}

/// Where a region lies in the world square of a world that doesn't wrap.
enum InWorld {
    /// A tile pyramid's bounds, as the rectangle around them.
    Box(WorldBox),
    /// A geometry's, if any of it has a place there.
    Geometry(Option<Geometry<f64>>),
}

impl InWorld {
    /// Where the region lies in the world square of `world`, if the world
    /// doesn't wrap; `None` in one that does, which covers it in lng/lat,
    /// across the antimeridian and in its world copies.
    fn new(definition: &OfflineRegionDefinition, world: &WorldMapping) -> Option<Self> {
        if world.wraps() {
            return None;
        }
        Some(match definition {
            OfflineRegionDefinition::TilePyramid(reg) => InWorld::Box(world.lng_lat_box_to_world_box(&reg.bounds)),
            OfflineRegionDefinition::Geometry(reg) => {
                let features = features_to_world(vec![Feature::new(reg.geometry.clone())], world);
                InWorld::Geometry(features.into_iter().next().and_then(|feature| feature.geometry))
            }
        })
    }

    /// Calls `f` with each tile of the square that the region covers at
    /// zoom `z`.
    fn cover(&self, z: u8, f: &mut impl FnMut(CanonicalTileID)) {
        match self {
            InWorld::Box(world_box) => {
                let range = TileRange::from_world_box(world_box, z, z);
                if range.zoom_range.min > range.zoom_range.max {
                    return;
                }
                for x in range.range.min.x..=range.range.max.x {
                    for y in range.range.min.y..=range.range.max.y {
                        f(CanonicalTileID::new(z, x, y));
                    }
                }
            }
            InWorld::Geometry(Some(geometry)) => {
                for tile in TileCover::new_from_world_geometry(geometry, z) {
                    if tile.wrap == 0 {
                        f(tile.canonical);
                    }
                }
            }
            InWorld::Geometry(None) => {}
        }
    }

    /// How many tiles of the square the region covers at zoom `z`; a box's
    /// are counted, not walked, and as many as a `u64` holds at most.
    fn count(&self, z: u8) -> u64 {
        if let InWorld::Box(world_box) = self {
            let range = TileRange::from_world_box(world_box, z, z);
            if range.zoom_range.min > range.zoom_range.max {
                return 0;
            }
            // From zoom 32 a row of the square has 2^32 tiles, one more than
            // a u32 holds.
            let tiles = |min: u32, max: u32| u64::from(max) - u64::from(min) + 1;
            let (min, max) = (range.range.min, range.range.max);
            return tiles(min.x, max.x).saturating_mul(tiles(min.y, max.y));
        }
        let mut count = 0;
        self.cover(z, &mut |_| count += 1);
        count
    }
}

/// Calls `f` with the tiles that the region covers in the grid that `world`
/// maps lng/lat to.
fn tile_cover(
    definition: &OfflineRegionDefinition,
    world: &WorldMapping,
    round_zoom: bool,
    tile_size: u16,
    zoom_range: Range<u8>,
    mut f: impl FnMut(CanonicalTileID),
) {
    let clamped_zoom_range = covering_zoom_range(definition, round_zoom, tile_size, zoom_range);
    let in_world = InWorld::new(definition, world);

    for z in clamped_zoom_range.min..=clamped_zoom_range.max {
        if let Some(in_world) = &in_world {
            in_world.cover(z, &mut f);
            continue;
        }
        let cover = match definition {
            OfflineRegionDefinition::TilePyramid(reg) => Some(TileCover::new_from_bounds(&reg.bounds, z)),
            OfflineRegionDefinition::Geometry(reg) => TileCover::new_from_geometry(&reg.geometry, z).ok(),
        };
        if let Some(mut cover) = cover {
            while cover.has_next() {
                if let Some(tile) = cover.next() {
                    f(tile.canonical);
                }
            }
        }
    }
}

/// How many tiles the region covers in the grid that `world` maps lng/lat
/// to.
fn tile_count(
    definition: &OfflineRegionDefinition,
    world: &WorldMapping,
    round_zoom: bool,
    tile_size: u16,
    zoom_range: Range<u8>,
) -> u64 {
    let clamped_zoom_range = covering_zoom_range(definition, round_zoom, tile_size, zoom_range);
    let in_world = InWorld::new(definition, world);

    let mut result: u64 = 0;
    for z in clamped_zoom_range.min..=clamped_zoom_range.max {
        result += match (&in_world, definition) {
            (Some(in_world), _) => in_world.count(z),
            (None, OfflineRegionDefinition::TilePyramid(reg)) => tile_count_bounds(&reg.bounds, z),
            (None, OfflineRegionDefinition::Geometry(reg)) => tile_count_geometry(&reg.geometry, z).unwrap_or(0),
        };
    }

    result
}

/// A task for the thread that owns a database and its downloads.
pub(crate) type DownloadTask = Box<dyn FnOnce(&mut OfflineDatabase, &mut Downloads) + Send>;

/// Hands a task to the thread that owns the database and its downloads,
/// which runs it after what it runs now. Any thread may call it.
pub(crate) type Post = Arc<dyn Fn(DownloadTask) + Send + Sync>;

/// The downloads of a database's offline regions, by region id, on the
/// thread that owns the database.
pub struct Downloads {
    downloads: HashMap<i64, OfflineDownload>,
    network: Option<Arc<dyn FileSource>>,
    post: Post,
    registry: Arc<Registry>,
}

impl Downloads {
    /// Downloads that load through `network`, come back through `post`, and
    /// read their styles against `registry`.
    #[must_use]
    pub fn new(network: Option<Arc<dyn FileSource>>, post: Post, registry: Arc<Registry>) -> Self {
        Downloads { downloads: HashMap::default(), network, post, registry }
    }

    /// The download of the region `region_id`, made at its first use. Fails
    /// without a network, and for a region that the database doesn't have.
    pub(crate) fn download(
        &mut self,
        db: &mut OfflineDatabase,
        region_id: i64,
    ) -> Result<&mut OfflineDownload, DatabaseError> {
        match self.downloads.entry(region_id) {
            Entry::Occupied(download) => Ok(download.into_mut()),
            Entry::Vacant(entry) => {
                let Some(network) = &self.network else {
                    return Err(DatabaseError::Failed("Network file source unavailable.".to_owned()));
                };
                let definition = db.region(region_id)?.ok_or(DatabaseError::RegionNotFound(region_id))?.definition;
                let download = OfflineDownload::new(
                    region_id,
                    definition,
                    Arc::clone(network),
                    Arc::clone(&self.post),
                    Arc::clone(&self.registry),
                );
                Ok(entry.insert(download))
            }
        }
    }

    /// Adds a download that was made apart, in place of the region's.
    pub fn insert(&mut self, download: OfflineDownload) {
        self.downloads.insert(download.id, download);
    }

    /// The download of `region_id`, if it has one.
    #[cfg(test)]
    pub(crate) fn get_mut(&mut self, region_id: i64) -> Option<&mut OfflineDownload> {
        self.downloads.get_mut(&region_id)
    }

    /// Stops and forgets the download of `region_id`.
    pub(crate) fn remove(&mut self, region_id: i64) -> Option<OfflineDownload> {
        self.downloads.remove(&region_id)
    }

    /// A response to the request `request` of the region's download.
    fn on_response(&mut self, db: &mut OfflineDatabase, region_id: i64, request: u64, response: Response) {
        if let Some(download) = self.downloads.get_mut(&region_id) {
            download.on_online_response(db, request, response);
        }
    }

    /// The queued check of a resource that the region's download needs.
    fn on_ensure(&mut self, db: &mut OfflineDatabase, region_id: i64, request: u64) {
        if let Some(download) = self.downloads.get_mut(&region_id) {
            download.ensure_resource_task(db, request);
        }
    }
}

/// The default observer.
struct NullObserver;

impl OfflineRegionObserver for NullObserver {}

/// What a downloaded resource lists, which the download goes on to load.
#[derive(Clone)]
enum Then {
    /// Nothing: a resource that lists no others.
    Nothing,
    /// The style, which lists the sources, glyphs and sprites.
    Style,
    /// A source's TileJSON, which lists its tiles.
    Source { url: String, source: mln_style::Source, tile_size: u16, round_zoom: bool },
}

impl Then {
    fn reads(&self) -> bool {
        !matches!(self, Then::Nothing)
    }
}

/// A resource the download waits for.
enum Pending {
    /// Its check of what the region holds is queued.
    Queued { resource: Resource, then: Then },
    /// It loads from the network, revalidating the stored copy, if any, with
    /// its stored size.
    Loading { _request: Request, resource: Resource, then: Then, stale: Option<(Response, u64)> },
}

/// The tiles of a tileset left to load, in order, and how to request them.
struct QueuedTileset {
    url_template: String,
    addressing: TileAddressing,
    format: TileFormat,
    tiles: VecDeque<CanonicalTileID>,
}

/// The download of an offline region's resources into the database.
pub struct OfflineDownload {
    id: i64,
    definition: OfflineRegionDefinition,
    network: Arc<dyn FileSource>,
    post: Post,
    registry: Arc<Registry>,
    /// How lng/lat maps to the tiles of the region's style, once it's read.
    world: WorldMapping,
    /// The most requests the download has in flight at once.
    maximum_concurrent_requests: u32,
    status: OfflineRegionStatus,
    observer: Box<dyn OfflineRegionObserver>,
    /// The resources it waits for, by request id.
    requests: VecMap<u64, Pending>,
    next_request_id: u64,
    required_source_urls: HashSet<String>,
    /// The resources other than tiles left to load, the next one last. They
    /// load before the tiles.
    resources_remaining: Vec<Resource>,
    /// The tilesets with tiles left to load, in order. A tile's resource is
    /// made as it loads: a region may cover millions of tiles.
    tiles_remaining: VecDeque<QueuedTileset>,
    resources_to_be_marked_as_used: Vec<Resource>,
    buffer: Vec<(Resource, Response)>,
}

impl OfflineDownload {
    /// The download of the region `id`, which loads through `network`, comes
    /// back through `post`, and reads the region's style against `registry`.
    #[must_use]
    pub fn new(
        id: i64,
        definition: OfflineRegionDefinition,
        network: Arc<dyn FileSource>,
        post: Post,
        registry: Arc<Registry>,
    ) -> Self {
        OfflineDownload {
            id,
            definition,
            network,
            post,
            registry,
            world: WorldMapping::default(),
            maximum_concurrent_requests: DEFAULT_MAXIMUM_CONCURRENT_REQUESTS,
            status: OfflineRegionStatus::default(),
            observer: Box::new(NullObserver),
            requests: VecMap::new(),
            next_request_id: 0,
            required_source_urls: HashSet::default(),
            resources_remaining: Vec::new(),
            tiles_remaining: VecDeque::new(),
            resources_to_be_marked_as_used: Vec::new(),
            buffer: Vec::new(),
        }
    }

    /// Sets the most requests the download has in flight at once.
    #[cfg(test)]
    pub(crate) fn set_maximum_concurrent_requests(&mut self, maximum: u32) {
        self.maximum_concurrent_requests = maximum;
    }

    /// Sets the download's observer, or the default one that ignores
    /// everything.
    pub fn set_observer(&mut self, observer: Option<Box<dyn OfflineRegionObserver>>) {
        self.observer = observer.unwrap_or_else(|| Box::new(NullObserver));
    }

    fn notify_status_changed(&self) {
        self.observer.status_changed(self.status);
    }

    fn next_request(&mut self) -> u64 {
        let id = self.next_request_id;
        self.next_request_id += 1;
        id
    }

    /// Starts or stops the download.
    pub fn set_state(&mut self, state: OfflineRegionDownloadState) {
        if self.status.download_state == state {
            return;
        }
        self.status.download_state = state;
        if state == OfflineRegionDownloadState::Active {
            self.activate_download();
        } else {
            self.deactivate_download();
        }
        self.notify_status_changed();
    }

    /// The download's status: while it's active, what it found so far, else
    /// what the region holds of what its stored style lists.
    #[must_use]
    pub(crate) fn status(&self, db: &mut OfflineDatabase) -> OfflineRegionStatus {
        if self.status.download_state == OfflineRegionDownloadState::Active {
            return self.status;
        }

        let Ok(mut result) = db.region_completed_status(self.id) else {
            // We can't find this offline region because the database is
            // unavailable, or the download does not exist.
            return OfflineRegionStatus::default();
        };

        result.required_resource_count += 1;
        let style_response = db.get(&Resource::style(self.definition.style_url()));
        let mut parser = Parser::new(self.registry.style());
        // A download reports a style it can't read, and the count stays
        // imprecise.
        let Some(style_data) = style_response.and_then(|response| response.data) else {
            return result;
        };
        if parser.parse(&String::from_utf8_lossy(&style_data)).is_err() {
            return result;
        }

        result.required_resource_count_is_precise = true;
        let world = self.registry.style().world(parser.projection());

        for source in &parser.sources {
            let record = source.clone();
            let Some(source_type) = self.registry.source_type(record.info().name) else { continue };
            let (tileset, tile_size, round_zoom) = match source_type.offline(&record) {
                OfflineResources::None => continue,
                OfflineResources::Source { .. } | OfflineResources::Image { .. } => {
                    result.required_resource_count += 1;
                    continue;
                }
                // A source without tile URLs has no tiles to download.
                OfflineResources::Tiles { tileset, tile_size, round_zoom } => (Some(tileset), tile_size, round_zoom),
                OfflineResources::TileJson { url, tile_size, round_zoom } => {
                    result.required_resource_count += 1;
                    let source_response = db.get(&Resource::source(&url));
                    let tileset = source_response
                        .and_then(|response| response.data)
                        .and_then(|data| source_type.offline_tileset(&record, &data).ok());
                    // As a download does, count no tiles for a TileJSON that
                    // is missing, can't be read, or has no tile URLs, and
                    // leave the count imprecise.
                    if tileset.as_ref().is_none_or(|tileset| tileset.tiles.is_empty()) {
                        result.required_resource_count_is_precise = false;
                    }
                    (tileset, tile_size, round_zoom)
                }
            };
            if let Some(tileset) = tileset.filter(|tileset| !tileset.tiles.is_empty()) {
                let count = tile_count(&self.definition, &world, round_zoom, tile_size, tileset.zoom_range);
                result.required_tile_count += count;
                result.required_resource_count += count;
            }
        }

        if !parser.glyph_url.is_empty() {
            let ttf_count = parser.font_faces.as_ref().map_or(0, |faces| faces.len() as u64); // custom faces
            let per_font_stack = if self.definition.include_ideographs() {
                u64::from(GLYPH_RANGES_PER_FONT_STACK) + ttf_count
            } else {
                u64::from(NON_IDEOGRAPH_GLYPH_RANGES_PER_FONT_STACK) + ttf_count
            };
            result.required_resource_count += parser.font_stacks().len() as u64 * per_font_stack;
        }

        if !parser.sprites.is_empty() {
            result.required_resource_count += 4 * parser.sprites.len() as u64;
        }

        result
    }

    fn activate_download(&mut self) {
        self.status = OfflineRegionStatus::default();
        self.status.download_state = OfflineRegionDownloadState::Active;
        self.status.required_resource_count += 1;

        let mut style_resource = Resource::style(self.definition.style_url());
        style_resource.set_priority(Priority::Low);
        style_resource.set_usage(Usage::Offline);
        self.ensure_resource(style_resource, Then::Style);
    }

    /// Reads what a downloaded style or TileJSON lists, and queues it.
    fn read(&mut self, then: &Then, response: &Response) -> Result<(), String> {
        match then {
            Then::Nothing => Ok(()),
            Then::Style => self.on_style_response(response),
            Then::Source { url, source, tile_size, round_zoom } => {
                let Some(data) = &response.data else {
                    return Err("the TileJSON has no content".to_owned());
                };
                let source_type = self.registry.source_type(source.info().name);
                let source_type = source_type.ok_or_else(|| "a source of a type the registry lacks".to_owned())?;
                let tileset = source_type.offline_tileset(source, data)?;
                if tileset.tiles.is_empty() {
                    return Err("the TileJSON has no tile URLs".to_owned());
                }
                self.queue_tiles(source.info(), *tile_size, *round_zoom, &tileset);
                if self.required_source_urls.remove(url) && self.required_source_urls.is_empty() {
                    self.status.required_resource_count_is_precise = true;
                }
                Ok(())
            }
        }
    }

    /// Queues the resources that the style lists.
    fn on_style_response(&mut self, style_response: &Response) -> Result<(), String> {
        let Some(style_data) = &style_response.data else {
            return Err("the style has no content".to_owned());
        };
        let mut parser = Parser::new(self.registry.style());
        parser.parse(&String::from_utf8_lossy(style_data)).map_err(|error| error.to_string())?;
        self.status.required_resource_count_is_precise = true;
        self.world = self.registry.style().world(parser.projection());

        for source in &parser.sources {
            let record = source.clone();
            let Some(source_type) = self.registry.source_type(record.info().name) else { continue };
            match source_type.offline(&record) {
                OfflineResources::None => {}
                OfflineResources::Tiles { tileset, tile_size, round_zoom } => {
                    self.queue_tiles(record.info(), tile_size, round_zoom, &tileset);
                }
                OfflineResources::TileJson { url, tile_size, round_zoom } => {
                    self.status.required_resource_count_is_precise = false;
                    self.status.required_resource_count += 1;
                    self.required_source_urls.insert(url.clone());

                    let mut source_resource = Resource::source(&url);
                    source_resource.set_priority(Priority::Low);
                    source_resource.set_usage(Usage::Offline);
                    self.ensure_resource(source_resource, Then::Source { url, source: record, tile_size, round_zoom });
                }
                OfflineResources::Source { url } => self.queue_resource(Resource::source(&url)),
                OfflineResources::Image { url } => {
                    if !url.is_empty() {
                        self.queue_resource(Resource::image(&url));
                    }
                }
            }
        }

        if !parser.glyph_url.is_empty() {
            let include_ideographs = self.definition.include_ideographs();
            for font_stack in parser.font_stacks() {
                for i in 0..GLYPH_RANGES_PER_FONT_STACK {
                    // Only skip a range when every codepoint in it can be
                    // generated locally; some ranges (e.g. 0xFF00) are mixed.
                    let start = (i * GLYPHS_PER_GLYPH_RANGE) as u16;
                    if include_ideographs || !glyph_range_is_entirely_locally_generated(start) {
                        let range = glyph_range(GlyphID::from(start));
                        self.queue_resource(Resource::glyphs(
                            &parser.glyph_url,
                            &font_stack,
                            (range.first, range.second),
                        ));
                    }
                    if let Some(faces) = &parser.font_faces {
                        for face in faces.iter() {
                            self.queue_resource(Resource::font_face(&face.url));
                        }
                    }
                }
            }
        }

        if !parser.sprites.is_empty() {
            // Always request 1x and @2x sprite images for portability.
            for sprite in &parser.sprites {
                let sprite_url = &sprite.sprite_url;
                self.queue_resource(Resource::sprite_image(sprite_url, 1.0));
                self.queue_resource(Resource::sprite_image(sprite_url, 2.0));
                self.queue_resource(Resource::sprite_json(sprite_url, 1.0));
                self.queue_resource(Resource::sprite_json(sprite_url, 2.0));
            }
        }
        Ok(())
    }

    // Fill up our own request queue by requesting the next few resources.
    // This is called when activating the download, or when a request
    // completes successfully.
    //
    // Note "successfully"; it's not called when a requests receives an
    // error. A request that errors will be retried after some delay. So in
    // that sense it's still "active" and consuming resources, notably the
    // request object, its timer, and network resources when the timer fires.
    //
    // We could try to squeeze in subsequent requests while we wait for the
    // errored request to retry. But that risks overloading the upstream
    // request queue -- defeating our own metering -- if there are a lot of
    // errored requests that all come up for retry at the same time. And many
    // times, the cause of a request error will apply to many requests of the
    // same type. For instance if a server is unreachable, all the requests
    // to that host are going to error. In that case, continuing to try
    // subsequent resources after the first few errors is fruitless anyway.
    fn continue_download(&mut self, db: &mut OfflineDatabase) {
        if !self.is_active() {
            return;
        }

        if self.nothing_remains() {
            // Flush pending buffers.
            self.flush_resources_buffer(db);
            if self.status.complete() {
                self.mark_pending_used_resources(db);
                self.set_state(OfflineRegionDownloadState::Inactive);
                return;
            }
        }

        if self.resources_to_be_marked_as_used.len() >= MARK_BATCH_SIZE {
            self.mark_pending_used_resources(db);
        }

        while self.requests.len() < self.maximum_concurrent_requests as usize {
            let Some(resource) = self.resources_remaining.pop().or_else(|| self.next_tile()) else {
                break;
            };
            self.ensure_resource(resource, Then::Nothing);
        }
    }

    fn deactivate_download(&mut self) {
        self.required_source_urls.clear();
        self.resources_remaining.clear();
        self.tiles_remaining.clear();
        self.requests.clear();
        self.buffer.clear();
    }

    fn is_active(&self) -> bool {
        self.status.download_state == OfflineRegionDownloadState::Active
    }

    fn flush_resources_buffer(&mut self, db: &mut OfflineDatabase) {
        if self.buffer.is_empty() {
            return;
        }
        db.put_region_resources(self.id, &self.buffer, &mut self.status);
        self.buffer.clear();
        self.notify_status_changed();
    }

    fn queue_resource(&mut self, mut resource: Resource) {
        resource.set_priority(Priority::Low);
        resource.set_usage(Usage::Offline);
        self.status.required_resource_count += 1;
        if resource.kind == Kind::Tile {
            self.status.required_tile_count += 1;
        }
        self.resources_remaining.push(resource);
    }

    fn nothing_remains(&self) -> bool {
        self.resources_remaining.is_empty() && self.tiles_remaining.is_empty()
    }

    /// The resource of the next tile left to load, taken from the queue.
    fn next_tile(&mut self) -> Option<Resource> {
        let tileset = self.tiles_remaining.front_mut()?;
        let tile = tileset.tiles.pop_front()?;
        let mut resource = Resource::tile(
            &tileset.url_template,
            self.definition.pixel_ratio(),
            tile.x as i32,
            tile.y as i32,
            tile.z as i8,
            tileset.addressing,
            tileset.format,
            LoadingMethod::ALL,
        );
        if tileset.tiles.is_empty() {
            self.tiles_remaining.pop_front();
        }
        resource.set_priority(Priority::Low);
        resource.set_usage(Usage::Offline);
        Some(resource)
    }

    /// Queues the tiles of `tileset`, of a source of type `source`, that cover
    /// the region, at the zoom level nearest each of its zooms if
    /// `round_zoom`.
    fn queue_tiles(&mut self, source: SourceTypeInfo, tile_size: u16, round_zoom: bool, tileset: &Tileset) {
        // A source without tile URLs has no tiles to download.
        let Some(url_template) = tileset.tiles.first() else {
            return;
        };
        let format = match source.layer_kind {
            SourceKind::Geometry if tileset.vector_encoding == Some(VectorEncoding::Mlt) => TileFormat::Mlt,
            SourceKind::Geometry => TileFormat::Mvt,
            SourceKind::None | SourceKind::Raster | SourceKind::RasterDem | SourceKind::Any => TileFormat::Image,
        };
        let world = &self.world;
        // A tile's `{bbox}` is its box in the tile matrix set of the style's
        // world, as a map drawn in it asks for the tile.
        let addressing = TileAddressing { scheme: tileset.scheme, tile_matrix_set: world.tile_matrix_set() };
        let mut tiles = VecDeque::new();
        tile_cover(&self.definition, world, round_zoom, tile_size, tileset.zoom_range, |tile| tiles.push_back(tile));
        let count = tiles.len() as u64;
        self.status.required_resource_count += count;
        self.status.required_tile_count += count;
        // `next_tile` takes a tileset off the queue with its last tile.
        if !tiles.is_empty() {
            self.tiles_remaining.push_back(QueuedTileset {
                url_template: url_template.clone(),
                addressing,
                format,
                tiles,
            });
        }
    }

    fn mark_pending_used_resources(&mut self, db: &mut OfflineDatabase) {
        db.mark_used_resources(self.id, &self.resources_to_be_marked_as_used);
        self.resources_to_be_marked_as_used.clear();
    }

    /// Queues the check of `resource` against what the region holds, which
    /// loads it unless the region holds a usable copy.
    fn ensure_resource(&mut self, resource: Resource, then: Then) {
        debug_assert_eq!(resource.priority, Priority::Low);
        debug_assert_eq!(resource.usage, Usage::Offline);

        let request = self.next_request();
        self.requests.insert(request, Pending::Queued { resource, then });
        let region = self.id;
        (self.post)(Box::new(move |db, downloads| downloads.on_ensure(db, region, request)));
    }

    /// The queued check of `ensure_resource`.
    fn ensure_resource_task(&mut self, db: &mut OfflineDatabase, request: u64) {
        let Some(Pending::Queued { resource, then }) = self.requests.remove(&request) else {
            // Its download stopped since.
            return;
        };

        // The region's copy is complete while it's fresh. A stale one is
        // revalidated, and stays as it is until its refresh arrives.
        let fresh = |caching: Caching| caching.is_fresh(now());
        let stale = if then.reads() {
            match db.region_resource(&resource) {
                Some((response, size)) if fresh(response.caching) => {
                    if let Err(error) = self.read(&then, &response) {
                        self.report_unparsable(&resource, &error);
                    }
                    self.complete_stored_resource(db, &resource, size);
                    return;
                }
                stale => stale,
            }
        } else {
            match db.check_region_resource(&resource) {
                Some((size, caching)) if fresh(caching) => {
                    self.complete_stored_resource(db, &resource, size);
                    return;
                }
                Some(_) => db.region_resource(&resource),
                None => None,
            }
        };

        let mut online_resource = resource.clone();
        if let Some((stored, _)) = &stale {
            // Lets the server answer 304 Not Modified.
            online_resource.set_prior(stored);
        }

        let request = self.next_request();
        let (region, post) = (self.id, Arc::clone(&self.post));
        let (handle, responder) = Request::new(move |response: Response| {
            post(Box::new(move |db, downloads| downloads.on_response(db, region, request, response)));
        });
        self.requests.insert(request, Pending::Loading { _request: handle, resource, then, stale });
        self.network.load(&online_resource, responder);
    }

    /// A response to the request `request` of `ensure_resource_task`.
    fn on_online_response(&mut self, db: &mut OfflineDatabase, request: u64, online_response: Response) {
        let Some(Pending::Loading { resource, then, stale, .. }) = self.requests.get(&request) else {
            return;
        };
        let (resource, then, stale) = (resource.clone(), then.clone(), stale.clone());

        if let Some(error) = &online_response.error {
            self.observer.response_error((**error).clone());
            // Another error keeps the request, which retries.
            if error.reason == Reason::NotFound {
                self.requests.remove(&request);
                if let Some(stale) = &stale
                    && then.reads()
                {
                    self.continue_from_stored_copy(db, &resource, &then, stale);
                    return;
                }

                // On error 404, we skip this request and go further.
                assert!(self.status.required_resource_count > 0);
                self.status.required_resource_count -= 1;
                if resource.kind == Kind::Source
                    && self.required_source_urls.remove(&resource.url)
                    && self.required_source_urls.is_empty()
                {
                    self.status.required_resource_count_is_precise = true;
                }
                self.notify_status_changed();
                self.continue_download(db);
            }
            return;
        }

        self.requests.remove(&request);

        if then.reads() {
            // A 304 response has no data, so pass on the stored copy.
            let parsed = match &stale {
                Some((stored, _)) if online_response.not_modified => self.read(&then, stored),
                _ => self.read(&then, &online_response),
            };
            if let Err(error) = &parsed {
                self.report_unparsable(&resource, error);
            }
            if let (Err(_), Some(stale), false) = (&parsed, &stale, online_response.not_modified) {
                self.continue_from_stored_copy(db, &resource, &then, stale);
                return;
            }
        }

        // Queue up for batched insertion
        self.buffer.push((resource, online_response));

        // Flush buffer periodically.
        // Have to keep `resourcesRemaining.empty()` as the following
        // condition would fail otherwise.
        if self.buffer.len() == RESOURCES_BATCH_SIZE || self.nothing_remains() {
            self.flush_resources_buffer(db);
        }

        self.continue_download(db);
    }

    /// A style or TileJSON lists the region's other resources. When its
    /// refresh is missing or can't be read, the download goes on from the
    /// stored copy.
    fn continue_from_stored_copy(
        &mut self,
        db: &mut OfflineDatabase,
        resource: &Resource,
        then: &Then,
        (stored, size): &(Response, u64),
    ) {
        if let Err(error) = self.read(then, stored) {
            self.report_unparsable(resource, &error);
        }
        self.complete_stored_resource(db, resource, *size);
    }

    /// Counts a resource the region already holds as complete.
    fn complete_stored_resource(&mut self, db: &mut OfflineDatabase, resource: &Resource, size: u64) {
        self.resources_to_be_marked_as_used.push(resource.clone());
        self.status.completed_resource_count += 1;
        self.status.completed_resource_size += size;
        if resource.kind == Kind::Tile {
            self.status.completed_tile_count += 1;
            self.status.completed_tile_size += size;
        }
        self.notify_status_changed();
        self.continue_download(db);
    }

    fn report_unparsable(&self, resource: &Resource, error: &str) {
        let message = format!("Can't parse {}: {error}", resource.url);
        self.observer.response_error(ResourceError::new(Reason::Other, message));
    }
}