Skip to main content

martin_core/resources/fonts/
cache.rs

1use bytes::Bytes;
2use martin_tile_utils::Encoding;
3
4use crate::cache::{CacheKey, ResourceCache};
5
6/// Font cache for storing generated font ranges (PBF glyph data).
7pub type FontCache = ResourceCache<FontCacheKey, Bytes>;
8
9/// Optional wrapper for [`FontCache`].
10pub type OptFontCache = Option<FontCache>;
11
12/// Constant representing no font cache configuration.
13pub const NO_FONT_CACHE: OptFontCache = None;
14
15/// Cache key for a font glyph range.
16///
17/// `ids` is the [`crate::fonts::normalize_font_ids`]-normalized font stack
18/// from the request path, with aliases already expanded to their member fonts
19/// so invalidating a font also evicts entries reached through an alias.
20/// Invalidation by font ID matches by token (not substring): invalidating
21/// `"Open Sans"` does not invalidate entries keyed against `"Open Sans Bold"`.
22#[derive(Debug, Hash, PartialEq, Eq, Clone)]
23pub struct FontCacheKey {
24    ids: String,
25    start: u32,
26    end: u32,
27    /// The content encoding the range is cached in, `None` for the glyphs as generated.
28    encoding: Option<Encoding>,
29}
30
31impl FontCacheKey {
32    /// Build a key for the given font stack and glyph range.
33    #[must_use]
34    pub const fn new(ids: String, start: u32, end: u32) -> Self {
35        Self {
36            ids,
37            start,
38            end,
39            encoding: None,
40        }
41    }
42
43    /// The key of the same glyph range compressed with `encoding`.
44    #[must_use]
45    pub fn with_encoding(self, encoding: Encoding) -> Self {
46        Self {
47            encoding: Some(encoding),
48            ..self
49        }
50    }
51}
52
53impl CacheKey for FontCacheKey {
54    const CACHE_NAME: &'static str = "font";
55
56    fn matches_source(&self, source_id: &str) -> bool {
57        self.ids.split(',').any(|s| s == source_id)
58    }
59
60    fn record_outcome(&self, hit: bool) {
61        #[cfg(feature = "metrics")]
62        crate::metrics::CACHE_REQUESTS_TOTAL
63            .with_label_values(&[Self::CACHE_NAME, crate::cache::hit_miss_label(hit)])
64            .inc();
65        #[allow(clippy::if_same_then_else)]
66        if hit {
67            hotpath::gauge!("font_cache_hits").inc(1.0);
68        } else {
69            hotpath::gauge!("font_cache_misses").inc(1.0);
70        }
71    }
72}