aptu-core 0.2.21

Core library for Aptu - OSS issue triage with AI assistance
Documentation
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
// SPDX-License-Identifier: Apache-2.0

//! TTL-based file caching for GitHub API responses.
//!
//! Stores issue and repository data as JSON files with embedded metadata
//! (timestamp, optional etag). Cache entries are validated against TTL settings
//! from configuration.

use std::fs;
use std::path::PathBuf;
use std::sync::Once;

use anyhow::{Context, Result};
use chrono::{DateTime, Duration, Utc};
use serde::{Deserialize, Serialize};
use tracing::warn;

/// Ensures the cache unavailable warning is only emitted once.
static CACHE_UNAVAILABLE_WARNING: Once = Once::new();

/// Default TTL for issue cache entries (in minutes).
pub const DEFAULT_ISSUE_TTL_MINS: i64 = 60;

/// Default TTL for repository cache entries (in hours).
pub const DEFAULT_REPO_TTL_HOURS: i64 = 24;

/// Default TTL for model registry cache entries (in seconds).
pub const DEFAULT_MODEL_TTL_SECS: u64 = 86400;

/// Default TTL for security finding cache entries (in days).
pub const DEFAULT_SECURITY_TTL_DAYS: i64 = 7;

/// A cached entry with metadata.
///
/// Wraps cached data with timestamp and optional etag for validation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheEntry<T> {
    /// The cached data.
    pub data: T,
    /// When the entry was cached.
    pub cached_at: DateTime<Utc>,
    /// Optional `ETag` for future conditional requests.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub etag: Option<String>,
}

impl<T> CacheEntry<T> {
    /// Create a new cache entry.
    pub fn new(data: T) -> Self {
        Self {
            data,
            cached_at: Utc::now(),
            etag: None,
        }
    }

    /// Create a new cache entry with an etag.
    pub fn with_etag(data: T, etag: String) -> Self {
        Self {
            data,
            cached_at: Utc::now(),
            etag: Some(etag),
        }
    }

    /// Check if this entry is still valid based on TTL.
    ///
    /// # Arguments
    ///
    /// * `ttl` - Time-to-live duration
    ///
    /// # Returns
    ///
    /// `true` if the entry is within its TTL, `false` if expired.
    pub fn is_valid(&self, ttl: Duration) -> bool {
        let now = Utc::now();
        now.signed_duration_since(self.cached_at) < ttl
    }
}

/// Returns the cache directory.
///
/// - Linux: `~/.cache/aptu`
/// - macOS: `~/Library/Caches/aptu`
/// - Windows: `C:\Users\<User>\AppData\Local\aptu`
///
/// Returns `None` if the cache directory cannot be determined.
#[must_use]
pub fn cache_dir() -> Option<PathBuf> {
    dirs::cache_dir().map(|dir| dir.join("aptu"))
}

/// Trait for TTL-based filesystem caching.
///
/// Provides a unified interface for caching serializable data with time-to-live validation.
pub trait FileCache<V> {
    /// Get a cached value if it exists and is valid.
    ///
    /// # Arguments
    ///
    /// * `key` - Cache key (filename without extension)
    ///
    /// # Returns
    ///
    /// The cached value if it exists and is within TTL, `None` otherwise.
    fn get(&self, key: &str) -> Result<Option<V>>;

    /// Get a cached value regardless of TTL (stale fallback).
    ///
    /// # Arguments
    ///
    /// * `key` - Cache key (filename without extension)
    ///
    /// # Returns
    ///
    /// The cached value if it exists, `None` otherwise.
    fn get_stale(&self, key: &str) -> Result<Option<V>>;

    /// Set a cached value.
    ///
    /// # Arguments
    ///
    /// * `key` - Cache key (filename without extension)
    /// * `value` - Value to cache
    fn set(&self, key: &str, value: &V) -> Result<()>;

