Line data Source code
1 : use crate::cache::common::{Cache, count_cache_insert, count_cache_outcome, eviction_listener};
2 : use crate::cache::{Cached, ControlPlaneResult, CplaneExpiry};
3 : use crate::config::CacheOptions;
4 : use crate::control_plane::NodeInfo;
5 : use crate::metrics::{CacheKind, Metrics};
6 : use crate::types::EndpointCacheKey;
7 :
8 : pub(crate) struct NodeInfoCache(moka::sync::Cache<EndpointCacheKey, ControlPlaneResult<NodeInfo>>);
9 : pub(crate) type CachedNodeInfo = Cached<&'static NodeInfoCache, NodeInfo>;
10 :
11 : impl Cache for NodeInfoCache {
12 : type Key = EndpointCacheKey;
13 : type Value = ControlPlaneResult<NodeInfo>;
14 :
15 6 : fn invalidate(&self, info: &EndpointCacheKey) {
16 6 : self.0.invalidate(info);
17 6 : }
18 : }
19 :
20 : impl NodeInfoCache {
21 13 : pub fn new(config: CacheOptions) -> Self {
22 13 : let builder = moka::sync::Cache::builder()
23 13 : .name("node_info_cache")
24 13 : .expire_after(CplaneExpiry::default());
25 13 : let builder = config.moka(builder);
26 :
27 13 : if let Some(size) = config.size {
28 13 : Metrics::get()
29 13 : .cache
30 13 : .capacity
31 13 : .set(CacheKind::NodeInfo, size as i64);
32 13 : }
33 :
34 13 : let builder = builder
35 13 : .eviction_listener(|_k, _v, cause| eviction_listener(CacheKind::NodeInfo, cause));
36 :
37 13 : Self(builder.build())
38 13 : }
39 :
40 17 : pub fn insert(&self, key: EndpointCacheKey, value: ControlPlaneResult<NodeInfo>) {
41 17 : count_cache_insert(CacheKind::NodeInfo);
42 17 : self.0.insert(key, value);
43 17 : }
44 :
45 0 : pub fn get(&self, key: &EndpointCacheKey) -> Option<ControlPlaneResult<NodeInfo>> {
46 0 : count_cache_outcome(CacheKind::NodeInfo, self.0.get(key))
47 0 : }
48 :
49 0 : pub fn get_entry(
50 0 : &'static self,
51 0 : key: &EndpointCacheKey,
52 0 : ) -> Option<ControlPlaneResult<CachedNodeInfo>> {
53 0 : self.get(key).map(|res| {
54 0 : res.map(|value| Cached {
55 0 : token: Some((self, key.clone())),
56 0 : value,
57 0 : })
58 0 : })
59 0 : }
60 : }
|