Skip to main content

mln_engine/offline/
offline_download.rs

1// The downloads of a database's offline regions live with the database, on
2// the thread that owns both (the database's worker): `Downloads` keeps one
3// `OfflineDownload` per region, which works on the database it's handed.
4// What a download sets off comes back as a task on that thread (`Post`),
5// which names the region and the request: a request's response, or the
6// queued check of a resource the region may hold. A request dropped from the
7// download, as a pause drops them all, finds nothing when its task comes.
8//
9// The observer is called while the download works; it reaches the download
10// again only through a task.
11
12use std::collections::VecDeque;
13use std::collections::hash_map::Entry;
14use std::sync::Arc;
15
16use mln_style::hash::{HashMap, HashSet};
17use mln_style::i18n::glyph_range_is_entirely_locally_generated;
18use mln_style::layer::SourceKind;
19use mln_style::range::Range;
20use mln_style::source::{OfflineResources, SourceTypeInfo};
21use mln_style::tile_id::CanonicalTileID;
22use mln_style::tileset::{Tileset, VectorEncoding};
23use mln_style::{Parser, StyleRegistry};
24use mln_vec_map::VecMap;
25
26use crate::storage::chrono::now;
27use crate::storage::constants::DEFAULT_MAXIMUM_CONCURRENT_REQUESTS;
28use crate::storage::offline::{
29    OfflineRegionDefinition, OfflineRegionDownloadState, OfflineRegionObserver, OfflineRegionStatus,
30};
31use crate::storage::offline_database::{DatabaseError, OfflineDatabase};
32use crate::storage::resource::{Priority, TileFormat, Usage};
33use crate::storage::response::{Caching, Reason, ResourceError};
34use crate::storage::{FileSource, Kind, LoadingMethod, Request, Resource, Response};
35use crate::text::glyph::{
36    GLYPH_RANGES_PER_FONT_STACK, GLYPHS_PER_GLYPH_RANGE, GlyphID, NON_IDEOGRAPH_GLYPH_RANGES_PER_FONT_STACK,
37    get_glyph_range,
38};
39use crate::tile_store::tile_cover::{TileCover, covering_zoom_level, tile_count_bounds, tile_count_geometry};
40
41const K_RESOURCES_BATCH_SIZE: usize = 64;
42const K_MARK_BATCH_SIZE: usize = 200;
43
44// Generic functions
45
46fn covering_zoom_range(
47    definition: &OfflineRegionDefinition,
48    round_zoom: bool,
49    tile_size: u16,
50    zoom_range: Range<u8>,
51) -> Range<u8> {
52    // `std::max<double>` / `std::min<double>`.
53    let a = f64::from(covering_zoom_level(definition.min_zoom(), round_zoom, tile_size));
54    let b = f64::from(zoom_range.min);
55    let min_z = if a < b { b } else { a };
56    let a = f64::from(covering_zoom_level(definition.max_zoom(), round_zoom, tile_size));
57    let b = f64::from(zoom_range.max);
58    let max_z = if b < a { b } else { a };
59
60    debug_assert!(min_z >= 0.0);
61    debug_assert!(max_z >= 0.0);
62    debug_assert!(min_z < f64::from(u8::MAX));
63    debug_assert!(max_z < f64::from(u8::MAX));
64    Range::new(min_z as u8, max_z as u8)
65}
66
67fn tile_cover(
68    definition: &OfflineRegionDefinition,
69    round_zoom: bool,
70    tile_size: u16,
71    zoom_range: Range<u8>,
72    mut f: impl FnMut(CanonicalTileID),
73) {
74    let clamped_zoom_range = covering_zoom_range(definition, round_zoom, tile_size, zoom_range);
75
76    for z in clamped_zoom_range.min..=clamped_zoom_range.max {
77        let cover = match definition {
78            OfflineRegionDefinition::TilePyramid(reg) => Some(TileCover::new_from_bounds(&reg.bounds, z)),
79            OfflineRegionDefinition::Geometry(reg) => TileCover::new_from_geometry(&reg.geometry, z).ok(),
80        };
81        if let Some(mut cover) = cover {
82            while cover.has_next() {
83                if let Some(tile) = cover.next() {
84                    f(tile.canonical);
85                }
86            }
87        }
88    }
89}
90
91fn tile_count(definition: &OfflineRegionDefinition, round_zoom: bool, tile_size: u16, zoom_range: Range<u8>) -> u64 {
92    let clamped_zoom_range = covering_zoom_range(definition, round_zoom, tile_size, zoom_range);
93
94    let mut result: u64 = 0;
95    for z in clamped_zoom_range.min..=clamped_zoom_range.max {
96        result += match definition {
97            OfflineRegionDefinition::TilePyramid(reg) => tile_count_bounds(&reg.bounds, z),
98            OfflineRegionDefinition::Geometry(reg) => tile_count_geometry(&reg.geometry, z).unwrap_or(0),
99        };
100    }
101
102    result
103}
104
105/// A task for the thread that owns a database and its downloads.
106pub type DownloadTask = Box<dyn FnOnce(&mut OfflineDatabase, &mut Downloads) + Send>;
107
108/// Hands a task to the thread that owns the database and its downloads,
109/// which runs it after what it runs now. Any thread may call it.
110pub type Post = Arc<dyn Fn(DownloadTask) + Send + Sync>;
111
112/// The downloads of a database's offline regions, by region id, on the
113/// thread that owns the database.
114pub struct Downloads {
115    downloads: HashMap<i64, OfflineDownload>,
116    network: Option<Arc<dyn FileSource>>,
117    post: Post,
118    registry: Arc<StyleRegistry>,
119}
120
121impl Downloads {
122    /// Downloads that load through `network`, come back through `post`, and
123    /// read their styles against `registry`.
124    #[must_use]
125    pub fn new(network: Option<Arc<dyn FileSource>>, post: Post, registry: Arc<StyleRegistry>) -> Self {
126        Downloads { downloads: HashMap::default(), network, post, registry }
127    }
128
129    /// The download of the region `region_id`, made at its first use. Fails
130    /// without a network, and for a region that the database doesn't have.
131    pub fn download(
132        &mut self,
133        db: &mut OfflineDatabase,
134        region_id: i64,
135    ) -> Result<&mut OfflineDownload, DatabaseError> {
136        match self.downloads.entry(region_id) {
137            Entry::Occupied(download) => Ok(download.into_mut()),
138            Entry::Vacant(entry) => {
139                let Some(network) = &self.network else {
140                    return Err(DatabaseError::Runtime("Network file source unavailable.".to_owned()));
141                };
142                let definition = db.get_region(region_id)?.ok_or(DatabaseError::RegionNotFound(region_id))?.definition;
143                let download = OfflineDownload::new(
144                    region_id,
145                    definition,
146                    Arc::clone(network),
147                    Arc::clone(&self.post),
148                    Arc::clone(&self.registry),
149                );
150                Ok(entry.insert(download))
151            }
152        }
153    }
154
155    /// Adds a download that was made apart, in place of the region's.
156    pub fn insert(&mut self, download: OfflineDownload) {
157        self.downloads.insert(download.id, download);
158    }
159
160    /// The download of `region_id`, if it has one.
161    pub fn get_mut(&mut self, region_id: i64) -> Option<&mut OfflineDownload> {
162        self.downloads.get_mut(&region_id)
163    }
164
165    /// Stops and forgets the download of `region_id`.
166    pub fn remove(&mut self, region_id: i64) -> Option<OfflineDownload> {
167        self.downloads.remove(&region_id)
168    }
169
170    /// A response to the request `request` of the region's download.
171    fn on_response(&mut self, db: &mut OfflineDatabase, region_id: i64, request: u64, response: Response) {
172        if let Some(download) = self.downloads.get_mut(&region_id) {
173            download.on_online_response(db, request, response);
174        }
175    }
176
177    /// The queued check of a resource that the region's download needs.
178    fn on_ensure(&mut self, db: &mut OfflineDatabase, region_id: i64, request: u64) {
179        if let Some(download) = self.downloads.get_mut(&region_id) {
180            download.ensure_resource_task(db, request);
181        }
182    }
183}
184
185/// The default observer.
186struct NullObserver;
187
188impl OfflineRegionObserver for NullObserver {}
189
190/// What a downloaded resource lists, which the download goes on to load.
191#[derive(Clone)]
192enum Then {
193    /// Nothing: a resource that lists no others.
194    Nothing,
195    /// The style, which lists the sources, glyphs and sprites.
196    Style,
197    /// A source's TileJSON, which lists its tiles.
198    Source { url: String, source: mln_style::Source, tile_size: u16 },
199}
200
201impl Then {
202    fn reads(&self) -> bool {
203        !matches!(self, Then::Nothing)
204    }
205}
206
207/// A resource the download waits for.
208enum Pending {
209    /// Its check of what the region holds is queued.
210    Queued { resource: Resource, then: Then },
211    /// It loads from the network, revalidating the stored copy, if any, with
212    /// its stored size.
213    Loading { _request: Request, resource: Resource, then: Then, stale: Option<(Response, u64)> },
214}
215
216/// The download of an offline region's resources into the database.
217pub struct OfflineDownload {
218    id: i64,
219    definition: OfflineRegionDefinition,
220    network: Arc<dyn FileSource>,
221    post: Post,
222    registry: Arc<StyleRegistry>,
223    /// The most requests the download has in flight at once.
224    maximum_concurrent_requests: u32,
225    status: OfflineRegionStatus,
226    observer: Box<dyn OfflineRegionObserver>,
227    /// The resources it waits for, by request id.
228    requests: VecMap<u64, Pending>,
229    next_request_id: u64,
230    required_source_urls: HashSet<String>,
231    resources_remaining: VecDeque<Resource>,
232    resources_to_be_marked_as_used: Vec<Resource>,
233    buffer: Vec<(Resource, Response)>,
234}
235
236impl OfflineDownload {
237    /// The download of the region `id`, which loads through `network`, comes
238    /// back through `post`, and reads the region's style against `registry`.
239    #[must_use]
240    pub fn new(
241        id: i64,
242        definition: OfflineRegionDefinition,
243        network: Arc<dyn FileSource>,
244        post: Post,
245        registry: Arc<StyleRegistry>,
246    ) -> Self {
247        OfflineDownload {
248            id,
249            definition,
250            network,
251            post,
252            registry,
253            maximum_concurrent_requests: DEFAULT_MAXIMUM_CONCURRENT_REQUESTS,
254            status: OfflineRegionStatus::default(),
255            observer: Box::new(NullObserver),
256            requests: VecMap::new(),
257            next_request_id: 0,
258            required_source_urls: HashSet::default(),
259            resources_remaining: VecDeque::new(),
260            resources_to_be_marked_as_used: Vec::new(),
261            buffer: Vec::new(),
262        }
263    }
264
265    /// The region's id.
266    #[must_use]
267    pub fn id(&self) -> i64 {
268        self.id
269    }
270
271    /// Sets the most requests the download has in flight at once.
272    pub fn set_maximum_concurrent_requests(&mut self, maximum: u32) {
273        self.maximum_concurrent_requests = maximum;
274    }
275
276    /// Sets the download's observer, or the default one that ignores
277    /// everything.
278    pub fn set_observer(&mut self, observer: Option<Box<dyn OfflineRegionObserver>>) {
279        self.observer = observer.unwrap_or_else(|| Box::new(NullObserver));
280    }
281
282    fn notify_status_changed(&self) {
283        self.observer.status_changed(self.status);
284    }
285
286    fn next_request(&mut self) -> u64 {
287        let id = self.next_request_id;
288        self.next_request_id += 1;
289        id
290    }
291
292    /// Starts or stops the download.
293    pub fn set_state(&mut self, state: OfflineRegionDownloadState) {
294        if self.status.download_state == state {
295            return;
296        }
297        self.status.download_state = state;
298        if state == OfflineRegionDownloadState::Active {
299            self.activate_download();
300        } else {
301            self.deactivate_download();
302        }
303        self.notify_status_changed();
304    }
305
306    /// The download's status: while it's active, what it found so far, else
307    /// what the region holds of what its stored style lists.
308    #[must_use]
309    pub fn get_status(&self, db: &mut OfflineDatabase) -> OfflineRegionStatus {
310        if self.status.download_state == OfflineRegionDownloadState::Active {
311            return self.status;
312        }
313
314        let Ok(mut result) = db.get_region_completed_status(self.id) else {
315            // We can't find this offline region because the database is
316            // unavailable, or the download does not exist.
317            return OfflineRegionStatus::default();
318        };
319
320        result.required_resource_count += 1;
321        let style_response = db.get(&Resource::style(self.definition.style_url()));
322        let mut parser = Parser::new(&self.registry);
323        // A download reports a style it can't read, and the count stays
324        // imprecise.
325        let Some(style_data) = style_response.and_then(|response| response.data) else {
326            return result;
327        };
328        if parser.parse(&String::from_utf8_lossy(&style_data)).is_err() {
329            return result;
330        }
331
332        result.required_resource_count_is_precise = true;
333
334        for source in &parser.sources {
335            let record = source.clone();
336            let round_zoom = record.info().round_zoom;
337            let (tileset, tile_size) = match record.data().offline() {
338                OfflineResources::None => continue,
339                OfflineResources::Source { .. } | OfflineResources::Image { .. } => {
340                    result.required_resource_count += 1;
341                    continue;
342                }
343                // A source without tile URLs has no tiles to download.
344                OfflineResources::Tiles { tileset, tile_size } => (Some(tileset), tile_size),
345                OfflineResources::TileJson { url, tile_size } => {
346                    result.required_resource_count += 1;
347                    let source_response = db.get(&Resource::source(&url));
348                    let tileset = source_response
349                        .and_then(|response| response.data)
350                        .and_then(|data| record.data().offline_tileset(&data).ok());
351                    // As a download does, count no tiles for a TileJSON that
352                    // is missing, can't be read, or has no tile URLs, and
353                    // leave the count imprecise.
354                    if tileset.as_ref().is_none_or(|tileset| tileset.tiles.is_empty()) {
355                        result.required_resource_count_is_precise = false;
356                    }
357                    (tileset, tile_size)
358                }
359            };
360            if let Some(tileset) = tileset.filter(|tileset| !tileset.tiles.is_empty()) {
361                let count = tile_count(&self.definition, round_zoom, tile_size, tileset.zoom_range);
362                result.required_tile_count += count;
363                result.required_resource_count += count;
364            }
365        }
366
367        if !parser.glyph_url.is_empty() {
368            let ttf_count = parser.font_faces.as_ref().map_or(0, |faces| faces.len() as u64); // custom faces
369            let per_font_stack = if self.definition.include_ideographs() {
370                u64::from(GLYPH_RANGES_PER_FONT_STACK) + ttf_count
371            } else {
372                u64::from(NON_IDEOGRAPH_GLYPH_RANGES_PER_FONT_STACK) + ttf_count
373            };
374            result.required_resource_count += parser.font_stacks().len() as u64 * per_font_stack;
375        }
376
377        if !parser.sprites.is_empty() {
378            result.required_resource_count += 4 * parser.sprites.len() as u64;
379        }
380
381        result
382    }
383
384    fn activate_download(&mut self) {
385        self.status = OfflineRegionStatus::default();
386        self.status.download_state = OfflineRegionDownloadState::Active;
387        self.status.required_resource_count += 1;
388
389        let mut style_resource = Resource::style(self.definition.style_url());
390        style_resource.set_priority(Priority::Low);
391        style_resource.set_usage(Usage::Offline);
392        self.ensure_resource(style_resource, Then::Style);
393    }
394
395    /// Reads what a downloaded style or TileJSON lists, and queues it.
396    fn read(&mut self, then: &Then, response: &Response) -> Result<(), String> {
397        match then {
398            Then::Nothing => Ok(()),
399            Then::Style => self.on_style_response(response),
400            Then::Source { url, source, tile_size } => {
401                let Some(data) = &response.data else {
402                    return Err("the TileJSON has no content".to_owned());
403                };
404                let tileset = source.data().offline_tileset(data)?;
405                if tileset.tiles.is_empty() {
406                    return Err("the TileJSON has no tile URLs".to_owned());
407                }
408                self.queue_tiles(source.info(), *tile_size, &tileset);
409                if self.required_source_urls.remove(url) && self.required_source_urls.is_empty() {
410                    self.status.required_resource_count_is_precise = true;
411                }
412                Ok(())
413            }
414        }
415    }
416
417    /// Queues the resources that the style lists.
418    fn on_style_response(&mut self, style_response: &Response) -> Result<(), String> {
419        let Some(style_data) = &style_response.data else {
420            return Err("the style has no content".to_owned());
421        };
422        let mut parser = Parser::new(&self.registry);
423        parser.parse(&String::from_utf8_lossy(style_data)).map_err(|error| error.to_string())?;
424        self.status.required_resource_count_is_precise = true;
425
426        for source in &parser.sources {
427            let record = source.clone();
428            match record.data().offline() {
429                OfflineResources::None => {}
430                OfflineResources::Tiles { tileset, tile_size } => {
431                    self.queue_tiles(record.info(), tile_size, &tileset);
432                }
433                OfflineResources::TileJson { url, tile_size } => {
434                    self.status.required_resource_count_is_precise = false;
435                    self.status.required_resource_count += 1;
436                    self.required_source_urls.insert(url.clone());
437
438                    let mut source_resource = Resource::source(&url);
439                    source_resource.set_priority(Priority::Low);
440                    source_resource.set_usage(Usage::Offline);
441                    self.ensure_resource(source_resource, Then::Source { url, source: record, tile_size });
442                }
443                OfflineResources::Source { url } => self.queue_resource(Resource::source(&url)),
444                OfflineResources::Image { url } => {
445                    if !url.is_empty() {
446                        self.queue_resource(Resource::image(&url));
447                    }
448                }
449            }
450        }
451
452        if !parser.glyph_url.is_empty() {
453            let include_ideographs = self.definition.include_ideographs();
454            for font_stack in parser.font_stacks() {
455                for i in 0..GLYPH_RANGES_PER_FONT_STACK {
456                    // Only skip a range when every codepoint in it can be
457                    // generated locally; some ranges (e.g. 0xFF00) are mixed.
458                    let start = (i * GLYPHS_PER_GLYPH_RANGE) as u16;
459                    if include_ideographs || !glyph_range_is_entirely_locally_generated(start) {
460                        let range = get_glyph_range(GlyphID::from(start));
461                        self.queue_resource(Resource::glyphs(
462                            &parser.glyph_url,
463                            &font_stack,
464                            (range.first, range.second),
465                        ));
466                    }
467                    if let Some(faces) = &parser.font_faces {
468                        for face in faces.iter() {
469                            self.queue_resource(Resource::font_face(&face.url));
470                        }
471                    }
472                }
473            }
474        }
475
476        if !parser.sprites.is_empty() {
477            // Always request 1x and @2x sprite images for portability.
478            for sprite in &parser.sprites {
479                let sprite_url = &sprite.sprite_url;
480                self.queue_resource(Resource::sprite_image(sprite_url, 1.0));
481                self.queue_resource(Resource::sprite_image(sprite_url, 2.0));
482                self.queue_resource(Resource::sprite_json(sprite_url, 1.0));
483                self.queue_resource(Resource::sprite_json(sprite_url, 2.0));
484            }
485        }
486        Ok(())
487    }
488
489    // Fill up our own request queue by requesting the next few resources.
490    // This is called when activating the download, or when a request
491    // completes successfully.
492    //
493    // Note "successfully"; it's not called when a requests receives an
494    // error. A request that errors will be retried after some delay. So in
495    // that sense it's still "active" and consuming resources, notably the
496    // request object, its timer, and network resources when the timer fires.
497    //
498    // We could try to squeeze in subsequent requests while we wait for the
499    // errored request to retry. But that risks overloading the upstream
500    // request queue -- defeating our own metering -- if there are a lot of
501    // errored requests that all come up for retry at the same time. And many
502    // times, the cause of a request error will apply to many requests of the
503    // same type. For instance if a server is unreachable, all the requests
504    // to that host are going to error. In that case, continuing to try
505    // subsequent resources after the first few errors is fruitless anyway.
506    fn continue_download(&mut self, db: &mut OfflineDatabase) {
507        if !self.is_active() {
508            return;
509        }
510
511        if self.resources_remaining.is_empty() {
512            // Flush pending buffers.
513            self.flush_resources_buffer(db);
514            if self.status.complete() {
515                self.mark_pending_used_resources(db);
516                self.set_state(OfflineRegionDownloadState::Inactive);
517                return;
518            }
519        }
520
521        if self.resources_to_be_marked_as_used.len() >= K_MARK_BATCH_SIZE {
522            self.mark_pending_used_resources(db);
523        }
524
525        while self.requests.len() < self.maximum_concurrent_requests as usize {
526            let Some(resource) = self.resources_remaining.pop_front() else {
527                break;
528            };
529            self.ensure_resource(resource, Then::Nothing);
530        }
531    }
532
533    fn deactivate_download(&mut self) {
534        self.required_source_urls.clear();
535        self.resources_remaining.clear();
536        self.requests.clear();
537        self.buffer.clear();
538    }
539
540    fn is_active(&self) -> bool {
541        self.status.download_state == OfflineRegionDownloadState::Active
542    }
543
544    fn flush_resources_buffer(&mut self, db: &mut OfflineDatabase) {
545        if self.buffer.is_empty() {
546            return;
547        }
548        db.put_region_resources(self.id, &self.buffer, &mut self.status);
549        self.buffer.clear();
550        self.notify_status_changed();
551    }
552
553    fn queue_resource(&mut self, mut resource: Resource) {
554        resource.set_priority(Priority::Low);
555        resource.set_usage(Usage::Offline);
556        self.status.required_resource_count += 1;
557        if resource.kind == Kind::Tile {
558            self.status.required_tile_count += 1;
559        }
560        self.resources_remaining.push_front(resource);
561    }
562
563    /// Queues the tiles of `tileset`, of a source of type `source`, that cover
564    /// the region.
565    fn queue_tiles(&mut self, source: SourceTypeInfo, tile_size: u16, tileset: &Tileset) {
566        // A source without tile URLs has no tiles to download.
567        let Some(url_template) = tileset.tiles.first() else {
568            return;
569        };
570        let format = match source.layer_kind {
571            SourceKind::Geometry if tileset.vector_encoding == Some(VectorEncoding::MLT) => TileFormat::Mlt,
572            SourceKind::Geometry => TileFormat::Mvt,
573            SourceKind::None | SourceKind::Raster | SourceKind::RasterDem => TileFormat::Image,
574        };
575        let (status, remaining) = (&mut self.status, &mut self.resources_remaining);
576        let pixel_ratio = self.definition.pixel_ratio();
577        tile_cover(&self.definition, source.round_zoom, tile_size, tileset.zoom_range, |tile: CanonicalTileID| {
578            status.required_resource_count += 1;
579            status.required_tile_count += 1;
580
581            let mut tile_resource = Resource::tile(
582                url_template,
583                pixel_ratio,
584                tile.x as i32,
585                tile.y as i32,
586                tile.z as i8,
587                tileset.scheme,
588                format,
589                LoadingMethod::All,
590            );
591
592            tile_resource.set_priority(Priority::Low);
593            tile_resource.set_usage(Usage::Offline);
594
595            remaining.push_back(tile_resource);
596        });
597    }
598
599    fn mark_pending_used_resources(&mut self, db: &mut OfflineDatabase) {
600        db.mark_used_resources(self.id, &self.resources_to_be_marked_as_used);
601        self.resources_to_be_marked_as_used.clear();
602    }
603
604    /// Queues the check of `resource` against what the region holds, which
605    /// loads it unless the region holds a usable copy.
606    fn ensure_resource(&mut self, resource: Resource, then: Then) {
607        debug_assert_eq!(resource.priority, Priority::Low);
608        debug_assert_eq!(resource.usage, Usage::Offline);
609
610        let request = self.next_request();
611        self.requests.insert(request, Pending::Queued { resource, then });
612        let region = self.id;
613        (self.post)(Box::new(move |db, downloads| downloads.on_ensure(db, region, request)));
614    }
615
616    /// The queued check of `ensure_resource`.
617    fn ensure_resource_task(&mut self, db: &mut OfflineDatabase, request: u64) {
618        let Some(Pending::Queued { resource, then }) = self.requests.remove(&request) else {
619            // Its download stopped since.
620            return;
621        };
622
623        // The region's copy is complete while it's fresh. A stale one is
624        // revalidated, and stays as it is until its refresh arrives.
625        let fresh = |caching: Caching| caching.is_fresh(now());
626        let stale = if then.reads() {
627            match db.get_region_resource(&resource) {
628                Some((response, size)) if fresh(response.caching) => {
629                    if let Err(error) = self.read(&then, &response) {
630                        self.report_unparsable(&resource, &error);
631                    }
632                    self.complete_stored_resource(db, &resource, size);
633                    return;
634                }
635                stale => stale,
636            }
637        } else {
638            match db.check_region_resource(&resource) {
639                Some((size, caching)) if fresh(caching) => {
640                    self.complete_stored_resource(db, &resource, size);
641                    return;
642                }
643                Some(_) => db.get_region_resource(&resource),
644                None => None,
645            }
646        };
647
648        let mut online_resource = resource.clone();
649        if let Some((stored, _)) = &stale {
650            // Lets the server answer 304 Not Modified.
651            online_resource.set_prior(stored);
652        }
653
654        let request = self.next_request();
655        let (region, post) = (self.id, Arc::clone(&self.post));
656        let (handle, responder) = Request::new(move |response: Response| {
657            post(Box::new(move |db, downloads| downloads.on_response(db, region, request, response)));
658        });
659        self.requests.insert(request, Pending::Loading { _request: handle, resource, then, stale });
660        self.network.load(&online_resource, responder);
661    }
662
663    /// A response to the request `request` of `ensure_resource_task`.
664    fn on_online_response(&mut self, db: &mut OfflineDatabase, request: u64, online_response: Response) {
665        let Some(Pending::Loading { resource, then, stale, .. }) = self.requests.get(&request) else {
666            return;
667        };
668        let (resource, then, stale) = (resource.clone(), then.clone(), stale.clone());
669
670        if let Some(error) = &online_response.error {
671            self.observer.response_error((**error).clone());
672            // Another error keeps the request, which retries.
673            if error.reason == Reason::NotFound {
674                self.requests.remove(&request);
675                if let Some(stale) = &stale
676                    && then.reads()
677                {
678                    self.continue_from_stored_copy(db, &resource, &then, stale);
679                    return;
680                }
681
682                // On error 404, we skip this request and go further.
683                assert!(self.status.required_resource_count > 0);
684                self.status.required_resource_count -= 1;
685                if resource.kind == Kind::Source
686                    && self.required_source_urls.remove(&resource.url)
687                    && self.required_source_urls.is_empty()
688                {
689                    self.status.required_resource_count_is_precise = true;
690                }
691                self.notify_status_changed();
692                self.continue_download(db);
693            }
694            return;
695        }
696
697        self.requests.remove(&request);
698
699        if then.reads() {
700            // A 304 response has no data, so pass on the stored copy.
701            let parsed = match &stale {
702                Some((stored, _)) if online_response.not_modified => self.read(&then, stored),
703                _ => self.read(&then, &online_response),
704            };
705            if let Err(error) = &parsed {
706                self.report_unparsable(&resource, error);
707            }
708            if let (Err(_), Some(stale), false) = (&parsed, &stale, online_response.not_modified) {
709                self.continue_from_stored_copy(db, &resource, &then, stale);
710                return;
711            }
712        }
713
714        // Queue up for batched insertion
715        self.buffer.push((resource, online_response));
716
717        // Flush buffer periodically.
718        // Have to keep `resourcesRemaining.empty()` as the following
719        // condition would fail otherwise.
720        if self.buffer.len() == K_RESOURCES_BATCH_SIZE || self.resources_remaining.is_empty() {
721            self.flush_resources_buffer(db);
722        }
723
724        self.continue_download(db);
725    }
726
727    /// A style or TileJSON lists the region's other resources. When its
728    /// refresh is missing or can't be read, the download goes on from the
729    /// stored copy.
730    fn continue_from_stored_copy(
731        &mut self,
732        db: &mut OfflineDatabase,
733        resource: &Resource,
734        then: &Then,
735        (stored, size): &(Response, u64),
736    ) {
737        if let Err(error) = self.read(then, stored) {
738            self.report_unparsable(resource, &error);
739        }
740        self.complete_stored_resource(db, resource, *size);
741    }
742
743    /// Counts a resource the region already holds as complete.
744    fn complete_stored_resource(&mut self, db: &mut OfflineDatabase, resource: &Resource, size: u64) {
745        self.resources_to_be_marked_as_used.push(resource.clone());
746        self.status.completed_resource_count += 1;
747        self.status.completed_resource_size = self.status.completed_resource_size.wrapping_add(size);
748        if resource.kind == Kind::Tile {
749            self.status.completed_tile_count += 1;
750            self.status.completed_tile_size = self.status.completed_tile_size.wrapping_add(size);
751        }
752        self.notify_status_changed();
753        self.continue_download(db);
754    }
755
756    fn report_unparsable(&self, resource: &Resource, error: &str) {
757        let message = format!("Can't parse {}: {error}", resource.url);
758        self.observer.response_error(ResourceError::new(Reason::Other, message));
759    }
760}