1use 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
37pub struct TilesetSource<K>(PhantomData<fn() -> K>);
40
41pub type VectorSource = TilesetSource<VectorKind>;
42pub type RasterSource = TilesetSource<RasterKind>;
43pub type RasterDemSource = TilesetSource<RasterDemKind>;
44
45trait TilesetTilesKind: TilesetKind + Sized {
47 type Data: TileKind;
48 const TILES: Tiles;
49 const ROUND_ZOOM: bool;
51 const OVERSCALE: bool;
53
54 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 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
137fn 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
145fn 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
184enum Tiles {
185 Vector,
188 Raster,
189 Dem,
190}
191
192enum Item {
195 Geometry(TileData),
196 Image(Data),
197}
198
199type ItemHeld = (Item, Option<Arc<Ancestor>>);
202
203struct 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 fn failed(&mut self, tile: &mut TilesetTile, _cx: &mut LoadContext<'_, '_, Self>) {
241 tile.drop_data();
242 }
243}
244
245const OVERSCALED_ZOOMS: u8 = 4;
249
250#[derive(Clone, Copy, Debug, PartialEq, Eq)]
251enum VectorTileEncoding {
252 Mvt,
253 Mlt,
254}
255
256impl VectorTileEncoding {
257 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
268struct Tilesets {
271 tiles: Tiles,
272 tileset: Option<Tileset>,
273 data: Option<TilesetData>,
275 params: NetworkParams,
277 pixel_ratio: f32,
279 tile_matrix_set: TileMatrixSet,
282}
283
284#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
286struct NetworkParams {
287 minimum_update_interval: Duration,
289 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
299struct 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 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 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 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 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 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 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 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 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 update.clear_tiles();
447 self.data = None;
448 }
449 let tileset = self.tileset.as_ref().filter(|tileset| !tileset.tiles.is_empty())?;
452 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 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 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 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 fn start(&mut self, cx: &mut LoadContext<'_, '_, Self>, copy: Option<WorldCopy<'_, TilesetTile>>) -> TilesetTile {
514 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 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 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 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 let res = if res.not_modified { tile.resource.deliver(res) } else { res };
571 self.take_response(tile, method, &res, cx);
572 return;
573 }
574 tile.stop();
576 cx.tried_optional();
577 cx.changed();
578 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 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 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 tile.stop();
618 }
619 }
620
621 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
631fn fail(tile: &mut TilesetTile, error: Error, cx: &mut LoadContext<'_, '_, Tilesets>) {
635 tile.drop_data();
636 cx.fail(error);
637}
638
639fn 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
649fn 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 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 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 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#[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
749fn 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#[derive(Default)]
761struct Ancestors(HashMap<CanonicalTileID, Held>);
762
763struct Held {
764 ancestor: Weak<Ancestor>,
765 url: String,
768 fetched: Option<Fetched>,
770}
771
772impl Ancestors {
773 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 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
801fn 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
810pub(crate) struct TilesetTile {
814 pub(crate) resource: Resource,
815 fetch: Fetch,
816 failed: bool,
820 caching: Caching,
822 from_network: bool,
825 held: Option<Arc<Ancestor>>,
828 has_data: bool,
830 data_hash: Option<u64>,
833}
834
835enum 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 params: NetworkParams,
847 },
848}
849
850#[derive(Clone, Copy, Debug, PartialEq, Eq)]
851enum Method {
852 Cache,
853 Network,
854}
855
856impl TilesetTile {
857 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 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 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(©.resource.prior_etag);
898 (self.caching, self.data_hash, self.has_data) = (copy.caching, copy.data_hash, true);
899 }
900
901 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 fn drop_data(&mut self) {
919 self.from_network = false;
920 self.held = None;
921 }
922
923 fn is_fresh(&self, now: Timestamp) -> bool {
926 self.from_network && self.caching.is_fresh(now)
927 }
928
929 fn has_lasting_data(&self) -> bool {
933 self.from_network && self.caching.expires.is_none()
934 }
935
936 pub(crate) fn is_idle(&self) -> bool {
938 matches!(self.fetch, Fetch::Idle)
939 }
940
941 pub(crate) fn is_requesting_network(&self) -> bool {
943 matches!(self.fetch, Fetch::Network { .. })
944 }
945
946 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}