-
Notifications
You must be signed in to change notification settings - Fork 245
Expand file tree
/
Copy pathcache.rs
More file actions
343 lines (277 loc) · 11.2 KB
/
cache.rs
File metadata and controls
343 lines (277 loc) · 11.2 KB
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
use deadpool_redis::{Pool, Runtime};
use redis::AsyncCommands;
use serde::{Deserialize, Serialize};
use solana_client::nonblocking::rpc_client::RpcClient;
use solana_sdk::{account::Account, pubkey::Pubkey};
use tokio::sync::OnceCell;
use crate::error::KoraError;
#[cfg(not(test))]
use crate::state::get_config;
#[cfg(test)]
use crate::tests::config_mock::mock_state::get_config;
const ACCOUNT_CACHE_KEY: &str = "account";
/// Global cache pool instance
static CACHE_POOL: OnceCell<Option<Pool>> = OnceCell::const_new();
/// Cached account data with metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CachedAccount {
pub account: Account,
pub cached_at: i64, // Unix timestamp
}
/// Cache utility for Solana RPC calls
pub struct CacheUtil;
impl CacheUtil {
/// Initialize the cache pool based on configuration
pub async fn init() -> Result<(), KoraError> {
let config = get_config()?;
let pool = if CacheUtil::is_cache_enabled() {
let redis_url = config.kora.cache.url.as_ref().ok_or(KoraError::ConfigError)?;
let cfg = deadpool_redis::Config::from_url(redis_url);
let pool = cfg.create_pool(Some(Runtime::Tokio1)).map_err(|e| {
KoraError::InternalServerError(format!("Failed to create cache pool: {e}"))
})?;
// Test connection
let mut conn = pool.get().await.map_err(|e| {
KoraError::InternalServerError(format!("Failed to connect to cache: {e}"))
})?;
// Simple connection test - try to get a non-existent key
let _: Option<String> = conn.get("__connection_test__").await.map_err(|e| {
KoraError::InternalServerError(format!("Cache connection test failed: {e}"))
})?;
log::info!("Cache initialized successfully with Redis at {redis_url}");
Some(pool)
} else {
log::info!("Cache disabled or no URL configured");
None
};
CACHE_POOL.set(pool).map_err(|_| {
KoraError::InternalServerError("Cache pool already initialized".to_string())
})?;
Ok(())
}
async fn get_connection(pool: &Pool) -> Result<deadpool_redis::Connection, KoraError> {
pool.get().await.map_err(|e| {
KoraError::InternalServerError(format!("Failed to get cache connection: {e}"))
})
}
fn get_account_key(pubkey: &Pubkey) -> String {
format!("{ACCOUNT_CACHE_KEY}:{pubkey}")
}
/// Get account directly from RPC (bypassing cache)
async fn get_account_from_rpc(
rpc_client: &RpcClient,
pubkey: &Pubkey,
) -> Result<Account, KoraError> {
match rpc_client.get_account(pubkey).await {
Ok(account) => Ok(account),
Err(e) => {
let kora_error = e.into();
match kora_error {
KoraError::AccountNotFound(_) => {
Err(KoraError::AccountNotFound(pubkey.to_string()))
}
other_error => Err(other_error),
}
}
}
}
/// Get data from cache
async fn get_from_cache(pool: &Pool, key: &str) -> Result<Option<CachedAccount>, KoraError> {
let mut conn = Self::get_connection(pool).await?;
let cached_data: Option<String> = conn.get(key).await.map_err(|e| {
KoraError::InternalServerError(format!("Failed to get from cache: {e}"))
})?;
match cached_data {
Some(data) => {
let cached_account: CachedAccount = serde_json::from_str(&data).map_err(|e| {
KoraError::InternalServerError(format!(
"Failed to deserialize cached data: {e}"
))
})?;
Ok(Some(cached_account))
}
None => Ok(None),
}
}
/// Get account from RPC and cache it
async fn get_account_from_rpc_and_cache(
rpc_client: &RpcClient,
pubkey: &Pubkey,
pool: &Pool,
ttl: u64,
) -> Result<Account, KoraError> {
let account = Self::get_account_from_rpc(rpc_client, pubkey).await?;
let cache_key = Self::get_account_key(pubkey);
let cached_account =
CachedAccount { account: account.clone(), cached_at: chrono::Utc::now().timestamp() };
if let Err(e) = Self::set_in_cache(pool, &cache_key, &cached_account, ttl).await {
log::warn!("Failed to cache account {pubkey}: {e}");
// Don't fail the request if caching fails
}
Ok(account)
}
/// Set data in cache with TTL
async fn set_in_cache(
pool: &Pool,
key: &str,
data: &CachedAccount,
ttl_seconds: u64,
) -> Result<(), KoraError> {
let mut conn = Self::get_connection(pool).await?;
let serialized = serde_json::to_string(data).map_err(|e| {
KoraError::InternalServerError(format!("Failed to serialize cache data: {e}"))
})?;
conn.set_ex::<_, _, ()>(key, serialized, ttl_seconds).await.map_err(|e| {
KoraError::InternalServerError(format!("Failed to set cache data: {e}"))
})?;
Ok(())
}
/// Check if cache is enabled and available
fn is_cache_enabled() -> bool {
match get_config() {
Ok(config) => config.kora.cache.enabled && config.kora.cache.url.is_some(),
Err(_) => false,
}
}
/// Get account from cache with optional force refresh
pub async fn get_account(
rpc_client: &RpcClient,
pubkey: &Pubkey,
force_refresh: bool,
) -> Result<Account, KoraError> {
let config = get_config()?;
// If cache is disabled or force refresh is requested, go directly to RPC
if !CacheUtil::is_cache_enabled() {
return Self::get_account_from_rpc(rpc_client, pubkey).await;
}
// Get cache pool - if not initialized, fallback to RPC
let pool = match CACHE_POOL.get() {
Some(pool) => pool,
None => {
// Cache not initialized, fallback to RPC
return Self::get_account_from_rpc(rpc_client, pubkey).await;
}
};
let pool = match pool {
Some(pool) => pool,
None => {
// Cache disabled, fallback to RPC
return Self::get_account_from_rpc(rpc_client, pubkey).await;
}
};
if force_refresh {
return Self::get_account_from_rpc_and_cache(
rpc_client,
pubkey,
pool,
config.kora.cache.account_ttl,
)
.await;
}
let cache_key = Self::get_account_key(pubkey);
// Try to get from cache first
if let Ok(Some(cached_account)) = Self::get_from_cache(pool, &cache_key).await {
let current_time = chrono::Utc::now().timestamp();
let cache_age = current_time - cached_account.cached_at;
// Check if cache is still valid
if cache_age < config.kora.cache.account_ttl as i64 {
return Ok(cached_account.account);
}
}
// Cache miss or expired, fetch from RPC
let account = Self::get_account_from_rpc_and_cache(
rpc_client,
pubkey,
pool,
config.kora.cache.account_ttl,
)
.await?;
Ok(account)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tests::{
common::{create_mock_token_account, RpcMockBuilder},
config_mock::ConfigMockBuilder,
};
#[tokio::test]
async fn test_is_cache_enabled_disabled() {
let _m = ConfigMockBuilder::new().with_cache_enabled(false).build_and_setup();
assert!(!CacheUtil::is_cache_enabled());
}
#[tokio::test]
async fn test_is_cache_enabled_no_url() {
let _m = ConfigMockBuilder::new()
.with_cache_enabled(true)
.with_cache_url(None) // Explicitly set no URL
.build_and_setup();
// Without URL, cache should be disabled
assert!(!CacheUtil::is_cache_enabled());
}
#[tokio::test]
async fn test_is_cache_enabled_with_url() {
let _m = ConfigMockBuilder::new()
.with_cache_enabled(true)
.with_cache_url(Some("redis://localhost:6379".to_string()))
.build_and_setup();
// Give time for config to be set up
assert!(CacheUtil::is_cache_enabled());
}
#[tokio::test]
async fn test_get_account_key_format() {
let pubkey = Pubkey::new_unique();
let key = CacheUtil::get_account_key(&pubkey);
assert_eq!(key, format!("account:{pubkey}"));
}
#[tokio::test]
async fn test_get_account_from_rpc_success() {
let pubkey = Pubkey::new_unique();
let expected_account = create_mock_token_account(&pubkey, &Pubkey::new_unique());
let rpc_client = RpcMockBuilder::new().with_account_info(&expected_account).build();
let result = CacheUtil::get_account_from_rpc(&rpc_client, &pubkey).await;
assert!(result.is_ok());
let account = result.unwrap();
assert_eq!(account.lamports, expected_account.lamports);
assert_eq!(account.owner, expected_account.owner);
}
#[tokio::test]
async fn test_get_account_from_rpc_error() {
let pubkey = Pubkey::new_unique();
let rpc_client = RpcMockBuilder::new().with_account_not_found().build();
let result = CacheUtil::get_account_from_rpc(&rpc_client, &pubkey).await;
assert!(result.is_err());
match result.unwrap_err() {
KoraError::AccountNotFound(account_key) => {
assert_eq!(account_key, pubkey.to_string());
}
_ => panic!("Expected AccountNotFound for account not found error"),
}
}
#[tokio::test]
async fn test_get_account_cache_disabled_fallback_to_rpc() {
let _m = ConfigMockBuilder::new().with_cache_enabled(false).build_and_setup();
let pubkey = Pubkey::new_unique();
let expected_account = create_mock_token_account(&pubkey, &Pubkey::new_unique());
let rpc_client = RpcMockBuilder::new().with_account_info(&expected_account).build();
let result = CacheUtil::get_account(&rpc_client, &pubkey, false).await;
assert!(result.is_ok());
let account = result.unwrap();
assert_eq!(account.lamports, expected_account.lamports);
}
#[tokio::test]
async fn test_get_account_force_refresh_bypasses_cache() {
let _m = ConfigMockBuilder::new()
.with_cache_enabled(false) // Force RPC fallback for simplicity
.build_and_setup();
let pubkey = Pubkey::new_unique();
let expected_account = create_mock_token_account(&pubkey, &Pubkey::new_unique());
let rpc_client = RpcMockBuilder::new().with_account_info(&expected_account).build();
// force_refresh = true should always go to RPC
let result = CacheUtil::get_account(&rpc_client, &pubkey, true).await;
assert!(result.is_ok());
let account = result.unwrap();
assert_eq!(account.lamports, expected_account.lamports);
}
}