cat_gateway/db/index/queries/caches/assets/
native.rs

1//! Cache for Native Assets by Stake Address Queries
2use std::sync::Arc;
3
4use moka::policy::EvictionPolicy;
5
6use crate::{
7    db::{index::queries::GetAssetsByStakeAddressQuery, types::DbStakeAddress},
8    metrics::caches::native_assets::{native_assets_hits_inc, native_assets_misses_inc},
9    service::utilities::cache::Cache,
10    settings::Settings,
11};
12
13/// Cache for TXO Native Assets by Stake Address Queries for Persistent Sessions
14pub(crate) struct AssetsNativeCache {
15    /// Interior cache type.
16    inner: Cache<DbStakeAddress, Arc<Vec<GetAssetsByStakeAddressQuery>>>,
17}
18
19impl AssetsNativeCache {
20    /// Name for cache
21    const CACHE_NAME: &str = "Cardano UTXO Native Assets Cache";
22
23    /// New Native Assets Cache instance.
24    ///
25    /// # Arguments
26    /// * `is_persistent` - If the `CassandraSession` is persistent.
27    ///
28    /// Disables the cache for Volatile sessions (`is_persistent` is `false`).
29    pub(crate) fn new(is_persistent: bool) -> Self {
30        let max_capacity = if is_persistent {
31            Settings::cardano_assets_cache().native_assets_cache_size()
32        } else {
33            0
34        };
35        Self {
36            inner: Cache::new(Self::CACHE_NAME, EvictionPolicy::lru(), max_capacity),
37        }
38    }
39
40    /// Get Native Assets entry from Cache.
41    pub(crate) fn get(
42        &self,
43        stake_address: &DbStakeAddress,
44    ) -> Option<Arc<Vec<GetAssetsByStakeAddressQuery>>> {
45        // Exit if cache is not enabled to avoid metric updates.
46        if !self.inner.is_enabled() {
47            return None;
48        }
49        self.inner
50            .get(stake_address)
51            .inspect(|_| native_assets_hits_inc())
52            .or_else(|| {
53                native_assets_misses_inc();
54                None
55            })
56    }
57
58    /// Insert Native Assets entry in Cache.
59    pub(crate) fn insert(
60        &self,
61        stake_address: DbStakeAddress,
62        rows: Arc<Vec<GetAssetsByStakeAddressQuery>>,
63    ) {
64        self.inner.insert(stake_address, rows);
65    }
66
67    /// Clear (invalidates) the cache entries.
68    pub(crate) fn clear_cache(&self) {
69        self.inner.clear_cache();
70    }
71
72    /// Size of TXO Assets cache.
73    pub(crate) fn weighted_size(&self) -> u64 {
74        self.inner.weighted_size()
75    }
76
77    /// Number of entries in TXO Assets cache.
78    pub(crate) fn entry_count(&self) -> u64 {
79        self.inner.entry_count()
80    }
81}