Skip to main content

mln_builtins/sources/
tileset.rs

1//! Vector, raster and raster-dem sources: a source loads the TileJSON at its
2//! URL, or else takes the tileset the style lists, the style's members
3//! winning, and its tiles load through the map's file source. A tile's first request only looks in the cache; a required
4//! tile then asks the network, unless it has data from there that never
5//! expires. The network request stays open while the tile is required: the
6//! file source answers it again as it retries an error or revalidates data
7//! that expired. The cache's copy shows at once unless caching rules forbid
8//! using it stale; then the tile holds it back until a 304 renews it.
9
10use std::marker::PhantomData;
11use std::sync::{Arc, Weak};
12use std::time::Duration;
13
14use mln_engine::MapMode;
15use mln_engine::source::{
16    Cover, DataOrigin, DemTiles, Described, GeometryTiles, Load, LoadContext, OfflineResources, OriginUpdate,
17    RasterTiles, Respond, SourceSummary, SourceType, Supply, TileKind, TileNecessity, TileOperation, TileTimes,
18    WorldCopy,
19};
20use mln_engine::storage::chrono::Timestamp;
21use mln_engine::storage::resource::{Priority, TileAddressing, TileFormat};
22use mln_engine::storage::response::{Caching, Reason};
23use mln_engine::storage::{Data, FileSource, LoadingMethod, Request, Resource, Response, StoragePolicy};
24use mln_engine::tile::cut::{Ancestor, Cut, CutData};
25use mln_engine::tile::{OverscaledTileID, TileData};
26use mln_style::crs::{TileMatrixSet, WorldMapping};
27use mln_style::error::Error;
28use mln_style::hash::{HashMap, hash_bytes};
29use mln_style::layer::SourceKind;
30use mln_style::source::{SourceCommon, SourceData};
31use mln_style::sources::tileset::{PromoteId, TilesetSourceOptions, TilesetSourceType};
32pub use mln_style::sources::tileset::{RasterDemKind, RasterKind, TilesetKind, VectorKind};
33use mln_style::tile_id::CanonicalTileID;
34use mln_style::tileset::{RasterEncoding, Scheme, Tileset, VectorEncoding};
35use mln_style::{Source, constants};
36
37/// The engine half of the vector, raster and raster-dem source types, whose
38/// style half is `mln_style`'s [`TilesetSourceType<K>`].
39pub struct TilesetSource<K>(PhantomData<fn() -> K>);
40
41pub type VectorSource = TilesetSource<VectorKind>;
42pub type RasterSource = TilesetSource<RasterKind>;
43pub type RasterDemSource = TilesetSource<RasterDemKind>;
44
45/// A tileset kind's kind of tiles, and how a view covers them.
46trait TilesetTilesKind: TilesetKind + Sized {
47    type Data: TileKind;
48    const TILES: Tiles;
49    /// [`Cover::round_zoom`].
50    const ROUND_ZOOM: bool;
51    /// [`Cover::overscale`].
52    const OVERSCALE: bool;
53
54    /// Sets how the tiles' pixels encode elevations, for a raster-dem
55    /// tileset.
56    fn set_encoding(_update: &mut OriginUpdate<'_, TilesetOrigin<Self>>, _encoding: RasterEncoding) {}
57}
58
59impl TilesetTilesKind for VectorKind {
60    type Data = GeometryTiles;
61    const TILES: Tiles = Tiles::Vector;
62    const ROUND_ZOOM: bool = false;
63    const OVERSCALE: bool = true;
64}
65
66impl TilesetTilesKind for RasterKind {
67    type Data = RasterTiles;
68    const TILES: Tiles = Tiles::Raster;
69    const ROUND_ZOOM: bool = true;
70    const OVERSCALE: bool = false;
71}
72
73impl TilesetTilesKind for RasterDemKind {
74    type Data = DemTiles;
75    const TILES: Tiles = Tiles::Dem;
76    const ROUND_ZOOM: bool = true;
77    // As a raster source's: a DEM tile is the same at every zoom past the
78    // maxzoom, so the map draws it larger rather than load it again.
79    const OVERSCALE: bool = false;
80
81    fn set_encoding(update: &mut OriginUpdate<'_, TilesetOrigin<Self>>, encoding: RasterEncoding) {
82        update.set_encoding(encoding);
83    }
84}
85
86macro_rules! tileset_source_type {
87    ($kind:ty, $data:ty) => {
88        impl SourceType for TilesetSource<$kind> {
89            type Style = TilesetSourceType<$kind>;
90            type Data = $data;
91            type Description = Tileset;
92
93            fn load(source: &SourceData<Self::Style>) -> Load<Tileset> {
94                load(source)
95            }
96
97            fn describe(
98                options: &TilesetSourceOptions,
99                _world: &WorldMapping,
100                data: Option<Data>,
101                respond: Respond<Described<Tileset>>,
102            ) {
103                describe::<$kind>(options, data, respond);
104            }
105
106            fn metadata_changed(old: Option<&Tileset>, new: Option<&Tileset>) -> bool {
107                old != new
108            }
109
110            fn attribution(source: &SourceData<Self::Style>) -> Option<String> {
111                source.description::<Tileset>().map(|tileset| tileset.attribution.clone())
112            }
113
114            fn summary(source: &SourceData<Self::Style>) -> SourceSummary {
115                summary(source)
116            }
117
118            fn offline(source: &SourceData<Self::Style>) -> OfflineResources {
119                offline::<$kind>(source)
120            }
121
122            fn offline_tileset(source: &SourceData<Self::Style>, tilejson: &[u8]) -> Result<Tileset, String> {
123                source.options.tileset_with_tilejson(tilejson, <$kind as TilesetKind>::INFO.layer_kind)
124            }
125
126            fn supply(_source: &Source) -> Supply<Self::Data> {
127                Supply::tiles(TilesetOrigin::<$kind>(Tilesets::new(<$kind>::TILES), PhantomData))
128            }
129        }
130    };
131}
132
133tileset_source_type!(VectorKind, GeometryTiles);
134tileset_source_type!(RasterKind, RasterTiles);
135tileset_source_type!(RasterDemKind, DemTiles);
136
137/// The TileJSON at the source's URL, or else the tileset the style lists.
138fn load<K: TilesetKind>(source: &SourceData<TilesetSourceType<K>>) -> Load<Tileset> {
139    match &source.options.url {
140        Some(url) => Load::Fetch(mln_engine::source::Fetch::Source(url.clone())),
141        None => Load::Ready(source.options.tileset.clone().into()),
142    }
143}
144
145/// The tileset of the TileJSON `data`, with the style's members over its.
146fn describe<K: TilesetKind>(options: &TilesetSourceOptions, data: Option<Data>, respond: Respond<Described<Tileset>>) {
147    let tileset = match data {
148        None => Err("unexpectedly empty TileJSON".to_owned()),
149        Some(data) => options.tileset_with_tilejson(&data, K::INFO.layer_kind),
150    };
151    respond(tileset.map(Some).map_err(Error::failed));
152}
153
154fn summary<K: TilesetKind>(source: &SourceData<TilesetSourceType<K>>) -> SourceSummary {
155    let options = &source.options;
156    let vector_encoding = (K::INFO.layer_kind == SourceKind::Geometry).then(|| {
157        let loaded = source.description::<Tileset>().and_then(|tileset| tileset.vector_encoding);
158        loaded.or(options.tileset.vector_encoding).unwrap_or(VectorEncoding::Mapbox)
159    });
160    SourceSummary {
161        url: options.url.clone(),
162        tile_size: Some(options.tile_size),
163        inline_tileset: options.inline_tileset(),
164        vector_encoding,
165        geojson: None,
166    }
167}
168
169fn offline<K: TilesetTilesKind>(source: &SourceData<TilesetSourceType<K>>) -> OfflineResources {
170    let options = &source.options;
171    let (tile_size, round_zoom) = (options.tile_size, K::ROUND_ZOOM);
172    match &options.url {
173        Some(url) => OfflineResources::TileJson { url: url.clone(), tile_size, round_zoom },
174        None => match options.inline_tileset() {
175            Some(tileset) => OfflineResources::Tiles { tileset, tile_size, round_zoom },
176            None => OfflineResources::None,
177        },
178    }
179}
180
181/// The kinds of tiles a tileset's are, which decide what a tile's data
182/// delivers.
183#[derive(Clone, Copy, Debug, PartialEq, Eq)]
184enum Tiles {
185    /// Vector tiles: always the default size, in the encoding that the
186    /// tileset names, cut past the tileset's last zoom.
187    Vector,
188    Raster,
189    Dem,
190}
191
192/// What a tile's data delivers: geometry of a vector tile, or a raster or
193/// raster-dem tile's image.
194enum Item {
195    Geometry(TileData),
196    Image(Data),
197}
198
199/// A tile's item, and the data at the tileset's last zoom that the tile
200/// holds for the tiles cut from it, if it is that data.
201type ItemHeld = (Item, Option<Arc<Ancestor>>);
202
203/// A tileset source's data origin for tiles of the kind `K`. Only the kind
204/// of data differs between kinds, so each hook runs [`Tilesets`]' own.
205struct TilesetOrigin<K>(Tilesets, PhantomData<fn() -> K>);
206
207impl<K: TilesetTilesKind> DataOrigin for TilesetOrigin<K> {
208    type Data = K::Data;
209    type Tile = TilesetTile;
210    type Reply = Response;
211
212    fn update(&mut self, update: &mut OriginUpdate<'_, Self>) -> Option<Cover> {
213        let data = SourceData::<TilesetSourceType<K>>::recover(update.source())?;
214        let (cover, encoding) = self.0.update(&mut update.cast(), &data.options, data.description::<Tileset>())?;
215        if let Some(encoding) = encoding {
216            K::set_encoding(update, encoding);
217        }
218        Some(Cover { round_zoom: K::ROUND_ZOOM, overscale: K::OVERSCALE, ..cover })
219    }
220
221    fn start(&mut self, cx: &mut LoadContext<'_, '_, Self>, copy: Option<WorldCopy<'_, TilesetTile>>) -> TilesetTile {
222        self.0.start(&mut cx.cast(), copy)
223    }
224
225    fn receive(&mut self, tile: &mut TilesetTile, res: Response, cx: &mut LoadContext<'_, '_, Self>) {
226        self.0.receive(tile, res, &mut cx.cast());
227    }
228
229    fn set_necessity(&mut self, tile: &mut TilesetTile, previous: TileNecessity, cx: &mut LoadContext<'_, '_, Self>) {
230        self.0.set_necessity(tile, previous, &mut cx.cast());
231    }
232
233    fn retry(&mut self, tile: &mut TilesetTile, cx: &mut LoadContext<'_, '_, Self>) {
234        self.0.retry(tile, &mut cx.cast());
235    }
236
237    /// The tile's data failed to lay out or decode: it isn't fresh, so the
238    /// tile loads it again when required again, and no longer holds it for
239    /// the tiles cut from it.
240    fn failed(&mut self, tile: &mut TilesetTile, _cx: &mut LoadContext<'_, '_, Self>) {
241        tile.drop_data();
242    }
243}
244
245/// How many zooms, up to the map's last, draw a vector tileset's tiles
246/// scaled up. The zooms between the tileset's last and these have tiles cut
247/// from its tiles.
248const OVERSCALED_ZOOMS: u8 = 4;
249
250#[derive(Clone, Copy, Debug, PartialEq, Eq)]
251enum VectorTileEncoding {
252    Mvt,
253    Mlt,
254}
255
256impl VectorTileEncoding {
257    /// `data`, whose features take their ids from the properties that
258    /// `promote_id` names.
259    fn decode(self, data: Data, promote_id: Option<&Arc<PromoteId>>) -> TileData {
260        let promote_id = promote_id.cloned();
261        match self {
262            VectorTileEncoding::Mvt => TileData::Mvt(mln_engine::tile::MvtTile::with_promote_id(data, promote_id)),
263            VectorTileEncoding::Mlt => TileData::Mlt(mln_engine::tile::MltTile::with_promote_id(data, promote_id)),
264        }
265    }
266}
267
268/// A tileset source's tiles: the tileset of the source's last version, and
269/// what the tiles load from.
270struct Tilesets {
271    tiles: Tiles,
272    tileset: Option<Tileset>,
273    /// `None` while the source has no tiles.
274    data: Option<TilesetData>,
275    /// What the source's last version says of network requests.
276    params: NetworkParams,
277    /// The map's pixel ratio, which raster tiles' resources ask for.
278    pixel_ratio: f32,
279    /// The tile matrix set of the map's world as of the last update, whose
280    /// units the tiles' `{bbox}` is in.
281    tile_matrix_set: TileMatrixSet,
282}
283
284/// How a tile's network requests keep its data fresh, as its source says.
285#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
286struct NetworkParams {
287    /// How long a tile waits before it loads again after its data expires.
288    minimum_update_interval: Duration,
289    /// Whether the tile's data stays out of the offline cache.
290    volatile: bool,
291}
292
293impl NetworkParams {
294    fn of(common: &SourceCommon) -> Self {
295        NetworkParams { minimum_update_interval: common.minimum_tile_update_interval, volatile: common.volatile }
296    }
297}
298
299/// What a tileset source's tiles load from.
300struct TilesetData {
301    tileset: Tileset,
302    encoding: VectorTileEncoding,
303    promote_id: Option<Arc<PromoteId>>,
304    file_source: Option<Arc<dyn FileSource>>,
305    ancestors: Ancestors,
306}
307
308impl Tilesets {
309    fn new(tiles: Tiles) -> Self {
310        Tilesets {
311            tiles,
312            tileset: None,
313            data: None,
314            params: NetworkParams::default(),
315            pixel_ratio: 1.0,
316            tile_matrix_set: TileMatrixSet::WEB_MERCATOR,
317        }
318    }
319
320    /// Starts a new tile's loading, whose first request only looks in the
321    /// cache, even for a required tile, so that it can go on if the tile
322    /// becomes optional.
323    fn start_loading(&mut self, tile: &mut TilesetTile, cx: &mut LoadContext<'_, '_, Self>) {
324        match self.data.as_ref().map(|data| data.file_source.as_ref()) {
325            Some(None) => fail(tile, Error::failed("Can't load tile."), cx),
326            Some(Some(file_source)) if file_source.supports_cache_only() => self.request(tile, Method::Cache, cx),
327            Some(Some(_)) | None => {}
328        }
329    }
330
331    /// Requests the tile's data with `method`, unless it can take it from
332    /// another tile's in memory. A required tile that takes data from
333    /// memory that expires still asks the network, which the file source
334    /// holds until the data expires.
335    fn request(&mut self, tile: &mut TilesetTile, mut method: Method, cx: &mut LoadContext<'_, '_, Self>) {
336        if !tile.is_fresh(mln_engine::storage::chrono::now()) && self.take_in_memory(tile, cx) {
337            if cx.necessity() != TileNecessity::Required || tile.has_lasting_data() {
338                return;
339            }
340            method = Method::Network;
341        }
342        let Some(file_source) = self.data.as_ref().and_then(|data| data.file_source.clone()) else {
343            fail(tile, Error::failed("Can't load tile."), cx);
344            return;
345        };
346        cx.report(match method {
347            Method::Cache => TileOperation::RequestedFromCache,
348            Method::Network => TileOperation::RequestedFromNetwork,
349        });
350        let replier = cx.begin_load_of::<Response>();
351        // A cache-only request answers once; a network request stays open
352        // while the tile is required.
353        let (request, responder) = match method {
354            Method::Cache => Request::once(move |response| replier.send(response)),
355            Method::Network => Request::new(move |response| replier.send(response)),
356        };
357        let params = self.params;
358        file_source.load(tile.resource_for(method, params), responder);
359        debug_assert!(tile.is_idle(), "one request at a time");
360        // A new request's errors are a new streak, which fails the tile.
361        tile.failed = false;
362        tile.fetch = match method {
363            Method::Cache => Fetch::Cache { request },
364            Method::Network => Fetch::Network { request, params },
365        };
366    }
367
368    /// A tile whose data at its tileset's last zoom another tile's load
369    /// brought fresh from the network, whether a tile cut from it or the
370    /// tile itself, takes its data from that, as that load's answer, instead
371    /// of loading it again.
372    fn take_in_memory(&mut self, tile: &mut TilesetTile, cx: &mut LoadContext<'_, '_, Self>) -> bool {
373        let Some(data) = self.data.as_mut().filter(|_| self.tiles == Tiles::Vector) else {
374            return false;
375        };
376        let Some(((item, held), fetched)) =
377            data.in_memory(cx.id(), &tile.resource.url, mln_engine::storage::chrono::now())
378        else {
379            return false;
380        };
381        let Fetched { modified, caching, etag } = fetched;
382        let resource = &mut tile.resource;
383        (resource.prior_modified, resource.prior_etag) = (modified, etag);
384        resource.prior_caching = caching;
385        tile.took(modified, caching, true, cx);
386        tile.data_hash = None;
387        tile.held = held;
388        deliver(self.tiles, cx, Some(item));
389        true
390    }
391
392    /// Takes a copy of the tile's data that a request with `method`
393    /// brought, which caching rules allow it to show: new data, or, for a
394    /// 304, the data it has. The same bytes as the data it has count as a
395    /// 304.
396    fn take_response(
397        &mut self,
398        tile: &mut TilesetTile,
399        method: Method,
400        res: &Response,
401        cx: &mut LoadContext<'_, '_, Self>,
402    ) {
403        if res.not_modified {
404            tile.resource.prior_caching = res.caching;
405        } else {
406            tile.resource.set_prior(res);
407        }
408        let from_network = method == Method::Network;
409        tile.took(res.modified, res.caching, from_network, cx);
410        let hash = res.data.as_deref().filter(|_| !res.no_content).map(|data| hash_bytes(data));
411        let unchanged = res.not_modified || hash.is_some_and(|hash| tile.data_hash == Some(hash));
412        if !unchanged {
413            tile.data_hash = hash;
414        }
415        cx.report(match method {
416            Method::Network => TileOperation::LoadFromNetwork,
417            Method::Cache => TileOperation::LoadFromCache,
418        });
419        if unchanged {
420            cx.keep_data();
421        } else if let Some(data) = &mut self.data {
422            tile.held = data.deliver(self.tiles, cx, &tile.resource.url, res, from_network);
423        }
424    }
425
426    /// Takes in a version of the source, with `options` and the tileset
427    /// `loaded` for it, if it has loaded. Returns the cover, and for a
428    /// raster-dem tileset its elevations' encoding.
429    fn update(
430        &mut self,
431        update: &mut OriginUpdate<'_, Self>,
432        options: &TilesetSourceOptions,
433        loaded: Option<&Tileset>,
434    ) -> Option<(Cover, Option<RasterEncoding>)> {
435        self.params = NetworkParams::of(update.source().common());
436        self.pixel_ratio = update.map().pixel_ratio;
437        // In Continuous mode, keep the existing tiles if the new tileset is
438        // not yet available, thus providing smart style transitions without
439        // flickering. In other modes, allow clearing the tiles first, before
440        // the early return in order to avoid render tests being flaky.
441        let can_update_tileset = loaded.is_some() || update.map().mode != MapMode::Continuous;
442        if can_update_tileset && self.tileset.as_ref() != loaded {
443            self.tileset = loaded.cloned();
444            // TODO: this removes existing buckets, and will cause flickering.
445            // Should instead refresh tile data in place.
446            update.clear_tiles();
447            self.data = None;
448        }
449        // A tileset without tiles makes no tiles, and the source counts as
450        // loaded until its tiles are set.
451        let tileset = self.tileset.as_ref().filter(|tileset| !tileset.tiles.is_empty())?;
452        // A tile's `{bbox}` is its box in the grid of the map's world, so the
453        // tiles of URLs that hold one load again when the grid changes.
454        let tile_matrix_set = update.map().world.tile_matrix_set();
455        if self.tile_matrix_set != tile_matrix_set {
456            if tileset.tiles.iter().any(|url| url.contains("{bbox}")) {
457                update.clear_tiles();
458            }
459            self.tile_matrix_set = tile_matrix_set;
460        }
461        let vector = self.tiles == Tiles::Vector;
462        let encoding = if vector && tileset.vector_encoding == Some(VectorEncoding::Mlt) {
463            // The encoding is decided once, from the first tileset (`isMLT`).
464            VectorTileEncoding::Mlt
465        } else {
466            VectorTileEncoding::Mvt
467        };
468        let dem_encoding =
469            (self.tiles == Tiles::Dem).then(|| tileset.raster_encoding.unwrap_or(RasterEncoding::Mapbox));
470        let file_source = update.map().file_source.clone();
471        let promote_id = options.promote_id.clone();
472        if self.data.as_ref().is_some_and(|current| current.promote_id != promote_id) {
473            // The tiles' features have other ids.
474            update.clear_tiles();
475        }
476        let current = self.data.as_ref().is_some_and(|current| {
477            current.tileset == *tileset
478                && current.encoding == encoding
479                && current.promote_id == promote_id
480                && same_file_source(current.file_source.as_ref(), file_source.as_ref())
481        });
482        if !current {
483            self.data = Some(TilesetData {
484                tileset: tileset.clone(),
485                encoding,
486                promote_id,
487                file_source,
488                ancestors: Ancestors::default(),
489            });
490        }
491        let tile_size = if vector { constants::TILE_SIZE_I } else { options.tile_size };
492        let mut zoom_range = tileset.zoom_range;
493        if vector {
494            // Past the tileset's last zoom, tiles are cut from its tiles until
495            // the last few zooms the map can reach, which draw them scaled up.
496            let max_zoom = update.map().max_zoom.floor() as i32 - i32::from(OVERSCALED_ZOOMS);
497            zoom_range.max = zoom_range.max.max(max_zoom.clamp(0, i32::from(u8::MAX)) as u8);
498        }
499        let cover = Cover {
500            tile_size,
501            zoom_range,
502            bounds: tileset.bounds,
503            round_zoom: false,
504            overscale: false,
505            prefetch: true,
506            synchronous: false,
507        };
508        Some((cover, dem_encoding))
509    }
510
511    /// A tile that starts from its copy in another world copy takes the
512    /// copy's validators with its contents, as a cache's answer.
513    fn start(&mut self, cx: &mut LoadContext<'_, '_, Self>, copy: Option<WorldCopy<'_, TilesetTile>>) -> TilesetTile {
514        // The source makes no tiles while it has no data, nor of a tileset
515        // without tiles: such a tile can't load.
516        let (url, canonical, scheme, encoding) = match &self.data {
517            Some(TilesetData { tileset, encoding, .. }) => (
518                tileset.tiles.first().map_or("", String::as_str),
519                loaded_tile(tileset, cx.id()),
520                tileset.scheme,
521                *encoding,
522            ),
523            None => ("", cx.id().canonical, Scheme::default(), VectorTileEncoding::Mvt),
524        };
525        let format = match encoding {
526            _ if self.tiles != Tiles::Vector => TileFormat::Image,
527            VectorTileEncoding::Mvt => TileFormat::Mvt,
528            VectorTileEncoding::Mlt => TileFormat::Mlt,
529        };
530        let (x, y, z) = (canonical.x as i32, canonical.y as i32, canonical.z as i8);
531        let addressing = TileAddressing { scheme, tile_matrix_set: self.tile_matrix_set };
532        let mut resource = Resource::tile(url, self.pixel_ratio, x, y, z, addressing, format, LoadingMethod::CACHE);
533        resource.order = cx.order();
534        let mut tile = TilesetTile::new(resource);
535        // A copy made at another pixel ratio is of another resource.
536        let taken = copy.filter(|copy| copy.state().resource.url == tile.resource.url).and_then(|copy| {
537            let state = copy.state();
538            copy.take_into(cx).then_some(state)
539        });
540        match taken {
541            Some(copy) => tile.take_validators(copy),
542            None => self.start_loading(&mut tile, cx),
543        }
544        tile
545    }
546
547    /// Applies a response to the tile's request: a cache-only request's
548    /// is followed by a network one while the tile is required. A network
549    /// request stays open: the file source answers it again after an error,
550    /// and when the data expires.
551    fn receive(&mut self, tile: &mut TilesetTile, res: Response, cx: &mut LoadContext<'_, '_, Self>) {
552        let method = match tile.fetch {
553            Fetch::Cache { .. } => Method::Cache,
554            Fetch::Network { .. } => Method::Network,
555            Fetch::Idle => return,
556        };
557        if method == Method::Network {
558            if let Some(error) = res.error.as_ref().filter(|error| error.reason != Reason::NotFound) {
559                // A streak of errors reports once. The request stays open,
560                // for the file source's retry.
561                if !std::mem::replace(&mut tile.failed, true) {
562                    tile.drop_data();
563                    cx.fail_retrying(Error::failed(error.message.clone()));
564                }
565                return;
566            }
567            tile.failed = false;
568            // A 304 renews the copy the tile held back, if the file source
569            // didn't deliver it.
570            let res = if res.not_modified { tile.resource.deliver(res) } else { res };
571            self.take_response(tile, method, &res, cx);
572            return;
573        }
574        // A cache-only request answers once.
575        tile.stop();
576        cx.tried_optional();
577        cx.changed();
578        // A cache-only request that found nothing isn't an error. A copy
579        // shows while it revalidates unless its caching rules forbid that;
580        // then the tile holds it back for the network request to revalidate.
581        // An empty copy has nothing to hold back: the network loads anew.
582        if res.error.is_none() {
583            if res.caching.is_usable(mln_engine::storage::chrono::now()) {
584                tile.resource.set_prior(&res);
585                self.take_response(tile, method, &res, cx);
586            } else if !res.no_content {
587                // The network request carries it, so that a 304 delivers it.
588                tile.resource.set_prior(&res);
589                tile.resource.prior_data.clone_from(&res.data);
590            }
591        }
592        if cx.necessity() == TileNecessity::Required && tile.is_idle() {
593            self.request(tile, Method::Network, cx);
594        }
595    }
596
597    /// A required tile asks the network, unless it has data from there that
598    /// never expires; an optional one stops a network request, with the file
599    /// source's retries and revalidations. A network request made with other
600    /// parameters than the source's is made again: the cover sets each tile's
601    /// necessity as each update first retains it, so the request restarts
602    /// then.
603    fn set_necessity(&mut self, tile: &mut TilesetTile, previous: TileNecessity, cx: &mut LoadContext<'_, '_, Self>) {
604        if matches!(tile.fetch, Fetch::Network { params, .. } if params != self.params) {
605            tile.stop();
606            self.request(tile, Method::Network, cx);
607        }
608        if previous == cx.necessity() {
609            return;
610        }
611        if cx.necessity() == TileNecessity::Required {
612            if tile.is_idle() && !tile.has_lasting_data() {
613                self.request(tile, Method::Network, cx);
614            }
615        } else if tile.is_requesting_network() {
616            // Only a network-only request is aborted.
617            tile.stop();
618        }
619    }
620
621    /// Requests a tile whose network request's last answer was an error
622    /// again, now rather than after the file source's backoff.
623    fn retry(&mut self, tile: &mut TilesetTile, cx: &mut LoadContext<'_, '_, Self>) {
624        if tile.failed {
625            tile.stop();
626            self.request(tile, Method::Network, cx);
627        }
628    }
629}
630
631/// Fails the tile with `error`. Its data isn't fresh: the tile loads it
632/// again when required again, and no longer holds it for the tiles cut from
633/// it.
634fn fail(tile: &mut TilesetTile, error: Error, cx: &mut LoadContext<'_, '_, Tilesets>) {
635    tile.drop_data();
636    cx.fail(error);
637}
638
639/// Gives the tile, one of `tiles`, `item`, as [`LoadContext::deliver`].
640fn deliver(tiles: Tiles, cx: &mut LoadContext<'_, '_, Tilesets>, item: Option<Item>) {
641    match (tiles, item) {
642        (_, Some(Item::Geometry(data))) => cx.deliver_of::<GeometryTiles>(Some(data)),
643        (_, Some(Item::Image(data))) => cx.deliver_of::<RasterTiles>(Some(data)),
644        (Tiles::Vector, None) => cx.deliver_of::<GeometryTiles>(None),
645        (Tiles::Raster | Tiles::Dem, None) => cx.deliver_of::<RasterTiles>(None),
646    }
647}
648
649/// Whether `a` and `b` are both absent or the same file source.
650fn same_file_source(a: Option<&Arc<dyn FileSource>>, b: Option<&Arc<dyn FileSource>>) -> bool {
651    match (a, b) {
652        (None, None) => true,
653        (Some(a), Some(b)) => std::ptr::addr_eq(Arc::as_ptr(a), Arc::as_ptr(b)),
654        _ => false,
655    }
656}
657
658impl TilesetData {
659    /// Delivers what response `res` to a request of `url` for one of the
660    /// `tiles` brought, from the network or only the cache. A 404, unlike
661    /// an empty response (204, or no tile in an archive), says the tileset
662    /// has no tile here: a vector tile is then empty, and a raster tile
663    /// missing. A sparse tileset's empty tiles are missing.
664    /// Returns the data at the tileset's last zoom that the tile holds for
665    /// the tiles cut from it, if it delivered that data.
666    fn deliver(
667        &mut self,
668        tiles: Tiles,
669        cx: &mut LoadContext<'_, '_, Tilesets>,
670        url: &str,
671        res: &Response,
672        network: bool,
673    ) -> Option<Arc<Ancestor>> {
674        let not_found = res.tile_not_found || res.error.as_ref().is_some_and(|e| e.reason == Reason::NotFound);
675        let empty = res.no_content || not_found;
676        let vector = tiles == Tiles::Vector;
677        if empty && (self.tileset.sparse || (not_found && !vector)) {
678            cx.missing();
679            return None;
680        }
681        let data = if empty { None } else { res.data.clone() };
682        let (item, held) = match data {
683            Some(data) if vector => {
684                let (data, held) = self.decode(cx.id(), url, data, network.then(|| Fetched::of(res)));
685                (Some(Item::Geometry(data)), held)
686            }
687            Some(data) => (Some(Item::Image(data)), None),
688            None => (None, None),
689        };
690        deliver(tiles, cx, item);
691        held
692    }
693
694    /// Tile `id`'s data, from `data` of `url`, which `fetched` brought from
695    /// the network if it isn't `None`: of its ancestor if it is cut from
696    /// one. A tile at the tileset's last zoom shares its data with the tiles
697    /// cut from it, and holds it for them, as the second value.
698    fn decode(
699        &mut self,
700        id: &OverscaledTileID,
701        url: &str,
702        data: Data,
703        fetched: Option<Fetched>,
704    ) -> (TileData, Option<Arc<Ancestor>>) {
705        let loaded = loaded_tile(&self.tileset, id);
706        let (encoding, promote_id) = (self.encoding, self.promote_id.as_ref());
707        let decode = |data| encoding.decode(data, promote_id);
708        match Cut::of(&id.canonical, self.tileset.zoom_range.max) {
709            Some(cut) => {
710                let ancestor = self.ancestors.get(loaded, url, data, decode, fetched);
711                (TileData::Cut(Arc::new(CutData::new(ancestor, cut))), None)
712            }
713            None if loaded.z == self.tileset.zoom_range.max => {
714                let ancestor = self.ancestors.get(loaded, url, data, decode, fetched);
715                (ancestor.data().clone(), Some(ancestor))
716            }
717            None => (decode(data), None),
718        }
719    }
720
721    /// Tile `id`'s data from another tile's, if that load brought it from
722    /// `url` on the network and it hasn't expired at `now`, with what that
723    /// load knew of it: cut from its ancestor at the tileset's last zoom, or
724    /// for a tile at that zoom, its own, which it then holds.
725    fn in_memory(&mut self, id: &OverscaledTileID, url: &str, now: Timestamp) -> Option<(ItemHeld, Fetched)> {
726        let (ancestor, fetched) = self.ancestors.fresh(loaded_tile(&self.tileset, id), url, now)?;
727        let item = match Cut::of(&id.canonical, self.tileset.zoom_range.max) {
728            Some(cut) => (Item::Geometry(TileData::Cut(Arc::new(CutData::new(ancestor, cut)))), None),
729            None => (Item::Geometry(ancestor.data().clone()), Some(ancestor)),
730        };
731        Some((item, fetched))
732    }
733}
734
735/// What a load from the network knew of the data it brought.
736#[derive(Clone, Debug)]
737struct Fetched {
738    modified: Option<Timestamp>,
739    caching: Caching,
740    etag: Option<String>,
741}
742
743impl Fetched {
744    fn of(res: &Response) -> Fetched {
745        Fetched { modified: res.modified, caching: res.caching, etag: res.etag.clone() }
746    }
747}
748
749/// The tile of `tileset` that tile `id` loads: past the tileset's last zoom,
750/// its ancestor there, which it is cut from.
751fn loaded_tile(tileset: &Tileset, id: &OverscaledTileID) -> CanonicalTileID {
752    if id.canonical.z > tileset.zoom_range.max { id.scaled_to(tileset.zoom_range.max).canonical } else { id.canonical }
753}
754
755/// The ancestors that a tileset's cut tiles share, by their tile id, while
756/// a tile cut from them, or the tile at the last zoom itself, holds them. A
757/// tile cut from an ancestor whose data is fresh from the network takes it
758/// as it is; otherwise it loads the ancestor, and those whose loads bring
759/// the same data share it, decoded once.
760#[derive(Default)]
761struct Ancestors(HashMap<CanonicalTileID, Held>);
762
763struct Held {
764    ancestor: Weak<Ancestor>,
765    /// Where its data came from: the pixel ratio can pick another URL for
766    /// the same tile.
767    url: String,
768    /// `None` if only the cache brought it.
769    fetched: Option<Fetched>,
770}
771
772impl Ancestors {
773    /// Ancestor `id` of `data` from `url`, which `fetched` brought from the
774    /// network if it isn't `None`.
775    fn get(
776        &mut self,
777        id: CanonicalTileID,
778        url: &str,
779        data: Data,
780        decode: impl FnOnce(Data) -> TileData,
781        fetched: Option<Fetched>,
782    ) -> Arc<Ancestor> {
783        self.0.retain(|_, held| held.ancestor.strong_count() > 0);
784        let ancestor = match self.0.get(&id).and_then(|held| held.ancestor.upgrade()) {
785            Some(ancestor) if encoded(ancestor.data()) == Some(data.as_slice()) => ancestor,
786            _ => Arc::new(Ancestor::new(decode(data))),
787        };
788        self.0.insert(id, Held { ancestor: Arc::downgrade(&ancestor), url: url.to_owned(), fetched });
789        ancestor
790    }
791
792    /// Ancestor `id`, if it is held, its data came from `url`, and its data
793    /// from the network hasn't expired at `now`.
794    fn fresh(&self, id: CanonicalTileID, url: &str, now: Timestamp) -> Option<(Arc<Ancestor>, Fetched)> {
795        let held = self.0.get(&id).filter(|held| held.url == url)?;
796        let fetched = held.fetched.as_ref().filter(|fetched| fetched.caching.is_fresh(now))?;
797        Some((held.ancestor.upgrade()?, fetched.clone()))
798    }
799}
800
801/// The bytes `data` was decoded from, if it was.
802fn encoded(data: &TileData) -> Option<&[u8]> {
803    match data {
804        TileData::Mvt(tile) => Some(tile.bytes().as_slice()),
805        TileData::Mlt(tile) => Some(tile.bytes().as_slice()),
806        TileData::Features(_) | TileData::Cut(_) => None,
807    }
808}
809
810/// A tileset tile's requests: one that only looks in the cache, then, while
811/// the tile is required, one to the network, which stays open. Dropping it
812/// cancels them.
813pub(crate) struct TilesetTile {
814    pub(crate) resource: Resource,
815    fetch: Fetch,
816    /// The current request's last answer was an error. Nothing asks again
817    /// until the tile is required or the engine retries it, unless a network
818    /// request is open, which the file source answers again.
819    failed: bool,
820    /// What caching rules allow for the data the tile has.
821    caching: Caching,
822    /// The tile's data came from the network, rather than only the cache,
823    /// and didn't fail to lay out or decode.
824    from_network: bool,
825    /// For a tile at its tileset's last zoom, its data, which the tiles cut
826    /// from it find while it holds it.
827    held: Option<Arc<Ancestor>>,
828    /// The tile has data of its own, shown or on its way.
829    has_data: bool,
830    /// A hash of the bytes the tile last took, so that the same bytes again,
831    /// as a revalidation without validators brings, aren't laid out again.
832    data_hash: Option<u64>,
833}
834
835/// The tile's request; dropping it cancels it.
836enum Fetch {
837    Idle,
838    Cache {
839        #[expect(dead_code, reason = "dropping the request cancels it")]
840        request: Request,
841    },
842    Network {
843        #[expect(dead_code, reason = "dropping the request cancels it")]
844        request: Request,
845        /// What the request was made with.
846        params: NetworkParams,
847    },
848}
849
850#[derive(Clone, Copy, Debug, PartialEq, Eq)]
851enum Method {
852    Cache,
853    Network,
854}
855
856impl TilesetTile {
857    /// A tile without data, whose requests are for `resource`.
858    fn new(resource: Resource) -> Self {
859        TilesetTile {
860            resource,
861            fetch: Fetch::Idle,
862            failed: false,
863            caching: Caching::default(),
864            from_network: false,
865            held: None,
866            has_data: false,
867            data_hash: None,
868        }
869    }
870
871    /// The resource to request with `method`, whose network loads follow
872    /// `params`. Instead of one request that loads from both, a cache-only
873    /// request comes first, then a network-only one, which waits behind the
874    /// requests of tiles without data if the tile has some.
875    fn resource_for(&mut self, method: Method, params: NetworkParams) -> &Resource {
876        let resource = &mut self.resource;
877        match method {
878            Method::Cache => resource.loading_method = LoadingMethod::CACHE,
879            Method::Network => {
880                resource.loading_method = LoadingMethod::NETWORK;
881                resource.priority = if self.has_data { Priority::Low } else { Priority::Regular };
882                resource.minimum_update_interval = params.minimum_update_interval;
883                resource.storage_policy =
884                    if params.volatile { StoragePolicy::Volatile } else { StoragePolicy::Permanent };
885            }
886        }
887        &self.resource
888    }
889
890    /// Takes the validators of `copy`, the same tile's in another world
891    /// copy, with its data's caching rules and the hash of its bytes, as a
892    /// cache's answer.
893    fn take_validators(&mut self, copy: &TilesetTile) {
894        let resource = &mut self.resource;
895        resource.prior_modified = copy.resource.prior_modified;
896        resource.prior_caching = copy.resource.prior_caching;
897        resource.prior_etag.clone_from(&copy.resource.prior_etag);
898        (self.caching, self.data_hash, self.has_data) = (copy.caching, copy.data_hash, true);
899    }
900
901    /// Records that the tile took data last modified at `modified`, under
902    /// `caching`, from the network if `from_network`. A copy it held back
903    /// goes.
904    fn took(
905        &mut self,
906        modified: Option<Timestamp>,
907        caching: Caching,
908        from_network: bool,
909        cx: &mut LoadContext<'_, '_, Tilesets>,
910    ) {
911        (self.caching, self.from_network, self.has_data) = (caching, from_network, true);
912        self.resource.prior_data = None;
913        cx.set_times(TileTimes { modified, expires: caching.expires, usable_until: caching.usable_until() });
914    }
915
916    /// The tile's data failed: it isn't fresh, and the tile no longer holds
917    /// it for the tiles cut from it.
918    fn drop_data(&mut self) {
919        self.from_network = false;
920        self.held = None;
921    }
922
923    /// Whether the tile's data came from the network and hasn't expired at
924    /// `now`. Data without an expiry stays fresh.
925    fn is_fresh(&self, now: Timestamp) -> bool {
926        self.from_network && self.caching.is_fresh(now)
927    }
928
929    /// Whether a required tile needn't ask the network: its data came from
930    /// there and never expires. Data that expires is asked for again, which
931    /// the file source holds until it does.
932    fn has_lasting_data(&self) -> bool {
933        self.from_network && self.caching.expires.is_none()
934    }
935
936    /// Whether no request is under way.
937    pub(crate) fn is_idle(&self) -> bool {
938        matches!(self.fetch, Fetch::Idle)
939    }
940
941    /// Whether a network request is open.
942    pub(crate) fn is_requesting_network(&self) -> bool {
943        matches!(self.fetch, Fetch::Network { .. })
944    }
945
946    /// Drops the request under way. A response it sent before it stopped
947    /// finds the load idle, and `receive` ignores it.
948    fn stop(&mut self) {
949        self.fetch = Fetch::Idle;
950    }
951}
952
953#[cfg(test)]
954mod tests {
955    use super::*;
956
957    #[test]
958    fn data_from_the_network_is_fresh_until_it_expires() {
959        let mut tile = TilesetTile::new(Resource::source("tiles"));
960        tile.from_network = true;
961        assert!(tile.is_fresh(Timestamp::from_secs(10)), "data that never expires");
962        tile.caching.expires = Some(Timestamp::from_secs(5));
963        assert!(tile.is_fresh(Timestamp::from_secs(4)));
964        assert!(!tile.is_fresh(Timestamp::from_secs(5)));
965        assert!(!tile.is_requesting_network() && tile.is_idle(), "a new tile asks nothing");
966    }
967}