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
//! Configuration caching layer
//!
//! Caches parsed configuration files to improve performance.
//! Uses file-based cache with TTL support.
use crate::cache::{CacheInvalidationStrategy, CacheManager};
use crate::error::{StorageError, StorageResult};
use serde_json::Value;
use std::path::Path;
use std::sync::Arc;
use tracing::{debug, info};
/// Configuration cache
///
/// Caches parsed configuration files to avoid redundant parsing.
/// Supports both global and project-level configuration caching.
pub struct ConfigCache {
cache: Arc<CacheManager>,
ttl_seconds: u64,
}
impl ConfigCache {
/// Create a new config cache
///
/// # Arguments
///
/// * `cache_dir` - Directory to store cache files
/// * `ttl_seconds` - Time-to-live for cache entries (default: 3600 = 1 hour)
///
/// # Errors
///
/// Returns error if cache directory cannot be created
pub fn new(cache_dir: impl AsRef<Path>, ttl_seconds: u64) -> StorageResult<Self> {
let cache = CacheManager::new(cache_dir)?;
Ok(Self {
cache: Arc::new(cache),
ttl_seconds,
})
}
/// Get a cached configuration
///
/// # Arguments
///
/// * `config_path` - Path to configuration file
///
/// # Returns
///
/// Returns cached configuration if found and not expired, None otherwise
pub fn get(&self, config_path: &Path) -> StorageResult<Option<Value>> {
let cache_key = self.make_cache_key(config_path);
match self.cache.get(&cache_key) {
Ok(Some(cached_json)) => {
match serde_json::from_str::<Value>(&cached_json) {
Ok(config) => {
debug!("Cache hit for config: {}", config_path.display());
Ok(Some(config))
}
Err(e) => {
debug!("Failed to deserialize cached config: {}", e);
// Invalidate corrupted cache entry
let _ = self.cache.invalidate(&cache_key);
Ok(None)
}
}
}
Ok(None) => {
debug!("Cache miss for config: {}", config_path.display());
Ok(None)
}
Err(e) => {
debug!("Cache lookup error: {}", e);
Ok(None)
}
}
}
/// Cache a configuration
///
/// # Arguments
///
/// * `config_path` - Path to configuration file
/// * `config` - Parsed configuration to cache
///
/// # Errors
///
/// Returns error if configuration cannot be cached
pub fn set(&self, config_path: &Path, config: &Value) -> StorageResult<()> {
let cache_key = self.make_cache_key(config_path);
let config_json = serde_json::to_string(config)
.map_err(|e| StorageError::internal(format!("Failed to serialize config: {}", e)))?;
let json_len = config_json.len();
self.cache.set(
&cache_key,
config_json,
CacheInvalidationStrategy::Ttl(self.ttl_seconds),
)?;
debug!(
"Cached config: {} ({} bytes)",
config_path.display(),
json_len
);
Ok(())
}
/// Invalidate a cached configuration
///
/// # Arguments
///
/// * `config_path` - Path to configuration file
///
/// # Returns
///
/// Returns Ok(true) if entry was deleted, Ok(false) if entry didn't exist
pub fn invalidate(&self, config_path: &Path) -> StorageResult<bool> {
let cache_key = self.make_cache_key(config_path);
self.cache.invalidate(&cache_key)
}
/// Clear all cached configurations
///
/// # Errors
///
/// Returns error if cache cannot be cleared
pub fn clear(&self) -> StorageResult<()> {
self.cache.clear()
}
/// Clean up expired cache entries
///
/// # Returns
///
/// Returns the number of entries cleaned up
pub fn cleanup_expired(&self) -> StorageResult<usize> {
let cleaned = self.cache.cleanup_expired()?;
if cleaned > 0 {
info!("Cleaned up {} expired config cache entries", cleaned);
}
Ok(cleaned)
}
/// Create a cache key from config path
fn make_cache_key(&self, config_path: &Path) -> String {
let path_str = config_path.to_string_lossy();
let sanitized = path_str
.chars()
.map(|c| {
if c.is_alphanumeric() || c == '_' || c == '-' || c == '.' {
c
} else {
'_'
}
})
.collect::<String>();
format!("config_{}", sanitized)
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
#[test]
fn test_cache_set_and_get() -> StorageResult<()> {
let temp_dir = TempDir::new().unwrap();
let cache = ConfigCache::new(temp_dir.path(), 3600)?;
let config_path = std::path::PathBuf::from("config.yaml");
let config = serde_json::json!({
"key": "value",
"nested": {
"setting": 42
}
});
// Cache config
cache.set(&config_path, &config)?;
// Retrieve from cache
let cached = cache.get(&config_path)?;
assert!(cached.is_some());
assert_eq!(cached.unwrap()["key"], "value");
Ok(())
}
#[test]
fn test_cache_miss() -> StorageResult<()> {
let temp_dir = TempDir::new().unwrap();
let cache = ConfigCache::new(temp_dir.path(), 3600)?;
let config_path = std::path::PathBuf::from("nonexistent.yaml");
// Try to get non-existent entry
let cached = cache.get(&config_path)?;
assert!(cached.is_none());
Ok(())
}
#[test]
fn test_cache_invalidate() -> StorageResult<()> {
let temp_dir = TempDir::new().unwrap();
let cache = ConfigCache::new(temp_dir.path(), 3600)?;
let config_path = std::path::PathBuf::from("config.yaml");
let config = serde_json::json!({"key": "value"});
// Cache config
cache.set(&config_path, &config)?;
// Invalidate
let invalidated = cache.invalidate(&config_path)?;
assert!(invalidated);
// Should be gone now
let cached = cache.get(&config_path)?;
assert!(cached.is_none());
Ok(())
}
#[test]
fn test_cache_clear() -> StorageResult<()> {
let temp_dir = TempDir::new().unwrap();
let cache = ConfigCache::new(temp_dir.path(), 3600)?;
let config_path1 = std::path::PathBuf::from("config1.yaml");
let config_path2 = std::path::PathBuf::from("config2.yaml");
let config = serde_json::json!({"key": "value"});
// Cache multiple configs
cache.set(&config_path1, &config)?;
cache.set(&config_path2, &config)?;
// Clear all
cache.clear()?;
// Both should be gone
assert!(cache.get(&config_path1)?.is_none());
assert!(cache.get(&config_path2)?.is_none());
Ok(())
}
}