martin_core/tiles/
cache.rs1use martin_tile_utils::{Encoding, Format, TileCoord};
2
3use crate::cache::{CacheKey, Cacheable, ResourceCache};
4use crate::tiles::Tile;
5
6pub type TileCache = ResourceCache<TileCacheKey, Tile>;
10
11pub type OptTileCache = Option<TileCache>;
13
14pub const NO_TILE_CACHE: OptTileCache = None;
16
17#[derive(Debug, Hash, PartialEq, Eq, Clone)]
19pub enum TileCacheKey {
20 Dynamic {
22 source_id: Box<str>,
24 xyz: TileCoord,
26 query: Option<Box<str>>,
28 format: Option<Format>,
31 encoding: Option<Encoding>,
34 },
35
36 Static {
38 source_id: Box<str>,
40 xyz: TileCoord,
42 },
43}
44
45impl TileCacheKey {
46 #[must_use]
48 pub fn new_request_dynamic(
49 source_id: impl Into<Box<str>>,
50 xyz: TileCoord,
51 query: Option<Box<str>>,
52 format: Option<Format>,
53 encoding: Option<Encoding>,
54 ) -> Self {
55 Self::Dynamic {
56 source_id: source_id.into(),
57 xyz,
58 query,
59 format,
60 encoding,
61 }
62 }
63
64 #[must_use]
66 pub fn new_request_static(source_id: impl Into<Box<str>>, xyz: TileCoord) -> Self {
67 Self::Static {
68 source_id: source_id.into(),
69 xyz,
70 }
71 }
72
73 #[must_use]
75 pub fn source_id(&self) -> &str {
76 match self {
77 Self::Dynamic { source_id, .. } | Self::Static { source_id, .. } => source_id,
78 }
79 }
80
81 pub const fn xyz(&self) -> TileCoord {
83 match self {
84 Self::Dynamic { xyz, .. } | Self::Static { xyz, .. } => *xyz,
85 }
86 }
87}
88
89impl CacheKey for TileCacheKey {
90 const CACHE_NAME: &'static str = "tile";
91
92 fn matches_source(&self, source_id: &str) -> bool {
93 self.source_id().split(',').any(|s| s == source_id)
94 }
95
96 fn record_outcome(&self, hit: bool) {
97 #[cfg(feature = "metrics")]
98 crate::metrics::TILE_CACHE_REQUESTS_TOTAL
99 .with_label_values(&[
100 Self::CACHE_NAME,
101 crate::cache::hit_miss_label(hit),
102 crate::metrics::ZOOM_LABELS[self.xyz().z() as usize],
103 ])
104 .inc();
105 #[allow(clippy::if_same_then_else)]
106 if hit {
107 hotpath::gauge!("tile_cache_hits").inc(1.0);
108 } else {
109 hotpath::gauge!("tile_cache_misses").inc(1.0);
110 }
111 }
112}
113
114impl Cacheable for Tile {
115 fn weight(&self) -> u32 {
116 self.data.len().try_into().unwrap_or(u32::MAX)
117 }
118}