    /// Remove a cached value.
    ///
    /// # Arguments
    ///
    /// * `key` - Cache key (filename without extension)
    fn remove(&self, key: &str) -> Result<()>;
}

/// File-based cache implementation with TTL support.
///
/// Stores serialized data in JSON files with embedded metadata.
/// When cache directory is unavailable (None), all operations become no-ops.
pub struct FileCacheImpl<V> {
    cache_dir: Option<PathBuf>,
    ttl: Duration,
    subdirectory: String,
    _phantom: std::marker::PhantomData<V>,
}

impl<V> FileCacheImpl<V>
where
    V: Serialize + for<'de> Deserialize<'de>,
{
    /// Create a new file cache with default cache directory.
    ///
    /// # Arguments
    ///
    /// * `subdirectory` - Subdirectory within cache directory
    /// * `ttl` - Time-to-live for cache entries
    ///
    /// If the cache directory cannot be determined, caching is disabled
    /// and a warning is emitted.
    #[must_use]
    pub fn new(subdirectory: impl Into<String>, ttl: Duration) -> Self {
        let cache_dir = cache_dir();
        if cache_dir.is_none() {
            CACHE_UNAVAILABLE_WARNING.call_once(|| {
                warn!("Cache directory unavailable, caching disabled");
            });
        }
        Self::with_dir(cache_dir, subdirectory, ttl)
    }

    /// Create a new file cache with custom cache directory.
    ///
    /// # Arguments
    ///
    /// * `cache_dir` - Base cache directory (None to disable caching)
    /// * `subdirectory` - Subdirectory within cache directory
    /// * `ttl` - Time-to-live for cache entries
    #[must_use]
    pub fn with_dir(
        cache_dir: Option<PathBuf>,
        subdirectory: impl Into<String>,
        ttl: Duration,
    ) -> Self {
        Self {
            cache_dir,
            ttl,
            subdirectory: subdirectory.into(),
            _phantom: std::marker::PhantomData,
        }
    }

    /// Check if caching is enabled.
    fn is_enabled(&self) -> bool {
        self.cache_dir.is_some()
    }

    /// Get the full path for a cache key.
    ///
    /// # Panics
    ///
    /// Panics if the key contains path separators or parent directory references,
    /// which could lead to path traversal vulnerabilities.
    fn cache_path(&self, key: &str) -> Option<PathBuf> {
        // Validate key to prevent path traversal
        assert!(
            !key.contains('/') && !key.contains('\\') && !key.contains(".."),
            "cache key must not contain path separators or '..': {key}"
        );

        let filename = if std::path::Path::new(key)
            .extension()
            .is_some_and(|ext| ext.eq_ignore_ascii_case("json"))
        {
            key.to_string()
        } else {
            format!("{key}.json")
        };
        self.cache_dir
            .as_ref()
            .map(|dir| dir.join(&self.subdirectory).join(filename))
    }
}

