Skip to content

Commit 52d0031

Browse files
committed
add response cache with TTL + Cache-Control parsing
- New cache.rs: FIFO-eviction cache with max_bytes cap - Cacheable: GET/HEAD only, no-store/no-cache/private/Set-Cookie reject - TTL from Cache-Control: max-age=, or heuristics by extension (css/js/fonts/images -> 1h) - Hook in DomainFronter::relay: check cache before network, store after 2xx - 10 new unit tests (23 total)
1 parent 00e0d41 commit 52d0031

3 files changed

Lines changed: 303 additions & 7 deletions

File tree

‎src/cache.rs‎

Lines changed: 273 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,273 @@
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+
}

‎src/domain_fronter.rs‎

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,8 @@
66
//! `/macros/s/{script_id}/exec`. Apps Script performs the actual upstream
77
//! HTTP fetch server-side and returns a JSON envelope.
88
//!
9-
//! TODO(mvp): add HTTP/2 multiplexing (`h2` crate) for lower latency.
10-
//! TODO(mvp): add fetchAll batching — group concurrent relay calls.
11-
//! TODO(mvp): add request coalescing for concurrent identical GETs.
12-
//! TODO(mvp): add response cache and parallel range-based downloads.
9+
//! TODO: add HTTP/2 multiplexing (`h2` crate) for lower latency.
10+
//! TODO: add parallel range-based downloads.
1311
1412
use std::sync::atomic::{AtomicUsize, Ordering};
1513
use std::sync::Arc;
@@ -30,6 +28,7 @@ use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, Server
3028
use rustls::pki_types::{CertificateDer, ServerName, UnixTime};
3129
use rustls::{ClientConfig, DigitallySignedStruct, SignatureScheme};
3230

31+
use crate::cache::{cache_key, is_cacheable_method, parse_ttl, ResponseCache};
3332
use crate::config::Config;
3433

3534
#[derive(Debug, thiserror::Error)]
@@ -69,6 +68,7 @@ pub struct DomainFronter {
6968
script_idx: AtomicUsize,
7069
tls_connector: TlsConnector,
7170
pool: Arc<Mutex<Vec<PoolEntry>>>,
71+
cache: Arc<ResponseCache>,
7272
}
7373

7474
/// Request payload sent to Apps Script (single, non-batch).
@@ -128,9 +128,14 @@ impl DomainFronter {
128128
script_idx: AtomicUsize::new(0),
129129
tls_connector,
130130
pool: Arc::new(Mutex::new(Vec::new())),
131+
cache: Arc::new(ResponseCache::with_default()),
131132
})
132133
}
133134

135+
pub fn cache(&self) -> &ResponseCache {
136+
&self.cache
137+
}
138+
134139
fn next_script_id(&self) -> &str {
135140
let idx = self.script_idx.fetch_add(1, Ordering::Relaxed);
136141
&self.script_ids[idx % self.script_ids.len()]
@@ -182,7 +187,16 @@ impl DomainFronter {
182187
headers: &[(String, String)],
183188
body: &[u8],
184189
) -> Vec<u8> {
185-
match timeout(
190+
let cacheable = is_cacheable_method(method) && body.is_empty();
191+
let key = if cacheable { Some(cache_key(method, url)) } else { None };
192+
if let Some(ref k) = key {
193+
if let Some(hit) = self.cache.get(k) {
194+
tracing::debug!("cache hit: {}", url);
195+
return hit;
196+
}
197+
}
198+
199+
let bytes = match timeout(
186200
Duration::from_secs(REQUEST_TIMEOUT_SECS),
187201
self.do_relay_with_retry(method, url, headers, body),
188202
)
@@ -191,13 +205,21 @@ impl DomainFronter {
191205
Ok(Ok(bytes)) => bytes,
192206
Ok(Err(e)) => {
193207
tracing::error!("Relay failed: {}", e);
194-
error_response(502, &format!("Relay error: {}", e))
208+
return error_response(502, &format!("Relay error: {}", e));
195209
}
196210
Err(_) => {
197211
tracing::error!("Relay timeout");
198-
error_response(504, "Relay timeout")
212+
return error_response(504, "Relay timeout");
213+
}
214+
};
215+
216+
if let Some(k) = key {
217+
if let Some(ttl) = parse_ttl(&bytes, url) {
218+
tracing::debug!("cache store: {} ttl={}s", url, ttl.as_secs());
219+
self.cache.put(k, bytes.clone(), ttl);
199220
}
200221
}
222+
bytes
201223
}
202224

203225
async fn do_relay_with_retry(

‎src/main.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#![allow(dead_code)]
22

3+
mod cache;
34
mod cert_installer;
45
mod config;
56
mod domain_fronter;

0 commit comments

Comments
 (0)