Skip to main content

martin_core/tiles/
cache.rs

1use martin_tile_utils::{Encoding, Format, TileCoord};
2
3use crate::cache::{CacheKey, Cacheable, ResourceCache};
4use crate::tiles::Tile;
5
6/// Tile cache for storing rendered tile data, keyed by source ID, tile
7/// coordinate, query string, `Accept`-driven output format, and the
8/// `Accept-Encoding`-negotiated encoding.
9pub type TileCache = ResourceCache<TileCacheKey, Tile>;
10
11/// Optional wrapper for [`TileCache`].
12pub type OptTileCache = Option<TileCache>;
13
14/// Constant representing no tile cache configuration.
15pub const NO_TILE_CACHE: OptTileCache = None;
16
17/// Cache key for one tile entry.
18#[derive(Debug, Hash, PartialEq, Eq, Clone)]
19pub enum TileCacheKey {
20    /// A particular request shapes the bytes that would be served
21    Dynamic {
22        /// Source the tile belongs to, or the comma-separated sources of a composite.
23        source_id: Box<str>,
24        /// Tile coordinate.
25        xyz: TileCoord,
26        /// Request query string, when the source consumes one.
27        query: Option<Box<str>>,
28        /// Format requested via the `Accept` header
29        /// `None` if absent.
30        format: Option<Format>,
31        /// Encoding negotiated via the `Accept-Encoding` header.
32        /// `None` for the tile as the pre-cache pipeline produced it.
33        encoding: Option<Encoding>,
34    },
35
36    /// A tile exactly as its source produced it, before any post-cache processing.
37    Static {
38        /// Source the tile belongs to.
39        source_id: Box<str>,
40        /// Tile coordinate.
41        xyz: TileCoord,
42    },
43}
44
45impl TileCacheKey {
46    /// Key for the bytes a particular request shape produces.
47    #[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    /// Key for a source's own bytes, independent of any request shape.
65    #[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    /// The source this entry belongs to.
74    #[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    /// The coordinate this entry is for.
82    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}