Skip to main content

ralph_workflow/agents/opencode_api/
cache.rs

1//! OpenCode API catalog caching.
2//!
3//! This module handles file-based caching of the OpenCode model catalog
4//! with TTL-based expiration.
5//!
6//! # Dependency Injection
7//!
8//! The [`CacheEnvironment`] trait abstracts filesystem operations for caching,
9//! enabling pure unit tests without real filesystem access. Production code
10//! uses [`RealCacheEnvironment`], tests use [`MemoryCacheEnvironment`].
11
12use 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/// Errors that can occur when loading the API catalog.
20#[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
35/// Trait for cache environment access.
36///
37/// This trait abstracts filesystem operations needed for caching:
38/// - Cache directory resolution
39/// - File reading and writing
40/// - Directory creation
41///
42/// By injecting this trait, cache code becomes pure and testable.
43trait CacheEnvironment: Send + Sync {
44    /// Get the cache directory for ralph-workflow.
45    ///
46    /// In production, returns `~/.cache/ralph-workflow` or equivalent.
47    /// Returns `None` if the cache directory cannot be determined.
48    fn cache_dir(&self) -> Option<PathBuf>;
49
50    /// Read the contents of a file.
51    fn read_file(&self, path: &Path) -> io::Result<String>;
52
53    /// Write content to a file.
54    fn write_file(&self, path: &Path, content: &str) -> io::Result<()>;
55
56    /// Create directories recursively.
57    fn create_dir_all(&self, path: &Path) -> io::Result<()>;
58}
59
60/// Production implementation of [`CacheEnvironment`].
61///
62/// Uses the `dirs` crate for cache directory resolution and `std::fs` for
63/// all file operations.
64#[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
85/// Get the cache file path using a custom environment.
86fn cache_file_path_with_env(env: &dyn CacheEnvironment) -> Result<PathBuf, CacheError> {
87    let cache_dir = env.cache_dir().ok_or(CacheError::CacheDirNotFound)?;
88
89    // Ensure cache directory exists
90    env.create_dir_all(&cache_dir)?;
91
92    Ok(cache_dir.join("opencode-api-cache.json"))
93}
94
95/// Load the API catalog from cache or fetch if expired.
96///
97/// This function:
98/// 1. Checks if a cached catalog exists
99/// 2. If cached and not expired, returns the cached version
100/// 3. If expired or missing, fetches a fresh catalog from the API
101/// 4. Saves the fetched catalog to disk for future use
102///
103/// Gracefully degrades on network errors: if fetching fails but a stale
104/// cache exists (< 7 days old), it will be used with a warning.
105pub fn load_api_catalog() -> Result<ApiCatalog, CacheError> {
106    load_api_catalog_with_env(&RealCacheEnvironment)
107}
108
109/// Load the API catalog using a custom environment.
110fn 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    // Try to load from cache
119    if let Ok(cached) = load_cached_catalog_with_env(env, &cache_path, ttl_seconds) {
120        return Ok(cached);
121    }
122
123    // Cache miss or expired, fetch from API
124    fetch_api_catalog()
125}
126
127/// Load a cached catalog from disk.
128///
129/// Returns an error if the cache file doesn't exist, is invalid, or is expired.
130fn 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    // Set the TTL for expiration checking
140    catalog.ttl_seconds = ttl_seconds;
141
142    // Check if expired
143    if catalog.is_expired() {
144        // Try to fetch fresh catalog, but use stale cache if fetch fails
145        match fetch_api_catalog() {
146            Ok(fresh) => return Ok(fresh),
147            Err(e) => {
148                // Use stale cache if it's less than 7 days old
149                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
169/// Save the API catalog to disk.
170///
171/// Note: Only serializes the providers and models data from the API.
172/// The cached_at timestamp and ttl_seconds are not persisted.
173pub fn save_catalog(catalog: &ApiCatalog) -> Result<(), CacheError> {
174    save_catalog_with_env(catalog, &RealCacheEnvironment)
175}
176
177/// Save the API catalog using a custom environment.
178fn 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    /// In-memory implementation of [`CacheEnvironment`] for testing.
206    ///
207    /// Provides complete isolation from the real filesystem:
208    /// - Configurable cache directory path
209    /// - In-memory file storage
210    #[derive(Debug, Clone, Default)]
211    struct MemoryCacheEnvironment {
212        cache_dir: Option<PathBuf>,
213        /// In-memory file storage.
214        files: Arc<RwLock<HashMap<PathBuf, String>>>,
215        /// Directories that have been created.
216        dirs: Arc<RwLock<std::collections::HashSet<PathBuf>>>,
217    }
218
219    impl MemoryCacheEnvironment {
220        /// Create a new memory environment with no paths configured.
221        fn new() -> Self {
222            Self::default()
223        }
224
225        /// Set the cache directory path.
226        #[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        /// Pre-populate a file in memory.
233        #[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        /// Get the contents of a file (for test assertions).
241        fn get_file(&self, path: &Path) -> Option<String> {
242            self.files.read().unwrap().get(path).cloned()
243        }
244
245        /// Check if a file was written (for test assertions).
246        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        // Test that MemoryCacheEnvironment correctly implements file operations
317        let env = MemoryCacheEnvironment::new().with_cache_dir("/test/cache");
318
319        let path = Path::new("/test/file.txt");
320
321        // Write file
322        env.write_file(path, "test content").unwrap();
323
324        // File can be read
325        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        // Test that files can be prepopulated for testing
332        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        // Test that cache_file_path_with_env returns correct path
345        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        // Test that cache_file_path_with_env returns error without cache dir
354        let env = MemoryCacheEnvironment::new(); // No cache dir set
355
356        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        // Test save and load using MemoryCacheEnvironment
363        let env = MemoryCacheEnvironment::new().with_cache_dir("/test/cache");
364
365        let catalog = create_test_catalog();
366
367        // Save catalog
368        save_catalog_with_env(&catalog, &env).unwrap();
369
370        // Verify file was written
371        let cache_path = Path::new("/test/cache/opencode-api-cache.json");
372        assert!(env.was_written(cache_path));
373
374        // Verify content is valid JSON that can be parsed
375        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        // Test that catalog serialization produces valid JSON
386        let catalog = create_test_catalog();
387
388        // Serialize using the same method as save_catalog
389        #[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        // Test that expiration detection works correctly
408        let mut catalog = create_test_catalog();
409
410        // Fresh catalog should not be expired
411        assert!(!catalog.is_expired());
412
413        // Old catalog should be expired
414        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        // Test that RealCacheEnvironment returns a valid path
423        let env = RealCacheEnvironment;
424        let cache_dir = env.cache_dir();
425
426        // Should return Some path (unless running in weird environment)
427        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        // Test that the production cache_file_path returns a path ending in the expected filename
435        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}