Skip to content

Commit ec5368d

Browse files
authored
fix(cache): bound retained entries and expose cache stats (#1371)
Use LRU eviction for response and MITM leaf caches, cap retained leaf configurations, and expose capacity/eviction statistics.
1 parent 4e9f223 commit ec5368d

4 files changed

Lines changed: 145 additions & 11 deletions

File tree

‎docs/guide.fa.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -345,15 +345,15 @@ sni_hosts = ["www.google.com", "drive.google.com", "docs.google.com"]
345345
|---|---|
346346
| HTTP proxy محلی | CONNECT برای HTTPS، forwarding ساده برای HTTP |
347347
| SOCKS5 محلی | dispatch هوشمند TLS / HTTP / TCP خام (تلگرام، xray، …) |
348-
| MITM | تولید گواهی per-domain روی پرواز با `rcgen` |
348+
| MITM | تولید گواهی per-domain روی پرواز با `rcgen`؛ configهای leaf تولیدشده داخل یک کش LRU محدود نگه‌داری می‌شوند |
349349
| نصب CA | تولید + نصب خودکار روی مک / لینوکس / ویندوز |
350350
| پشتیبانی فایرفاکس | نصب گواهی NSS با `certutil` (best-effort) |
351351
| رلهٔ JSON | پروتکل سازگار با `Code.gs` |
352352
| Connection pool | TTL ۴۵ ثانیه، حداکثر ۲۰ idle |
353353
| رمزگشایی gzip | اتوماتیک |
354354
| چند اسکریپت | چرخش round-robin |
355355
| Blacklist خودکار | روی خطای 429 / quota، با cooldown ۱۰ دقیقه |
356-
| کش پاسخ | ۵۰ مگابایت، FIFO + TTL، آگاه از `Cache-Control: max-age`، heuristic برای static asset |
356+
| کش پاسخ | ۵۰ مگابایت، LRU + TTL، آگاه از `Cache-Control: max-age`، heuristic برای static asset |
357357
| Coalescing | GETهای یکسان همزمان یک fetch upstream را به اشتراک می‌گذارند |
358358
| تونل بازنویسی SNI | مستقیم به لبهٔ گوگل (بدون رله) برای `google.com`، `youtube.com`، `youtu.be`، `youtube-nocookie.com`، `fonts.googleapis.com` — دامنه‌های اضافی از فیلد `hosts` |
359359
| هندل ریدایرکت | اتوماتیک: `/exec` → `googleusercontent.com` |

‎docs/guide.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -341,15 +341,15 @@ This port focuses on the **`apps_script` mode** — the only one that reliably w
341341

342342
- [x] Local HTTP proxy (CONNECT for HTTPS, plain forwarding for HTTP)
343343
- [x] Local SOCKS5 with smart TLS / HTTP / raw-TCP dispatch (Telegram, xray, etc.)
344-
- [x] MITM with on-the-fly per-domain certs via `rcgen`
344+
- [x] MITM with on-the-fly per-domain certs via `rcgen`; generated leaf configs are held in a bounded LRU cache
345345
- [x] CA generation + auto-install on macOS / Linux / Windows
346346
- [x] Firefox NSS cert install (best-effort via `certutil`)
347347
- [x] Apps Script JSON relay protocol-compatible with `Code.gs`
348348
- [x] Connection pooling (45 s TTL, max 20 idle)
349349
- [x] Gzip response decoding
350350
- [x] Multi-script round-robin
351351
- [x] Auto-blacklist failing scripts on 429 / quota errors (10 min cooldown)
352-
- [x] Response cache (50 MB, FIFO + TTL, `Cache-Control: max-age` aware, heuristics for static assets)
352+
- [x] Response cache (50 MB, LRU + TTL, `Cache-Control: max-age` aware, heuristics for static assets)
353353
- [x] Request coalescing: concurrent identical GETs share one upstream fetch
354354
- [x] SNI-rewrite tunnels for `google.com`, `youtube.com`, `youtu.be`, `youtube-nocookie.com`, `fonts.googleapis.com`, configurable via `hosts` map
355355
- [x] Automatic redirect handling on the relay (`/exec` → `googleusercontent.com`)

‎src/cache.rs‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,11 @@ impl ResponseCache {
5353
let mut inner = self.inner.lock().unwrap();
5454
if let Some(entry) = inner.entries.get(key) {
5555
if entry.expires > now {
56+
let bytes = entry.bytes.clone();
57+
inner.order.retain(|k| k != key);
58+
inner.order.push_back(key.to_string());
5659
self.hits.fetch_add(1, Ordering::Relaxed);
57-
return Some(entry.bytes.clone());
60+
return Some(bytes);
5861
}
5962
let size = entry.bytes.len();
6063
inner.entries.remove(key);
@@ -215,15 +218,17 @@ mod tests {
215218
}
216219

217220
#[test]
218-
fn fifo_eviction_when_full() {
221+
fn least_recently_used_entry_is_evicted_when_full() {
219222
let c = ResponseCache::new(1000);
220223
c.put("a".into(), vec![0u8; 200], Duration::from_secs(60));
221224
c.put("b".into(), vec![0u8; 200], Duration::from_secs(60));
222225
c.put("c".into(), vec![0u8; 200], Duration::from_secs(60));
223226
c.put("d".into(), vec![0u8; 200], Duration::from_secs(60));
224227
c.put("e".into(), vec![0u8; 200], Duration::from_secs(60));
228+
assert!(c.get("a").is_some());
225229
c.put("f".into(), vec![0u8; 200], Duration::from_secs(60));
226-
assert!(c.get("a").is_none());
230+
assert!(c.get("a").is_some());
231+
assert!(c.get("b").is_none());
227232
assert!(c.get("f").is_some());
228233
}
229234

‎src/mitm.rs‎

Lines changed: 133 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use std::collections::HashMap;
1+
use std::collections::{HashMap, VecDeque};
22
use std::path::{Path, PathBuf};
33
use std::sync::Arc;
44

@@ -27,6 +27,14 @@ pub const CERT_NAME: &str = "MasterHttpRelayVPN";
2727
pub const CA_DIR: &str = "ca";
2828
pub const CA_KEY_FILE: &str = "ca/ca.key";
2929
pub const CA_CERT_FILE: &str = "ca/ca.crt";
30+
const DEFAULT_LEAF_CACHE_CAPACITY: usize = 512;
31+
32+
#[derive(Clone, Debug, Eq, PartialEq)]
33+
pub struct MitmCacheStats {
34+
pub leaf_entries: usize,
35+
pub leaf_capacity: usize,
36+
pub leaf_evictions: u64,
37+
}
3038

3139
pub struct MitmCertManager {
3240
/// The CA certificate bytes as they appear on disk.
@@ -41,6 +49,9 @@ pub struct MitmCertManager {
4149
/// re-made), but that's fine — we never send this cert to browsers.
4250
ca_cert: Certificate,
4351
cache: HashMap<String, Arc<ServerConfig>>,
52+
cache_order: VecDeque<String>,
53+
cache_capacity: usize,
54+
cache_evictions: u64,
4455
}
4556

4657
impl MitmCertManager {
@@ -88,6 +99,9 @@ impl MitmCertManager {
8899
ca_key_pair: key_pair,
89100
ca_cert,
90101
cache: HashMap::new(),
102+
cache_order: VecDeque::new(),
103+
cache_capacity: DEFAULT_LEAF_CACHE_CAPACITY,
104+
cache_evictions: 0,
91105
})
92106
}
93107

@@ -127,6 +141,9 @@ impl MitmCertManager {
127141
ca_key_pair: key_pair,
128142
ca_cert,
129143
cache: HashMap::new(),
144+
cache_order: VecDeque::new(),
145+
cache_capacity: DEFAULT_LEAF_CACHE_CAPACITY,
146+
cache_evictions: 0,
130147
})
131148
}
132149

@@ -136,8 +153,9 @@ impl MitmCertManager {
136153

137154
/// Return a rustls ServerConfig for the given domain, ALPN ["http/1.1"].
138155
pub fn get_server_config(&mut self, domain: &str) -> Result<Arc<ServerConfig>, MitmError> {
139-
if let Some(cfg) = self.cache.get(domain) {
140-
return Ok(cfg.clone());
156+
if let Some(cfg) = self.cache.get(domain).cloned() {
157+
self.touch_cached_domain(domain);
158+
return Ok(cfg);
141159
}
142160
let (leaf_der, leaf_key_der) = self.issue_leaf(domain)?;
143161

@@ -149,10 +167,45 @@ impl MitmCertManager {
149167
.with_single_cert(chain, key)?;
150168
cfg.alpn_protocols = vec![b"http/1.1".to_vec()];
151169
let arc = Arc::new(cfg);
152-
self.cache.insert(domain.to_string(), arc.clone());
170+
self.insert_cached_config(domain.to_string(), arc.clone());
153171
Ok(arc)
154172
}
155173

174+
pub fn cache_stats(&self) -> MitmCacheStats {
175+
MitmCacheStats {
176+
leaf_entries: self.cache.len(),
177+
leaf_capacity: self.cache_capacity,
178+
leaf_evictions: self.cache_evictions,
179+
}
180+
}
181+
182+
fn touch_cached_domain(&mut self, domain: &str) {
183+
self.cache_order.retain(|cached| cached != domain);
184+
self.cache_order.push_back(domain.to_string());
185+
}
186+
187+
fn insert_cached_config(&mut self, domain: String, cfg: Arc<ServerConfig>) {
188+
if self.cache_capacity == 0 {
189+
return;
190+
}
191+
192+
if self.cache.remove(&domain).is_some() {
193+
self.cache_order.retain(|cached| cached != &domain);
194+
}
195+
196+
while self.cache.len() >= self.cache_capacity {
197+
let Some(evicted_domain) = self.cache_order.pop_front() else {
198+
break;
199+
};
200+
if self.cache.remove(&evicted_domain).is_some() {
201+
self.cache_evictions = self.cache_evictions.saturating_add(1);
202+
}
203+
}
204+
205+
self.cache.insert(domain.clone(), cfg);
206+
self.cache_order.push_back(domain);
207+
}
208+
156209
fn issue_leaf(&self, domain: &str) -> Result<(CertificateDer<'static>, Vec<u8>), MitmError> {
157210
let mut params = CertificateParams::default();
158211
let mut dn = DistinguishedName::new();
@@ -268,6 +321,82 @@ mod tests {
268321
let _ = std::fs::remove_dir_all(&tmp);
269322
}
270323

324+
#[test]
325+
fn leaf_cache_is_capacity_bounded() {
326+
init_crypto();
327+
let tmp = tempdir();
328+
let mut m = MitmCertManager::new_in(&tmp).unwrap();
329+
m.cache_capacity = 2;
330+
331+
let _ = m.get_server_config("a.example.com").unwrap();
332+
let _ = m.get_server_config("b.example.com").unwrap();
333+
let _ = m.get_server_config("c.example.com").unwrap();
334+
335+
assert_eq!(m.cache.len(), 2);
336+
assert!(!m.cache.contains_key("a.example.com"));
337+
assert!(m.cache.contains_key("b.example.com"));
338+
assert!(m.cache.contains_key("c.example.com"));
339+
assert_eq!(m.cache_order.len(), 2);
340+
assert_eq!(
341+
m.cache_stats(),
342+
MitmCacheStats {
343+
leaf_entries: 2,
344+
leaf_capacity: 2,
345+
leaf_evictions: 1,
346+
}
347+
);
348+
let _ = std::fs::remove_dir_all(&tmp);
349+
}
350+
351+
#[test]
352+
fn leaf_cache_hit_refreshes_eviction_order() {
353+
init_crypto();
354+
let tmp = tempdir();
355+
let mut m = MitmCertManager::new_in(&tmp).unwrap();
356+
m.cache_capacity = 2;
357+
358+
let _ = m.get_server_config("a.example.com").unwrap();
359+
let _ = m.get_server_config("b.example.com").unwrap();
360+
let _ = m.get_server_config("a.example.com").unwrap();
361+
let _ = m.get_server_config("c.example.com").unwrap();
362+
363+
assert_eq!(m.cache.len(), 2);
364+
assert!(m.cache.contains_key("a.example.com"));
365+
assert!(!m.cache.contains_key("b.example.com"));
366+
assert!(m.cache.contains_key("c.example.com"));
367+
assert_eq!(m.cache_stats().leaf_evictions, 1);
368+
let _ = std::fs::remove_dir_all(&tmp);
369+
}
370+
371+
#[test]
372+
fn cache_stats_reports_leaf_cache_capacity_and_evictions() {
373+
init_crypto();
374+
let tmp = tempdir();
375+
let mut m = MitmCertManager::new_in(&tmp).unwrap();
376+
m.cache_capacity = 1;
377+
378+
let _ = m.get_server_config("a.example.com").unwrap();
379+
assert_eq!(
380+
m.cache_stats(),
381+
MitmCacheStats {
382+
leaf_entries: 1,
383+
leaf_capacity: 1,
384+
leaf_evictions: 0,
385+
}
386+
);
387+
388+
let _ = m.get_server_config("b.example.com").unwrap();
389+
assert_eq!(
390+
m.cache_stats(),
391+
MitmCacheStats {
392+
leaf_entries: 1,
393+
leaf_capacity: 1,
394+
leaf_evictions: 1,
395+
}
396+
);
397+
let _ = std::fs::remove_dir_all(&tmp);
398+
}
399+
271400
fn tempdir() -> PathBuf {
272401
let mut p = std::env::temp_dir();
273402
let n: u64 = rand::random();

0 commit comments

Comments
 (0)