1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
use std::fmt::Display;
use std::fmt::{self};
use std::hash::Hash;
use std::num::NonZeroUsize;
use std::sync::Arc;
use lru::LruCache;
use serde::de::DeserializeOwned;
use serde::Serialize;
use tokio::sync::Mutex;
use tokio::time::Instant;
use super::redis::*;
pub(crate) trait KeyType:
Clone + fmt::Debug + fmt::Display + Hash + Eq + Send + Sync
{
}
pub(crate) trait ValueType:
Clone + fmt::Debug + Send + Sync + Serialize + DeserializeOwned
{
}
impl<K> KeyType for K
where
K: Clone + fmt::Debug + fmt::Display + Hash + Eq + Send + Sync,
{
}
impl<V> ValueType for V
where
V: Clone + fmt::Debug + Send + Sync + Serialize + DeserializeOwned,
{
}
#[derive(Clone)]
pub(crate) struct CacheStorage<K: KeyType, V: ValueType> {
caller: String,
inner: Arc<Mutex<LruCache<K, V>>>,
redis: Option<RedisCacheStorage>,
}
impl<K, V> CacheStorage<K, V>
where
K: KeyType,
V: ValueType,
{
pub(crate) async fn new(
max_capacity: NonZeroUsize,
_redis_urls: Option<Vec<String>>,
caller: &str,
) -> Self {
Self {
caller: caller.to_string(),
inner: Arc::new(Mutex::new(LruCache::new(max_capacity))),
redis: if let Some(urls) = _redis_urls {
match RedisCacheStorage::new(urls, None).await {
Err(e) => {
tracing::error!(
"could not open connection to Redis for {} caching: {:?}",
caller,
e
);
None
}
Ok(storage) => Some(storage),
}
} else {
None
},
}
}
pub(crate) async fn get(&self, key: &K) -> Option<V> {
let mut guard = self.inner.lock().await;
let instant_memory = Instant::now();
match guard.get(key) {
Some(v) => {
tracing::info!(
monotonic_counter.apollo_router_cache_hit_count = 1u64,
kind = %self.caller,
storage = &tracing::field::display(CacheStorageName::Memory),
);
let duration = instant_memory.elapsed().as_secs_f64();
tracing::info!(
histogram.apollo_router_cache_hit_time = duration,
kind = %self.caller,
storage = &tracing::field::display(CacheStorageName::Memory),
);
Some(v.clone())
}
None => {
let duration = instant_memory.elapsed().as_secs_f64();
tracing::info!(
histogram.apollo_router_cache_miss_time = duration,
kind = %self.caller,
storage = &tracing::field::display(CacheStorageName::Memory),
);
tracing::info!(
monotonic_counter.apollo_router_cache_miss_count = 1u64,
kind = %self.caller,
storage = &tracing::field::display(CacheStorageName::Memory),
);
let instant_redis = Instant::now();
if let Some(redis) = self.redis.as_ref() {
let inner_key = RedisKey(key.clone());
match redis.get::<K, V>(inner_key).await {
Some(v) => {
guard.put(key.clone(), v.0.clone());
tracing::info!(
monotonic_counter.apollo_router_cache_hit_count = 1u64,
kind = %self.caller,
storage = &tracing::field::display(CacheStorageName::Redis),
);
let duration = instant_redis.elapsed().as_secs_f64();
tracing::info!(
histogram.apollo_router_cache_hit_time = duration,
kind = %self.caller,
storage = &tracing::field::display(CacheStorageName::Redis),
);
Some(v.0)
}
None => {
tracing::info!(
monotonic_counter.apollo_router_cache_miss_count = 1u64,
kind = %self.caller,
storage = &tracing::field::display(CacheStorageName::Redis),
);
let duration = instant_redis.elapsed().as_secs_f64();
tracing::info!(
histogram.apollo_router_cache_miss_time = duration,
kind = %self.caller,
storage = &tracing::field::display(CacheStorageName::Redis),
);
None
}
}
} else {
None
}
}
}
}
pub(crate) async fn insert(&self, key: K, value: V) {
if let Some(redis) = self.redis.as_ref() {
redis
.insert(RedisKey(key.clone()), RedisValue(value.clone()))
.await;
}
self.inner.lock().await.put(key, value);
}
pub(crate) async fn in_memory_keys(&self) -> Vec<K> {
self.inner
.lock()
.await
.iter()
.map(|(k, _)| k.clone())
.collect()
}
#[cfg(test)]
pub(crate) async fn len(&self) -> usize {
self.inner.lock().await.len()
}
}
enum CacheStorageName {
Redis,
Memory,
}
impl Display for CacheStorageName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
CacheStorageName::Redis => write!(f, "redis"),
CacheStorageName::Memory => write!(f, "memory"),
}
}
}