ralph_workflow/agents/opencode_api/
cache.rs1use crate::agents::opencode_api::fetch::fetch_api_catalog;
13use crate::agents::opencode_api::types::ApiCatalog;
14use crate::agents::opencode_api::{CACHE_TTL_ENV_VAR, DEFAULT_CACHE_TTL_SECONDS};
15use std::io;
16use std::path::{Path, PathBuf};
17use thiserror::Error;
18
19#[derive(Debug, Error)]
21pub enum CacheError {
22 #[error("Failed to read cache file: {0}")]
23 ReadError(#[from] std::io::Error),
24
25 #[error("Failed to parse cache JSON: {0}")]
26 ParseError(#[from] serde_json::Error),
27
28 #[error("Failed to fetch API catalog: {0}")]
29 FetchError(String),
30
31 #[error("Cache directory not found")]
32 CacheDirNotFound,
33}
34
35trait CacheEnvironment: Send + Sync {
44 fn cache_dir(&self) -> Option<PathBuf>;
49
50 fn read_file(&self, path: &Path) -> io::Result<String>;
52
53 fn write_file(&self, path: &Path, content: &str) -> io::Result<()>;
55
56 fn create_dir_all(&self, path: &Path) -> io::Result<()>;
58}
59
60#[derive(Debug, Default, Clone, Copy)]
65struct RealCacheEnvironment;
66
67impl CacheEnvironment for RealCacheEnvironment {
68 fn cache_dir(&self) -> Option<PathBuf> {
69 dirs::cache_dir().map(|d| d.join("ralph-workflow"))
70 }
71
72 fn read_file(&self, path: &Path) -> io::Result<String> {
73 std::fs::read_to_string(path)
74 }
75
76 fn write_file(&self, path: &Path, content: &str) -> io::Result<()> {
77 std::fs::write(path, content)
78 }
79
80 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
81 std::fs::create_dir_all(path)
82 }
83}
84
85fn cache_file_path_with_env(env: &dyn CacheEnvironment) -> Result<PathBuf, CacheError> {
87 let cache_dir = env.cache_dir().ok_or(CacheError::CacheDirNotFound)?;
88
89 env.create_dir_all(&cache_dir)?;
91
92 Ok(cache_dir.join("opencode-api-cache.json"))
93}
94
95pub fn load_api_catalog() -> Result<ApiCatalog, CacheError> {
106 load_api_catalog_with_env(&RealCacheEnvironment)
107}
108
109fn load_api_catalog_with_env(env: &dyn CacheEnvironment) -> Result<ApiCatalog, CacheError> {
111 let ttl_seconds = std::env::var(CACHE_TTL_ENV_VAR)
112 .ok()
113 .and_then(|v| v.parse().ok())
114 .unwrap_or(DEFAULT_CACHE_TTL_SECONDS);
115
116 let cache_path = cache_file_path_with_env(env)?;
117
118 if let Ok(cached) = load_cached_catalog_with_env(env, &cache_path, ttl_seconds) {
120 return Ok(cached);
121 }
122
123 fetch_api_catalog()
125}
126
127fn load_cached_catalog_with_env(
131 env: &dyn CacheEnvironment,
132 path: &Path,
133 ttl_seconds: u64,
134) -> Result<ApiCatalog, CacheError> {
135 let content = env.read_file(path)?;
136
137 let mut catalog: ApiCatalog = serde_json::from_str(&content)?;
138
139 catalog.ttl_seconds = ttl_seconds;
141
142 if catalog.is_expired() {
144 match fetch_api_catalog() {
146 Ok(fresh) => return Ok(fresh),
147 Err(e) => {
148 if let Some(cached_at) = catalog.cached_at {
150 let now = chrono::Utc::now();
151 let stale_days =
152 (now.signed_duration_since(cached_at).num_seconds() / 86400).abs();
153 if stale_days < 7 {
154 eprintln!(
155 "Warning: Failed to fetch fresh OpenCode API catalog ({}), using stale cache from {} days ago",
156 e, stale_days
157 );
158 return Ok(catalog);
159 }
160 }
161 return Err(CacheError::FetchError(e.to_string()));
162 }
163 }
164 }
165
166 Ok(catalog)
167}
168
169pub fn save_catalog(catalog: &ApiCatalog) -> Result<(), CacheError> {
174 save_catalog_with_env(catalog, &RealCacheEnvironment)
175}
176
177fn save_catalog_with_env(
179 catalog: &ApiCatalog,
180 env: &dyn CacheEnvironment,
181) -> Result<(), CacheError> {
182 #[derive(serde::Serialize)]
183 struct SerializableCatalog<'a> {
184 providers: &'a std::collections::HashMap<String, crate::agents::opencode_api::Provider>,
185 models: &'a std::collections::HashMap<String, Vec<crate::agents::opencode_api::Model>>,
186 }
187
188 let cache_path = cache_file_path_with_env(env)?;
189 let serializable = SerializableCatalog {
190 providers: &catalog.providers,
191 models: &catalog.models,
192 };
193 let content = serde_json::to_string_pretty(&serializable)?;
194 env.write_file(&cache_path, &content)?;
195 Ok(())
196}
197
198#[cfg(test)]
199mod tests {
200 use super::*;
201 use crate::agents::opencode_api::types::{Model, Provider};
202 use std::collections::HashMap;
203 use std::sync::{Arc, RwLock};
204
205 #[derive(Debug, Clone, Default)]
211 struct MemoryCacheEnvironment {
212 cache_dir: Option<PathBuf>,
213 files: Arc<RwLock<HashMap<PathBuf, String>>>,
215 dirs: Arc<RwLock<std::collections::HashSet<PathBuf>>>,
217 }
218
219 impl MemoryCacheEnvironment {
220 fn new() -> Self {
222 Self::default()
223 }
224
225 #[must_use]
227 fn with_cache_dir<P: Into<PathBuf>>(mut self, path: P) -> Self {
228 self.cache_dir = Some(path.into());
229 self
230 }
231
232 #[must_use]
234 fn with_file<P: Into<PathBuf>, S: Into<String>>(self, path: P, content: S) -> Self {
235 let path = path.into();
236 self.files.write().unwrap().insert(path, content.into());
237 self
238 }
239
240 fn get_file(&self, path: &Path) -> Option<String> {
242 self.files.read().unwrap().get(path).cloned()
243 }
244
245 fn was_written(&self, path: &Path) -> bool {
247 self.files.read().unwrap().contains_key(path)
248 }
249 }
250
251 impl CacheEnvironment for MemoryCacheEnvironment {
252 fn cache_dir(&self) -> Option<PathBuf> {
253 self.cache_dir.clone()
254 }
255
256 fn read_file(&self, path: &Path) -> io::Result<String> {
257 self.files
258 .read()
259 .unwrap()
260 .get(path)
261 .cloned()
262 .ok_or_else(|| {
263 io::Error::new(
264 io::ErrorKind::NotFound,
265 format!("File not found: {}", path.display()),
266 )
267 })
268 }
269
270 fn write_file(&self, path: &Path, content: &str) -> io::Result<()> {
271 self.files
272 .write()
273 .unwrap()
274 .insert(path.to_path_buf(), content.to_string());
275 Ok(())
276 }
277
278 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
279 self.dirs.write().unwrap().insert(path.to_path_buf());
280 Ok(())
281 }
282 }
283
284 fn create_test_catalog() -> ApiCatalog {
285 let mut providers = HashMap::new();
286 providers.insert(
287 "test".to_string(),
288 Provider {
289 id: "test".to_string(),
290 name: "Test Provider".to_string(),
291 description: "Test".to_string(),
292 },
293 );
294
295 let mut models = HashMap::new();
296 models.insert(
297 "test".to_string(),
298 vec![Model {
299 id: "test-model".to_string(),
300 name: "Test Model".to_string(),
301 description: "Test".to_string(),
302 context_length: None,
303 }],
304 );
305
306 ApiCatalog {
307 providers,
308 models,
309 cached_at: Some(chrono::Utc::now()),
310 ttl_seconds: DEFAULT_CACHE_TTL_SECONDS,
311 }
312 }
313
314 #[test]
315 fn test_memory_environment_file_operations() {
316 let env = MemoryCacheEnvironment::new().with_cache_dir("/test/cache");
318
319 let path = Path::new("/test/file.txt");
320
321 env.write_file(path, "test content").unwrap();
323
324 assert_eq!(env.read_file(path).unwrap(), "test content");
326 assert!(env.was_written(path));
327 }
328
329 #[test]
330 fn test_memory_environment_with_prepopulated_file() {
331 let env = MemoryCacheEnvironment::new()
333 .with_cache_dir("/test/cache")
334 .with_file("/test/existing.txt", "existing content");
335
336 assert_eq!(
337 env.read_file(Path::new("/test/existing.txt")).unwrap(),
338 "existing content"
339 );
340 }
341
342 #[test]
343 fn test_cache_file_path_with_memory_env() {
344 let env = MemoryCacheEnvironment::new().with_cache_dir("/test/cache");
346
347 let path = cache_file_path_with_env(&env).unwrap();
348 assert_eq!(path, PathBuf::from("/test/cache/opencode-api-cache.json"));
349 }
350
351 #[test]
352 fn test_cache_file_path_without_cache_dir() {
353 let env = MemoryCacheEnvironment::new(); let result = cache_file_path_with_env(&env);
357 assert!(matches!(result, Err(CacheError::CacheDirNotFound)));
358 }
359
360 #[test]
361 fn test_save_and_load_catalog_with_memory_env() {
362 let env = MemoryCacheEnvironment::new().with_cache_dir("/test/cache");
364
365 let catalog = create_test_catalog();
366
367 save_catalog_with_env(&catalog, &env).unwrap();
369
370 let cache_path = Path::new("/test/cache/opencode-api-cache.json");
372 assert!(env.was_written(cache_path));
373
374 let content = env.get_file(cache_path).unwrap();
376 let loaded: ApiCatalog = serde_json::from_str(&content).unwrap();
377
378 assert_eq!(loaded.providers.len(), catalog.providers.len());
379 assert!(loaded.has_provider("test"));
380 assert!(loaded.has_model("test", "test-model"));
381 }
382
383 #[test]
384 fn test_catalog_serialization() {
385 let catalog = create_test_catalog();
387
388 #[derive(serde::Serialize)]
390 struct SerializableCatalog<'a> {
391 providers: &'a std::collections::HashMap<String, crate::agents::opencode_api::Provider>,
392 models: &'a std::collections::HashMap<String, Vec<crate::agents::opencode_api::Model>>,
393 }
394 let serializable = SerializableCatalog {
395 providers: &catalog.providers,
396 models: &catalog.models,
397 };
398 let json = serde_json::to_string(&serializable).unwrap();
399 let deserialized: ApiCatalog = serde_json::from_str(&json).unwrap();
400
401 assert_eq!(deserialized.providers.len(), catalog.providers.len());
402 assert_eq!(deserialized.models.len(), catalog.models.len());
403 }
404
405 #[test]
406 fn test_expired_catalog_detection() {
407 let mut catalog = create_test_catalog();
409
410 assert!(!catalog.is_expired());
412
413 catalog.cached_at = Some(
415 chrono::Utc::now() - chrono::Duration::seconds(DEFAULT_CACHE_TTL_SECONDS as i64 + 1),
416 );
417 assert!(catalog.is_expired());
418 }
419
420 #[test]
421 fn test_real_environment_returns_path() {
422 let env = RealCacheEnvironment;
424 let cache_dir = env.cache_dir();
425
426 if let Some(dir) = cache_dir {
428 assert!(dir.to_string_lossy().contains("ralph-workflow"));
429 }
430 }
431
432 #[test]
433 fn test_production_cache_file_path_returns_correct_filename() {
434 let env = RealCacheEnvironment;
436 let path = cache_file_path_with_env(&env).unwrap();
437 assert!(
438 path.ends_with("opencode-api-cache.json"),
439 "cache file should end with opencode-api-cache.json"
440 );
441 }
442}