|
| 1 | +use std::collections::{HashMap, VecDeque}; |
| 2 | +use std::sync::atomic::{AtomicU64, Ordering}; |
| 3 | +use std::sync::Mutex; |
| 4 | +use std::time::{Duration, Instant}; |
| 5 | + |
| 6 | +const DEFAULT_MAX_BYTES: usize = 50 * 1024 * 1024; |
| 7 | +const MAX_ENTRY_FRACTION: usize = 4; |
| 8 | + |
| 9 | +pub struct ResponseCache { |
| 10 | + inner: Mutex<Inner>, |
| 11 | + max_bytes: usize, |
| 12 | + hits: AtomicU64, |
| 13 | + misses: AtomicU64, |
| 14 | +} |
| 15 | + |
| 16 | +struct Inner { |
| 17 | + entries: HashMap<String, CachedResponse>, |
| 18 | + order: VecDeque<String>, |
| 19 | + size: usize, |
| 20 | +} |
| 21 | + |
| 22 | +struct CachedResponse { |
| 23 | + bytes: Vec<u8>, |
| 24 | + expires: Instant, |
| 25 | +} |
| 26 | + |
| 27 | +impl ResponseCache { |
| 28 | + pub fn new(max_bytes: usize) -> Self { |
| 29 | + Self { |
| 30 | + inner: Mutex::new(Inner { |
| 31 | + entries: HashMap::new(), |
| 32 | + order: VecDeque::new(), |
| 33 | + size: 0, |
| 34 | + }), |
| 35 | + max_bytes, |
| 36 | + hits: AtomicU64::new(0), |
| 37 | + misses: AtomicU64::new(0), |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + pub fn with_default() -> Self { |
| 42 | + Self::new(DEFAULT_MAX_BYTES) |
| 43 | + } |
| 44 | + |
| 45 | + pub fn get(&self, key: &str) -> Option<Vec<u8>> { |
| 46 | + let now = Instant::now(); |
| 47 | + let mut inner = self.inner.lock().unwrap(); |
| 48 | + if let Some(entry) = inner.entries.get(key) { |
| 49 | + if entry.expires > now { |
| 50 | + self.hits.fetch_add(1, Ordering::Relaxed); |
| 51 | + return Some(entry.bytes.clone()); |
| 52 | + } |
| 53 | + let size = entry.bytes.len(); |
| 54 | + inner.entries.remove(key); |
| 55 | + inner.order.retain(|k| k != key); |
| 56 | + inner.size = inner.size.saturating_sub(size); |
| 57 | + } |
| 58 | + self.misses.fetch_add(1, Ordering::Relaxed); |
| 59 | + None |
| 60 | + } |
| 61 | + |
| 62 | + pub fn put(&self, key: String, bytes: Vec<u8>, ttl: Duration) { |
| 63 | + let size = bytes.len(); |
| 64 | + if size == 0 || size > self.max_bytes / MAX_ENTRY_FRACTION { |
| 65 | + return; |
| 66 | + } |
| 67 | + let expires = Instant::now() + ttl; |
| 68 | + let mut inner = self.inner.lock().unwrap(); |
| 69 | + |
| 70 | + if let Some(old) = inner.entries.remove(&key) { |
| 71 | + inner.size = inner.size.saturating_sub(old.bytes.len()); |
| 72 | + inner.order.retain(|k| k != &key); |
| 73 | + } |
| 74 | + |
| 75 | + while inner.size + size > self.max_bytes { |
| 76 | + let Some(oldest_key) = inner.order.pop_front() else { |
| 77 | + break; |
| 78 | + }; |
| 79 | + if let Some(removed) = inner.entries.remove(&oldest_key) { |
| 80 | + inner.size = inner.size.saturating_sub(removed.bytes.len()); |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + inner.entries.insert(key.clone(), CachedResponse { bytes, expires }); |
| 85 | + inner.order.push_back(key); |
| 86 | + inner.size += size; |
| 87 | + } |
| 88 | + |
| 89 | + pub fn hits(&self) -> u64 { |
| 90 | + self.hits.load(Ordering::Relaxed) |
| 91 | + } |
| 92 | + |
| 93 | + pub fn misses(&self) -> u64 { |
| 94 | + self.misses.load(Ordering::Relaxed) |
| 95 | + } |
| 96 | + |
| 97 | + pub fn size(&self) -> usize { |
| 98 | + self.inner.lock().unwrap().size |
| 99 | + } |
| 100 | +} |
| 101 | + |
| 102 | +pub fn parse_ttl(raw_response: &[u8], url: &str) -> Option<Duration> { |
| 103 | + let sep = b"\r\n\r\n"; |
| 104 | + let hdr_end = raw_response |
| 105 | + .windows(sep.len()) |
| 106 | + .position(|w| w == sep)?; |
| 107 | + let hdr = std::str::from_utf8(&raw_response[..hdr_end]).ok()?; |
| 108 | + let hdr_lower = hdr.to_ascii_lowercase(); |
| 109 | + |
| 110 | + let first_line = hdr_lower.lines().next()?; |
| 111 | + if !first_line.starts_with("http/1.1 200") && !first_line.starts_with("http/1.0 200") { |
| 112 | + return None; |
| 113 | + } |
| 114 | + if hdr_lower.contains("no-store") || hdr_lower.contains("no-cache") || hdr_lower.contains("private") { |
| 115 | + return None; |
| 116 | + } |
| 117 | + if hdr_lower.contains("set-cookie:") { |
| 118 | + return None; |
| 119 | + } |
| 120 | + |
| 121 | + if let Some(pos) = hdr_lower.find("max-age=") { |
| 122 | + let rest = &hdr_lower[pos + 8..]; |
| 123 | + let end = rest |
| 124 | + .find(|c: char| !c.is_ascii_digit()) |
| 125 | + .unwrap_or(rest.len()); |
| 126 | + if let Ok(secs) = rest[..end].parse::<u64>() { |
| 127 | + if secs == 0 { |
| 128 | + return None; |
| 129 | + } |
| 130 | + return Some(Duration::from_secs(secs.min(86400))); |
| 131 | + } |
| 132 | + } |
| 133 | + |
| 134 | + let path_no_query = url.split('?').next().unwrap_or(url).to_ascii_lowercase(); |
| 135 | + const STATIC_EXTS: &[&str] = &[ |
| 136 | + ".css", ".js", ".mjs", ".woff", ".woff2", ".ttf", ".otf", ".eot", |
| 137 | + ".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".ico", ".avif", |
| 138 | + ".mp3", ".mp4", ".wasm", ".webm", ".ogg", |
| 139 | + ]; |
| 140 | + for ext in STATIC_EXTS { |
| 141 | + if path_no_query.ends_with(ext) { |
| 142 | + return Some(Duration::from_secs(3600)); |
| 143 | + } |
| 144 | + } |
| 145 | + |
| 146 | + let ct_key = "content-type:"; |
| 147 | + if let Some(pos) = hdr_lower.find(ct_key) { |
| 148 | + let rest = &hdr_lower[pos + ct_key.len()..]; |
| 149 | + let line_end = rest.find('\r').unwrap_or(rest.len()); |
| 150 | + let ct = &rest[..line_end]; |
| 151 | + if ct.contains("image/") || ct.contains("font/") { |
| 152 | + return Some(Duration::from_secs(3600)); |
| 153 | + } |
| 154 | + if ct.contains("text/css") || ct.contains("javascript") || ct.contains("application/wasm") { |
| 155 | + return Some(Duration::from_secs(1800)); |
| 156 | + } |
| 157 | + } |
| 158 | + |
| 159 | + None |
| 160 | +} |
| 161 | + |
| 162 | +pub fn is_cacheable_method(method: &str) -> bool { |
| 163 | + matches!( |
| 164 | + method.to_ascii_uppercase().as_str(), |
| 165 | + "GET" | "HEAD" |
| 166 | + ) |
| 167 | +} |
| 168 | + |
| 169 | +pub fn cache_key(method: &str, url: &str) -> String { |
| 170 | + format!("{}:{}", method.to_ascii_uppercase(), url) |
| 171 | +} |
| 172 | + |
| 173 | +#[cfg(test)] |
| 174 | +mod tests { |
| 175 | + use super::*; |
| 176 | + |
| 177 | + fn mk_resp(headers: &str, body: &str) -> Vec<u8> { |
| 178 | + let mut r = Vec::new(); |
| 179 | + r.extend_from_slice(headers.as_bytes()); |
| 180 | + r.extend_from_slice(b"\r\n\r\n"); |
| 181 | + r.extend_from_slice(body.as_bytes()); |
| 182 | + r |
| 183 | + } |
| 184 | + |
| 185 | + #[test] |
| 186 | + fn get_miss_then_put_then_hit() { |
| 187 | + let c = ResponseCache::new(1024); |
| 188 | + assert!(c.get("k").is_none()); |
| 189 | + c.put("k".into(), b"hello".to_vec(), Duration::from_secs(60)); |
| 190 | + assert_eq!(c.get("k").unwrap(), b"hello"); |
| 191 | + assert_eq!(c.hits(), 1); |
| 192 | + assert_eq!(c.misses(), 1); |
| 193 | + } |
| 194 | + |
| 195 | + #[test] |
| 196 | + fn expired_entry_is_removed_on_get() { |
| 197 | + let c = ResponseCache::new(1024); |
| 198 | + c.put("k".into(), b"hi".to_vec(), Duration::from_millis(1)); |
| 199 | + std::thread::sleep(Duration::from_millis(20)); |
| 200 | + assert!(c.get("k").is_none()); |
| 201 | + assert_eq!(c.size(), 0); |
| 202 | + } |
| 203 | + |
| 204 | + #[test] |
| 205 | + fn too_large_entry_rejected() { |
| 206 | + let c = ResponseCache::new(100); |
| 207 | + c.put("k".into(), vec![0u8; 60], Duration::from_secs(60)); |
| 208 | + assert!(c.get("k").is_none()); |
| 209 | + } |
| 210 | + |
| 211 | + #[test] |
| 212 | + fn fifo_eviction_when_full() { |
| 213 | + let c = ResponseCache::new(1000); |
| 214 | + c.put("a".into(), vec![0u8; 200], Duration::from_secs(60)); |
| 215 | + c.put("b".into(), vec![0u8; 200], Duration::from_secs(60)); |
| 216 | + c.put("c".into(), vec![0u8; 200], Duration::from_secs(60)); |
| 217 | + c.put("d".into(), vec![0u8; 200], Duration::from_secs(60)); |
| 218 | + c.put("e".into(), vec![0u8; 200], Duration::from_secs(60)); |
| 219 | + c.put("f".into(), vec![0u8; 200], Duration::from_secs(60)); |
| 220 | + assert!(c.get("a").is_none()); |
| 221 | + assert!(c.get("f").is_some()); |
| 222 | + } |
| 223 | + |
| 224 | + #[test] |
| 225 | + fn max_age_parsed() { |
| 226 | + let raw = mk_resp( |
| 227 | + "HTTP/1.1 200 OK\r\nCache-Control: public, max-age=300\r\nContent-Type: text/html", |
| 228 | + "body", |
| 229 | + ); |
| 230 | + let ttl = parse_ttl(&raw, "http://example.com/page").unwrap(); |
| 231 | + assert_eq!(ttl, Duration::from_secs(300)); |
| 232 | + } |
| 233 | + |
| 234 | + #[test] |
| 235 | + fn no_store_rejects_cache() { |
| 236 | + let raw = mk_resp( |
| 237 | + "HTTP/1.1 200 OK\r\nCache-Control: no-store\r\nContent-Type: text/css", |
| 238 | + "body", |
| 239 | + ); |
| 240 | + assert!(parse_ttl(&raw, "http://x.com/a.css").is_none()); |
| 241 | + } |
| 242 | + |
| 243 | + #[test] |
| 244 | + fn static_extension_heuristic() { |
| 245 | + let raw = mk_resp("HTTP/1.1 200 OK\r\nContent-Type: text/css", "body"); |
| 246 | + let ttl = parse_ttl(&raw, "http://x.com/style.css").unwrap(); |
| 247 | + assert_eq!(ttl, Duration::from_secs(3600)); |
| 248 | + } |
| 249 | + |
| 250 | + #[test] |
| 251 | + fn set_cookie_rejects_cache() { |
| 252 | + let raw = mk_resp( |
| 253 | + "HTTP/1.1 200 OK\r\nSet-Cookie: a=b\r\nCache-Control: max-age=600", |
| 254 | + "body", |
| 255 | + ); |
| 256 | + assert!(parse_ttl(&raw, "http://x.com/page").is_none()); |
| 257 | + } |
| 258 | + |
| 259 | + #[test] |
| 260 | + fn non_200_rejected() { |
| 261 | + let raw = mk_resp("HTTP/1.1 404 Not Found\r\nCache-Control: max-age=600", "body"); |
| 262 | + assert!(parse_ttl(&raw, "http://x.com/page").is_none()); |
| 263 | + } |
| 264 | + |
| 265 | + #[test] |
| 266 | + fn method_check() { |
| 267 | + assert!(is_cacheable_method("GET")); |
| 268 | + assert!(is_cacheable_method("get")); |
| 269 | + assert!(is_cacheable_method("HEAD")); |
| 270 | + assert!(!is_cacheable_method("POST")); |
| 271 | + assert!(!is_cacheable_method("DELETE")); |
| 272 | + } |
| 273 | +} |
0 commit comments