1use crate::fetch::{FetchError, Response};
4use std::collections::HashMap;
5use std::sync::{Arc, RwLock};
6use std::time::{Duration, Instant};
7
8#[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 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, }
28 }
29}
30
31#[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 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 pub fn put(&self, url: &str, response: Response) -> Result<bool, FetchError> {
57 let cache_control = response.headers.get("cache-control").unwrap_or("");
59 let lower_cc = cache_control.to_ascii_lowercase();
60
61 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 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 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 pub fn clear(&self) {
115 if let Ok(mut lock) = self.entries.write() {
116 lock.clear();
117 }
118 }
119}
120
121#[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 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 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 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 pub fn keys(&self) -> Vec<String> {
158 self.caches
159 .read()
160 .map(|l| l.keys().cloned().collect())
161 .unwrap_or_default()
162 }
163}