impl<V> FileCache<V> for FileCacheImpl<V>
where
    V: Serialize + for<'de> Deserialize<'de>,
{
    fn get(&self, key: &str) -> Result<Option<V>> {
        if !self.is_enabled() {
            return Ok(None);
        }

        let Some(path) = self.cache_path(key) else {
            return Ok(None);
        };

        if !path.exists() {
            return Ok(None);
        }

        let contents = fs::read_to_string(&path)
            .with_context(|| format!("Failed to read cache file: {}", path.display()))?;

        let entry: CacheEntry<V> = serde_json::from_str(&contents)
            .with_context(|| format!("Failed to parse cache file: {}", path.display()))?;

        if entry.is_valid(self.ttl) {
            Ok(Some(entry.data))
        } else {
            Ok(None)
        }
    }

    fn get_stale(&self, key: &str) -> Result<Option<V>> {
        if !self.is_enabled() {
            return Ok(None);
        }

        let Some(path) = self.cache_path(key) else {
            return Ok(None);
        };

        if !path.exists() {
            return Ok(None);
        }

        let contents = fs::read_to_string(&path)
            .with_context(|| format!("Failed to read cache file: {}", path.display()))?;

        let entry: CacheEntry<V> = serde_json::from_str(&contents)
            .with_context(|| format!("Failed to parse cache file: {}", path.display()))?;

        Ok(Some(entry.data))
    }

    fn set(&self, key: &str, value: &V) -> Result<()> {
        if !self.is_enabled() {
            return Ok(());
        }

        let Some(path) = self.cache_path(key) else {
            return Ok(());
        };

        // Create parent directories if needed
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).with_context(|| {
                format!("Failed to create cache directory: {}", parent.display())
            })?;
        }

        let entry = CacheEntry::new(value);
        let contents =
            serde_json::to_string_pretty(&entry).context("Failed to serialize cache entry")?;

        // Atomic write: write to temp file, then rename
        let temp_path = path.with_extension("tmp");
        fs::write(&temp_path, contents)
            .with_context(|| format!("Failed to write cache temp file: {}", temp_path.display()))?;

        fs::rename(&temp_path, &path)
            .with_context(|| format!("Failed to rename cache file: {}", path.display()))?;

        Ok(())
    }

    fn remove(&self, key: &str) -> Result<()> {
        if !self.is_enabled() {
            return Ok(());
        }

        let Some(path) = self.cache_path(key) else {
            return Ok(());
        };

        if path.exists() {
            fs::remove_file(&path)
                .with_context(|| format!("Failed to remove cache file: {}", path.display()))?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
    struct TestData {
        value: String,
        count: u32,
    }

    #[test]
    fn test_cache_entry_new() {
        let data = TestData {
            value: "test".to_string(),
            count: 42,
        };
        let entry = CacheEntry::new(data.clone());

        assert_eq!(entry.data, data);
        assert!(entry.etag.is_none());
    }

    #[test]
    fn test_cache_entry_with_etag() {
        let data = TestData {
            value: "test".to_string(),
            count: 42,
        };
        let etag = "abc123".to_string();
        let entry = CacheEntry::with_etag(data.clone(), etag.clone());

        assert_eq!(entry.data, data);
        assert_eq!(entry.etag, Some(etag));
    }

    #[test]
    fn test_cache_entry_is_valid_within_ttl() {
        let data = TestData {
            value: "test".to_string(),
            count: 42,
        };
        let entry = CacheEntry::new(data);
        let ttl = Duration::hours(1);

        assert!(entry.is_valid(ttl));
    }

    #[test]
    fn test_cache_entry_is_valid_expired() {
        let data = TestData {
            value: "test".to_string(),
            count: 42,
        };
        let mut entry = CacheEntry::new(data);
        // Manually set cached_at to 2 hours ago
        entry.cached_at = Utc::now() - Duration::hours(2);
        let ttl = Duration::hours(1);

        assert!(!entry.is_valid(ttl));
    }

    #[test]
    fn test_cache_dir_path() {
        let dir = cache_dir();
        assert!(dir.is_some());
        assert!(dir.unwrap().ends_with("aptu"));
    }

    #[test]
    fn test_cache_serialization_with_etag() {
        let data = TestData {
            value: "test".to_string(),
            count: 42,
        };
        let etag = "xyz789".to_string();
        let entry = CacheEntry::with_etag(data.clone(), etag.clone());

        let json = serde_json::to_string(&entry).expect("serialize");
        let parsed: CacheEntry<TestData> = serde_json::from_str(&json).expect("deserialize");

        assert_eq!(parsed.data, data);
        assert_eq!(parsed.etag, Some(etag));
    }

    #[test]
    fn test_file_cache_get_set() {
        let cache: FileCacheImpl<TestData> = FileCacheImpl::new("test_cache", Duration::hours(1));
        let data = TestData {
            value: "test".to_string(),
            count: 42,
        };

        // Set value
        cache.set("test_key", &data).expect("set cache");

        // Get value
        let result = cache.get("test_key").expect("get cache");
        assert!(result.is_some());
        assert_eq!(result.unwrap(), data);

        // Cleanup
        cache.remove("test_key").ok();
    }

    #[test]
    fn test_file_cache_get_miss() {
        let cache: FileCacheImpl<TestData> = FileCacheImpl::new("test_cache", Duration::hours(1));

        let result = cache.get("nonexistent").expect("get cache");
        assert!(result.is_none());
    }

    #[test]
    fn test_file_cache_get_stale() {
        let cache: FileCacheImpl<TestData> = FileCacheImpl::new("test_cache", Duration::seconds(0));
        let data = TestData {
            value: "stale".to_string(),
            count: 99,
        };

        // Set value
        cache.set("stale_key", &data).expect("set cache");

        // Wait for TTL to expire
        std::thread::sleep(std::time::Duration::from_millis(10));

        // get() should return None (expired)
        let result = cache.get("stale_key").expect("get cache");
        assert!(result.is_none());

        // get_stale() should return the value
        let stale_result = cache.get_stale("stale_key").expect("get stale cache");
        assert!(stale_result.is_some());
        assert_eq!(stale_result.unwrap(), data);

        // Cleanup
        cache.remove("stale_key").ok();
    }

    #[test]
    fn test_file_cache_remove() {
        let cache: FileCacheImpl<TestData> = FileCacheImpl::new("test_cache", Duration::hours(1));
        let data = TestData {
            value: "remove_me".to_string(),
            count: 1,
        };

        // Set value
        cache.set("remove_key", &data).expect("set cache");

        // Verify it exists
        assert!(cache.get("remove_key").expect("get cache").is_some());

        // Remove it
        cache.remove("remove_key").expect("remove cache");

        // Verify it's gone
        assert!(cache.get("remove_key").expect("get cache").is_none());
    }

    #[test]
    #[should_panic(expected = "cache key must not contain path separators")]
    fn test_cache_key_rejects_forward_slash() {
        let cache: FileCacheImpl<TestData> = FileCacheImpl::new("test_cache", Duration::hours(1));
        let _ = cache.get("../etc/passwd");
    }

    #[test]
    #[should_panic(expected = "cache key must not contain path separators")]
    fn test_cache_key_rejects_backslash() {
        let cache: FileCacheImpl<TestData> = FileCacheImpl::new("test_cache", Duration::hours(1));
        let _ = cache.get("..\\windows\\system32");
    }

    #[test]
    #[should_panic(expected = "cache key must not contain path separators")]
    fn test_cache_key_rejects_parent_dir() {
        let cache: FileCacheImpl<TestData> = FileCacheImpl::new("test_cache", Duration::hours(1));
        let _ = cache.get("foo..bar");
    }

    #[test]
    fn test_disabled_cache_get_returns_none() {
        let cache: FileCacheImpl<TestData> =
            FileCacheImpl::with_dir(None, "test_cache", Duration::hours(1));
        let result = cache.get("any_key").expect("get should succeed");
        assert!(result.is_none());
    }

    #[test]
    fn test_disabled_cache_set_succeeds_silently() {
        let cache: FileCacheImpl<TestData> =
            FileCacheImpl::with_dir(None, "test_cache", Duration::hours(1));
        let data = TestData {
            value: "test".to_string(),
            count: 42,
        };
        cache.set("any_key", &data).expect("set should succeed");
    }

    #[test]
    fn test_disabled_cache_remove_succeeds_silently() {
        let cache: FileCacheImpl<TestData> =
            FileCacheImpl::with_dir(None, "test_cache", Duration::hours(1));
        cache.remove("any_key").expect("remove should succeed");
    }

    #[test]
    fn test_disabled_cache_get_stale_returns_none() {
        let cache: FileCacheImpl<TestData> =
            FileCacheImpl::with_dir(None, "test_cache", Duration::hours(1));
        let result = cache
            .get_stale("any_key")
            .expect("get_stale should succeed");
        assert!(result.is_none());
    }
}