Skip to main content

martin_core/resources/sprites/
cache.rs

1use actix_web::web::Bytes;
2
3use crate::cache::{CacheKey, Cacheable, ResourceCache};
4
5/// Sprite cache for storing generated sprite sheets.
6pub type SpriteCache = ResourceCache<SpriteCacheKey, Bytes>;
7
8/// Optional wrapper for [`SpriteCache`].
9pub type OptSpriteCache = Option<SpriteCache>;
10
11/// Constant representing no sprite cache configuration.
12pub const NO_SPRITE_CACHE: OptSpriteCache = None;
13
14/// Cache key for sprite data.
15///
16/// `ids` is the comma-joined list of sprite source IDs from the request path,
17/// normalized (sorted and deduplicated) via [`crate::sprites::normalize_sprite_ids`]
18/// so that equivalent requests - different id order, repeated ids - share one
19/// cache entry, with aliases already expanded to their member sources so
20/// invalidating a source also evicts entries reached through an alias.
21/// Invalidation by source ID matches by token (not substring):
22/// invalidating `"foo"` does not invalidate entries keyed against `"foobar"`.
23#[derive(Debug, Hash, PartialEq, Eq, Clone)]
24pub struct SpriteCacheKey {
25    ids: String,
26    as_sdf: bool,
27    as_json: bool,
28}
29
30impl SpriteCacheKey {
31    /// Build a key from the request fields.
32    #[must_use]
33    pub const fn new(ids: String, as_sdf: bool, as_json: bool) -> Self {
34        Self { ids, as_sdf, as_json }
35    }
36}
37
38impl CacheKey for SpriteCacheKey {
39    const CACHE_NAME: &'static str = "sprite";
40
41    fn matches_source(&self, source_id: &str) -> bool {
42        self.ids.split(',').any(|s| s == source_id)
43    }
44
45    fn record_outcome(&self, hit: bool) {
46        #[cfg(feature = "metrics")]
47        crate::metrics::CACHE_REQUESTS_TOTAL
48            .with_label_values(&[Self::CACHE_NAME, crate::cache::hit_miss_label(hit)])
49            .inc();
50        #[allow(clippy::if_same_then_else)]
51        if hit {
52            hotpath::gauge!("sprite_cache_hits").inc(1.0);
53        } else {
54            hotpath::gauge!("sprite_cache_misses").inc(1.0);
55        }
56    }
57}
58
59impl Cacheable for Bytes {
60    fn weight(&self) -> u32 {
61        self.len().try_into().unwrap_or(u32::MAX)
62    }
63}