Skip to main content

strata_web_api/
cache.rs

1//! W3C Cache API & In-Memory HTTP Resource Store with Cache-Control and ETag validation.
2
3use crate::fetch::{FetchError, Response};
4use std::collections::HashMap;
5use std::sync::{Arc, RwLock};
6use std::time::{Duration, Instant};
7
8/// Cached HTTP response entry with expiration and revalidation metadata.
9#[derive(Debug, Clone)]
10pub struct CacheEntry {
11    pub response: Response,
12    pub stored_at: Instant,
13    pub max_age: Option<Duration>,
14    pub etag: Option<String>,
15    pub no_cache: bool,
16}
17
18impl CacheEntry {
19    /// Returns whether this cached entry has expired according to its max-age directive.
20    pub fn is_fresh(&self) -> bool {
21        if self.no_cache {
22            return false;
23        }
24        match self.max_age {
25            Some(max_age) => self.stored_at.elapsed() < max_age,
26            None => true, // Indefinite if no expiration specified
27        }
28    }
29}
30
31/// A named W3C Cache storing request/response pairs.
32#[derive(Debug, Clone, Default)]
33pub struct Cache {
34    entries: Arc<RwLock<HashMap<String, CacheEntry>>>,
35}
36
37impl Cache {
38    pub fn new() -> Self {
39        Self {
40            entries: Arc::new(RwLock::new(HashMap::new())),
41        }
42    }
43
44    /// Retrieves a fresh cached Response for the specified URL, if valid.
45    pub fn match_url(&self, url: &str) -> Option<Response> {
46        let entries = self.entries.read().ok()?;
47        let entry = entries.get(url)?;
48        if entry.is_fresh() {
49            Some(entry.response.clone())
50        } else {
51            None
52        }
53    }
54
55    /// Stores a response in the cache, respecting Cache-Control directives (`no-store`, `no-cache`, `max-age`).
56    pub fn put(&self, url: &str, response: Response) -> Result<bool, FetchError> {
57        // Inspect Cache-Control header
58        let cache_control = response.headers.get("cache-control").unwrap_or("");
59        let lower_cc = cache_control.to_ascii_lowercase();
60
61        // If no-store is present, must not store in cache per RFC 7234
62        if lower_cc.contains("no-store") {
63            return Ok(false);
64        }
65
66        let no_cache = lower_cc.contains("no-cache");
67        let mut max_age = None;
68
69        for part in lower_cc.split(',') {
70            let trimmed = part.trim();
71            if let Some(sec_str) = trimmed.strip_prefix("max-age=") {
72                if let Ok(secs) = sec_str.trim().parse::<u64>() {
73                    max_age = Some(Duration::from_secs(secs));
74                }
75            }
76        }
77
78        let etag = response.headers.get("etag").map(|s| s.to_string());
79
80        let entry = CacheEntry {
81            response,
82            stored_at: Instant::now(),
83            max_age,
84            etag,
85            no_cache,
86        };
87
88        if let Ok(mut lock) = self.entries.write() {
89            lock.insert(url.to_string(), entry);
90            Ok(true)
91        } else {
92            Err(FetchError::IoError("Cache lock poisoned".into()))
93        }
94    }
95
96    /// Deletes a cached entry by URL. Returns true if an entry was removed.
97    pub fn delete(&self, url: &str) -> bool {
98        if let Ok(mut lock) = self.entries.write() {
99            lock.remove(url).is_some()
100        } else {
101            false
102        }
103    }
104
105    /// Returns a list of all cached URLs in this cache.
106    pub fn keys(&self) -> Vec<String> {
107        self.entries
108            .read()
109            .map(|l| l.keys().cloned().collect())
110            .unwrap_or_default()
111    }
112
113    /// Clears all entries from this cache.
114    pub fn clear(&self) {
115        if let Ok(mut lock) = self.entries.write() {
116            lock.clear();
117        }
118    }
119}
120
121/// Global W3C CacheStorage managing multiple named caches.
122#[derive(Debug, Clone, Default)]
123pub struct CacheStorage {
124    caches: Arc<RwLock<HashMap<String, Cache>>>,
125}
126
127impl CacheStorage {
128    pub fn new() -> Self {
129        Self {
130            caches: Arc::new(RwLock::new(HashMap::new())),
131        }
132    }
133
134    /// Opens or retrieves an existing named Cache.
135    pub fn open(&self, name: &str) -> Cache {
136        let mut lock = self.caches.write().expect("CacheStorage write lock");
137        lock.entry(name.to_string()).or_default().clone()
138    }
139
140    /// Returns whether a cache with the given name exists.
141    pub fn has(&self, name: &str) -> bool {
142        self.caches
143            .read()
144            .map(|l| l.contains_key(name))
145            .unwrap_or(false)
146    }
147
148    /// Deletes a named cache. Returns true if it was present.
149    pub fn delete(&self, name: &str) -> bool {
150        self.caches
151            .write()
152            .map(|mut l| l.remove(name).is_some())
153            .unwrap_or(false)
154    }
155
156    /// Returns the names of all open caches.
157    pub fn keys(&self) -> Vec<String> {
158        self.caches
159            .read()
160            .map(|l| l.keys().cloned().collect())
161            .unwrap_or_default()
162    }
163}