1use std::fs;
16use std::io::{Read, Write};
17use std::path::{Path, PathBuf};
18use std::time::{Duration, SystemTime, UNIX_EPOCH};
19
20use bytes::Bytes;
21use reqwest::{StatusCode, Url};
22use serde::{Deserialize, Serialize};
23use sha2::{Digest, Sha256};
24use tracing::debug;
25
26use crate::config::HARD_MAX_BODY_BYTES;
27use crate::error::{AppError, AppResult, ErrorKind};
28use crate::http::HttpResponse;
29
30pub const CACHE_PARSER_VERSION: &str = "1";
32pub const DEFAULT_CACHE_TTL_SECS: u64 = 86_400;
34pub const DEFAULT_MAX_CACHE_BYTES: u64 = 256 * 1024 * 1024;
36pub const MAX_CACHE_META_BYTES: u64 = 64 * 1024;
41const CACHE_LAYOUT: &str = "http/v1";
43
44#[derive(Debug, Clone)]
46pub struct DiskCache {
47 root: PathBuf,
48 ttl: Duration,
49 max_bytes: u64,
51}
52
53#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
55pub struct CacheStats {
56 pub root: String,
58 pub layout: String,
60 pub entries: u64,
62 pub total_bytes: u64,
64 pub max_bytes: u64,
66 pub ttl_secs: u64,
68 pub parser_version: String,
70}
71
72#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
74pub struct CacheClearResult {
75 pub root: String,
77 pub removed_entries: u64,
79 pub freed_bytes: u64,
81}
82
83#[derive(Debug, Clone, Serialize, Deserialize)]
84struct CacheMeta {
85 url: String,
86 parser_version: String,
87 accept: String,
88 status: u16,
89 content_type: Option<String>,
90 final_url: String,
91 stored_at_unix: u64,
92 body_sha256: String,
93 input_sha256: String,
95}
96
97#[derive(Debug)]
98struct EntryOnDisk {
99 key: String,
100 stored_at_unix: u64,
101 bytes: u64,
102}
103
104impl DiskCache {
105 pub fn new(root: PathBuf, ttl: Duration, max_bytes: u64) -> Self {
107 Self {
108 root,
109 ttl,
110 max_bytes,
111 }
112 }
113
114 pub fn root(&self) -> &Path {
116 &self.root
117 }
118
119 pub fn ttl(&self) -> Duration {
121 self.ttl
122 }
123
124 pub fn max_bytes(&self) -> u64 {
126 self.max_bytes
127 }
128
129 fn entry_dir(&self) -> PathBuf {
130 self.root.join(CACHE_LAYOUT)
131 }
132
133 fn paths_for_key(&self, key_hex: &str) -> (PathBuf, PathBuf) {
134 let dir = self.entry_dir();
135 (
136 dir.join(format!("{key_hex}.meta.json")),
137 dir.join(format!("{key_hex}.bin")),
138 )
139 }
140
141 pub fn get(&self, url: &Url, accept: &str) -> Option<HttpResponse> {
143 if self.ttl.as_secs() == 0 {
145 return None;
146 }
147 let input_sha = input_checksum(url.as_str(), CACHE_PARSER_VERSION, accept);
148 let key = key_hex(url.as_str(), CACHE_PARSER_VERSION, accept);
149 let (meta_path, body_path) = self.paths_for_key(&key);
150 if !meta_path.is_file() || !body_path.is_file() {
151 return None;
152 }
153 let Some(meta) = read_meta_file(&meta_path) else {
154 debug!(%key, "cache miss: meta unreadable or over cap");
155 return None;
156 };
157 if meta.parser_version != CACHE_PARSER_VERSION {
158 debug!(%key, "cache miss: parser version mismatch");
159 let _ = self.remove_entry(&key);
160 return None;
161 }
162 if meta.url != url.as_str() || meta.accept != accept {
163 debug!(%key, "cache miss: url/accept mismatch");
164 let _ = self.remove_entry(&key);
165 return None;
166 }
167 if meta.input_sha256 != input_sha {
168 debug!(%key, "cache miss: input checksum mismatch");
169 let _ = self.remove_entry(&key);
170 return None;
171 }
172 let now = unix_now();
173 if now.saturating_sub(meta.stored_at_unix) >= self.ttl.as_secs() {
174 debug!(%key, "cache miss: expired");
175 let _ = self.remove_entry(&key);
176 return None;
177 }
178 let body_len = fs::metadata(&body_path).ok()?.len();
183 let budget = if self.max_bytes > 0 {
184 self.max_bytes
185 } else {
186 DEFAULT_MAX_CACHE_BYTES
187 };
188 let read_cap = budget.min(HARD_MAX_BODY_BYTES);
189 if body_len > read_cap {
190 debug!(%key, body_len, read_cap, "cache miss: body exceeds read budget");
191 let _ = self.remove_entry(&key);
192 return None;
193 }
194 let n = usize::try_from(body_len).ok()?;
199 let mut buf = Vec::new();
200 if let Err(e) = buf.try_reserve_exact(n) {
201 debug!(%key, body_len, error = %e, "cache miss: failed to reserve body buffer");
202 return None;
203 }
204 buf.resize(n, 0);
205 {
206 let mut file = fs::File::open(&body_path).ok()?;
207 if file.read_exact(&mut buf).is_err() {
208 debug!(%key, "cache miss: body read failed");
209 return None;
210 }
211 }
212 let body_sha = sha256_hex(&buf);
213 if body_sha != meta.body_sha256 {
214 debug!(%key, "cache miss: body checksum mismatch");
215 let _ = self.remove_entry(&key);
216 return None;
217 }
218 let final_url = Url::parse(&meta.final_url).ok()?;
219 let status = StatusCode::from_u16(meta.status).ok()?;
220 debug!(%key, "cache hit");
221 Some(HttpResponse {
222 status,
223 final_url,
224 body: Bytes::from(buf),
225 content_type: meta.content_type,
226 })
227 }
228
229 pub fn put(&self, url: &Url, accept: &str, resp: &HttpResponse) -> AppResult<()> {
236 if !resp.status.is_success() {
237 return Ok(());
238 }
239 if self.max_bytes > 0 && (resp.body.len() as u64) > self.max_bytes {
242 debug!(
243 body = resp.body.len(),
244 max = self.max_bytes,
245 "cache skip: body exceeds max_bytes"
246 );
247 return Ok(());
248 }
249 let dir = self.entry_dir();
250 fs::create_dir_all(&dir).map_err(|e| {
251 AppError::with_source(
252 ErrorKind::Internal,
253 format!("failed to create cache dir {}", dir.display()),
254 e,
255 )
256 })?;
257 crate::platform::restrict_private_dir(&dir);
258 let key = key_hex(url.as_str(), CACHE_PARSER_VERSION, accept);
259 let input_sha = input_checksum(url.as_str(), CACHE_PARSER_VERSION, accept);
260 let body_sha = sha256_hex(resp.body.as_ref());
261 let meta = CacheMeta {
262 url: url.as_str().to_string(),
263 parser_version: CACHE_PARSER_VERSION.to_string(),
264 accept: accept.to_string(),
265 status: resp.status.as_u16(),
266 content_type: resp.content_type.clone(),
267 final_url: resp.final_url.as_str().to_string(),
268 stored_at_unix: unix_now(),
269 body_sha256: body_sha,
270 input_sha256: input_sha,
271 };
272 let (meta_path, body_path) = self.paths_for_key(&key);
273 let meta_tmp = meta_path.with_extension("meta.json.tmp");
274 let body_tmp = body_path.with_extension("bin.tmp");
275
276 struct TempCleanup {
278 paths: [PathBuf; 2],
279 armed: bool,
280 }
281 impl Drop for TempCleanup {
282 fn drop(&mut self) {
283 if !self.armed {
284 return;
285 }
286 for p in &self.paths {
287 if p.as_os_str().is_empty() {
288 continue;
289 }
290 let _ = fs::remove_file(p);
291 }
292 }
293 }
294 let mut temps = TempCleanup {
296 paths: [body_tmp, meta_tmp],
297 armed: true,
298 };
299
300 {
301 let mut f = fs::File::create(&temps.paths[0]).map_err(|e| {
302 AppError::with_source(ErrorKind::Internal, "cache body temp create", e)
303 })?;
304 f.write_all(resp.body.as_ref())
305 .map_err(|e| AppError::with_source(ErrorKind::Internal, "cache body write", e))?;
306 f.sync_all()
307 .map_err(|e| AppError::with_source(ErrorKind::Internal, "cache body sync", e))?;
308 }
309 {
310 let text = serde_json::to_string(&meta).map_err(|e| {
312 AppError::with_source(ErrorKind::Internal, "cache meta serialize", e)
313 })?;
314 let mut f = fs::File::create(&temps.paths[1]).map_err(|e| {
315 AppError::with_source(ErrorKind::Internal, "cache meta temp create", e)
316 })?;
317 f.write_all(text.as_bytes())
318 .map_err(|e| AppError::with_source(ErrorKind::Internal, "cache meta write", e))?;
319 f.sync_all()
320 .map_err(|e| AppError::with_source(ErrorKind::Internal, "cache meta sync", e))?;
321 }
322
323 fs::rename(&temps.paths[0], &body_path)
324 .map_err(|e| AppError::with_source(ErrorKind::Internal, "cache body rename", e))?;
325 crate::platform::restrict_private_file(&body_path);
326 temps.paths[0] = PathBuf::new();
328 fs::rename(&temps.paths[1], &meta_path).map_err(|e| {
329 AppError::with_source(ErrorKind::Internal, "cache meta rename", e)
331 })?;
332 crate::platform::restrict_private_file(&meta_path);
333 temps.armed = false;
334 debug!(%key, "cache store");
335 self.enforce_max_bytes(Some(&key));
336 Ok(())
337 }
338
339 pub fn clear(&self) -> AppResult<CacheClearResult> {
345 let dir = self.entry_dir();
346 let mut removed_entries = 0u64;
347 let mut freed_bytes = 0u64;
348 if dir.is_dir() {
349 for entry in fs::read_dir(&dir).map_err(|e| {
350 AppError::with_source(ErrorKind::Internal, "cache clear read_dir", e)
351 })? {
352 let entry = entry.map_err(|e| {
353 AppError::with_source(ErrorKind::Internal, "cache clear entry", e)
354 })?;
355 let path = entry.path();
356 let len = entry.metadata().map(|m| m.len()).unwrap_or(0);
357 if path.is_file() {
358 if path
360 .file_name()
361 .and_then(|n| n.to_str())
362 .is_some_and(|n| n.ends_with(".meta.json"))
363 {
364 removed_entries = removed_entries.saturating_add(1);
365 }
366 freed_bytes = freed_bytes.saturating_add(len);
367 let _ = fs::remove_file(&path);
368 }
369 }
370 }
371 Ok(CacheClearResult {
372 root: self.root.display().to_string(),
373 removed_entries,
374 freed_bytes,
375 })
376 }
377
378 pub fn stats(&self) -> CacheStats {
380 let entries = self.scan_entries();
381 let total_bytes = entries.iter().map(|e| e.bytes).sum();
382 CacheStats {
383 root: self.root.display().to_string(),
384 layout: CACHE_LAYOUT.to_string(),
385 entries: entries.len() as u64,
386 total_bytes,
387 max_bytes: self.max_bytes,
388 ttl_secs: self.ttl.as_secs(),
389 parser_version: CACHE_PARSER_VERSION.to_string(),
390 }
391 }
392
393 fn scan_entries(&self) -> Vec<EntryOnDisk> {
394 let dir = self.entry_dir();
395 let mut out = Vec::new();
396 let Ok(rd) = fs::read_dir(&dir) else {
397 return out;
398 };
399 for entry in rd.flatten() {
400 let path = entry.path();
401 let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
402 continue;
403 };
404 let Some(key) = name.strip_suffix(".meta.json") else {
405 continue;
406 };
407 let (meta_path, body_path) = self.paths_for_key(key);
408 if !meta_path.is_file() || !body_path.is_file() {
409 continue;
410 }
411 let meta_len = fs::metadata(&meta_path).map(|m| m.len()).unwrap_or(0);
412 let body_len = fs::metadata(&body_path).map(|m| m.len()).unwrap_or(0);
413 let stored_at = read_meta_file(&meta_path)
416 .map(|m| m.stored_at_unix)
417 .unwrap_or(0);
418 out.push(EntryOnDisk {
419 key: key.to_string(),
420 stored_at_unix: stored_at,
421 bytes: meta_len.saturating_add(body_len),
422 });
423 }
424 out
425 }
426
427 fn enforce_max_bytes(&self, keep_key: Option<&str>) {
431 if self.max_bytes == 0 {
432 return;
433 }
434 loop {
435 let mut entries = self.scan_entries();
436 let total: u64 = entries.iter().map(|e| e.bytes).sum();
437 if total <= self.max_bytes {
438 break;
439 }
440 entries.sort_by_key(|e| e.stored_at_unix);
441 let victim = entries
442 .iter()
443 .find(|e| keep_key.is_none_or(|k| k != e.key.as_str()));
444 let Some(v) = victim else {
445 break;
447 };
448 debug!(key = %v.key, "cache evict for budget");
449 let _ = self.remove_entry(&v.key);
450 }
451 }
452
453 fn remove_entry(&self, key_hex: &str) -> AppResult<()> {
454 let (meta_path, body_path) = self.paths_for_key(key_hex);
455 let _ = fs::remove_file(meta_path);
456 let _ = fs::remove_file(body_path);
457 Ok(())
458 }
459}
460
461pub fn resolve_cache_dir(override_dir: Option<PathBuf>) -> Option<PathBuf> {
469 resolve_cache_dir_with_source(override_dir).0
470}
471
472pub fn resolve_cache_dir_with_source(
474 override_dir: Option<PathBuf>,
475) -> (Option<PathBuf>, crate::config::PathSource) {
476 use crate::config::PathSource;
477 if let Some(p) = override_dir {
478 return (Some(p), PathSource::CliOrEnv);
479 }
480 if let Some(p) = std::env::var_os("DOCSRS_CLI_CACHE_DIR") {
481 return (Some(PathBuf::from(p)), PathSource::CliOrEnv);
482 }
483 if let Some(h) = std::env::var_os("DOCSRS_CLI_HOME") {
484 return (Some(PathBuf::from(h).join("cache")), PathSource::HomeSandbox);
485 }
486 if let Some(p) = directories::ProjectDirs::from("", "", crate::config::APP_NAME)
487 .map(|d| d.cache_dir().to_path_buf())
488 {
489 return (Some(p), PathSource::Xdg);
490 }
491 (None, PathSource::Unresolved)
492}
493
494fn key_hex(url: &str, parser_version: &str, accept: &str) -> String {
495 input_checksum(url, parser_version, accept)
496}
497
498fn read_meta_file(path: &Path) -> Option<CacheMeta> {
503 let len = fs::metadata(path).ok()?.len();
504 if len > MAX_CACHE_META_BYTES {
505 debug!(
506 path = %path.display(),
507 len,
508 cap = MAX_CACHE_META_BYTES,
509 "cache meta exceeds cap"
510 );
511 return None;
512 }
513 let n = usize::try_from(len).ok()?;
514 let mut buf = Vec::new();
515 if let Err(e) = buf.try_reserve_exact(n) {
516 debug!(
517 path = %path.display(),
518 len,
519 error = %e,
520 "cache meta reserve failed"
521 );
522 return None;
523 }
524 buf.resize(n, 0);
525 {
526 let mut file = fs::File::open(path).ok()?;
527 if file.read_exact(&mut buf).is_err() {
528 return None;
529 }
530 }
531 serde_json::from_slice(&buf).ok()
532}
533
534fn input_checksum(url: &str, parser_version: &str, accept: &str) -> String {
535 let mut h = Sha256::new();
536 h.update(url.as_bytes());
537 h.update([0u8]);
538 h.update(parser_version.as_bytes());
539 h.update([0u8]);
540 h.update(accept.as_bytes());
541 hex_encode(h.finalize())
542}
543
544fn sha256_hex(bytes: &[u8]) -> String {
545 let mut h = Sha256::new();
546 h.update(bytes);
547 hex_encode(h.finalize())
548}
549
550fn hex_encode(bytes: impl AsRef<[u8]>) -> String {
551 const HEX: &[u8; 16] = b"0123456789abcdef";
552 let bytes = bytes.as_ref();
553 let mut out = String::with_capacity(bytes.len() * 2);
554 for &b in bytes {
555 out.push(HEX[(b >> 4) as usize] as char);
556 out.push(HEX[(b & 0xf) as usize] as char);
557 }
558 out
559}
560
561fn unix_now() -> u64 {
562 SystemTime::now()
563 .duration_since(UNIX_EPOCH)
564 .map(|d| d.as_secs())
565 .unwrap_or(0)
566}
567
568#[cfg(test)]
569mod tests {
570 use super::*;
571
572 fn sample_resp(url: &Url, body: &'static [u8]) -> HttpResponse {
573 HttpResponse {
574 status: StatusCode::OK,
575 final_url: url.clone(),
576 body: Bytes::from_static(body),
577 content_type: Some("text/html".into()),
578 }
579 }
580
581 #[test]
582 fn put_get_roundtrip() {
583 let dir = tempfile::tempdir().unwrap();
584 let cache = DiskCache::new(dir.path().to_path_buf(), Duration::from_secs(3600), 0);
585 let url = Url::parse("https://docs.rs/serde/latest/serde/index.html").unwrap();
586 let resp = sample_resp(&url, b"<html>ok</html>");
587 cache.put(&url, "text/html", &resp).unwrap();
588 let hit = cache.get(&url, "text/html").expect("cache hit");
589 assert_eq!(hit.body.as_ref(), b"<html>ok</html>");
590 assert_eq!(hit.status, StatusCode::OK);
591 }
592
593 #[test]
594 fn ttl_zero_never_hits() {
595 let dir = tempfile::tempdir().unwrap();
596 let cache = DiskCache::new(dir.path().to_path_buf(), Duration::from_secs(0), 0);
597 let url = Url::parse("https://crates.io/api/v1/crates?q=x").unwrap();
598 let resp = sample_resp(&url, b"{}");
599 cache.put(&url, "application/json", &resp).unwrap();
600 assert!(cache.get(&url, "application/json").is_none());
601 }
602
603 #[test]
604 fn expired_entry_is_miss() {
605 let dir = tempfile::tempdir().unwrap();
606 let cache = DiskCache::new(dir.path().to_path_buf(), Duration::from_secs(10), 0);
607 let url = Url::parse("https://crates.io/api/v1/crates?q=x").unwrap();
608 let resp = sample_resp(&url, b"{}");
609 cache.put(&url, "application/json", &resp).unwrap();
610 let key = key_hex(url.as_str(), CACHE_PARSER_VERSION, "application/json");
611 let (meta_path, _) = cache.paths_for_key(&key);
612 let mut meta: CacheMeta =
613 serde_json::from_str(&fs::read_to_string(&meta_path).unwrap()).unwrap();
614 meta.stored_at_unix = 1;
615 fs::write(&meta_path, serde_json::to_string(&meta).unwrap()).unwrap();
616 let short = DiskCache::new(dir.path().to_path_buf(), Duration::from_secs(1), 0);
617 assert!(short.get(&url, "application/json").is_none());
618 }
619
620 #[test]
621 fn body_tamper_is_miss() {
622 let dir = tempfile::tempdir().unwrap();
623 let cache = DiskCache::new(dir.path().to_path_buf(), Duration::from_secs(3600), 0);
624 let url = Url::parse("https://docs.rs/x/1/x/all.html").unwrap();
625 let resp = sample_resp(&url, b"original");
626 cache.put(&url, "text/html", &resp).unwrap();
627 let key = key_hex(url.as_str(), CACHE_PARSER_VERSION, "text/html");
628 let (_, body_path) = cache.paths_for_key(&key);
629 fs::write(&body_path, b"tampered").unwrap();
630 assert!(cache.get(&url, "text/html").is_none());
631 }
632
633 #[test]
634 fn get_refuses_body_over_max_bytes() {
635 let dir = tempfile::tempdir().unwrap();
638 let writer = DiskCache::new(dir.path().to_path_buf(), Duration::from_secs(3600), 0);
639 let url = Url::parse("https://docs.rs/big/1/big/index.html").unwrap();
640 let body = vec![b'z'; 200];
641 writer
642 .put(
643 &url,
644 "text/html",
645 &HttpResponse {
646 status: StatusCode::OK,
647 final_url: url.clone(),
648 body: Bytes::from(body),
649 content_type: Some("text/html".into()),
650 },
651 )
652 .unwrap();
653 let reader = DiskCache::new(dir.path().to_path_buf(), Duration::from_secs(3600), 50);
654 assert!(reader.get(&url, "text/html").is_none());
655 }
656
657 #[test]
658 fn get_refuses_body_over_hard_max_even_when_budget_unlimited() {
659 use crate::config::HARD_MAX_BODY_BYTES;
662 let dir = tempfile::tempdir().unwrap();
663 let cache = DiskCache::new(dir.path().to_path_buf(), Duration::from_secs(3600), 0);
664 let url = Url::parse("https://docs.rs/poison/1/p/index.html").unwrap();
665 let tiny = sample_resp(&url, b"ok");
666 cache.put(&url, "text/html", &tiny).unwrap();
667 let key = key_hex(url.as_str(), CACHE_PARSER_VERSION, "text/html");
668 let (meta_path, body_path) = cache.paths_for_key(&key);
669 let over = (HARD_MAX_BODY_BYTES as usize).saturating_add(1);
672 fs::write(&body_path, vec![b'P'; over]).unwrap();
673 assert!(meta_path.is_file());
674 assert!(cache.get(&url, "text/html").is_none());
675 }
676
677 #[test]
678 fn get_refuses_meta_over_cap() {
679 let dir = tempfile::tempdir().unwrap();
682 let cache = DiskCache::new(dir.path().to_path_buf(), Duration::from_secs(3600), 0);
683 let url = Url::parse("https://docs.rs/poison-meta/1/p/index.html").unwrap();
684 let tiny = sample_resp(&url, b"ok");
685 cache.put(&url, "text/html", &tiny).unwrap();
686 let key = key_hex(url.as_str(), CACHE_PARSER_VERSION, "text/html");
687 let (meta_path, _body_path) = cache.paths_for_key(&key);
688 let over = (MAX_CACHE_META_BYTES as usize).saturating_add(1);
689 fs::write(&meta_path, vec![b'{'; over]).unwrap();
690 assert!(meta_path.is_file());
691 assert!(cache.get(&url, "text/html").is_none());
692 let stats = cache.stats();
694 assert_eq!(stats.entries, 1);
695 }
696
697 #[test]
698 fn input_checksum_stable() {
699 let a = input_checksum("https://docs.rs/a", "1", "text/html");
700 let b = input_checksum("https://docs.rs/a", "1", "text/html");
701 let c = input_checksum("https://docs.rs/a", "2", "text/html");
702 assert_eq!(a, b);
703 assert_ne!(a, c);
704 assert_eq!(a.len(), 64);
705 }
706
707 #[test]
708 fn non_success_not_stored() {
709 let dir = tempfile::tempdir().unwrap();
710 let cache = DiskCache::new(dir.path().to_path_buf(), Duration::from_secs(3600), 0);
711 let url = Url::parse("https://docs.rs/missing").unwrap();
712 let resp = HttpResponse {
713 status: StatusCode::NOT_FOUND,
714 final_url: url.clone(),
715 body: Bytes::from_static(b"nope"),
716 content_type: None,
717 };
718 cache.put(&url, "text/html", &resp).unwrap();
719 assert!(cache.get(&url, "text/html").is_none());
720 }
721
722 #[test]
723 fn clear_removes_all_entries() {
724 let dir = tempfile::tempdir().unwrap();
725 let cache = DiskCache::new(dir.path().to_path_buf(), Duration::from_secs(3600), 0);
726 for (i, body) in [(1, b"a" as &[u8]), (2, b"bb"), (3, b"ccc")] {
727 let url = Url::parse(&format!("https://docs.rs/c{i}/1/c{i}/index.html")).unwrap();
728 cache
729 .put(&url, "text/html", &sample_resp(&url, body))
730 .unwrap();
731 }
732 let before = cache.stats();
733 assert_eq!(before.entries, 3);
734 assert!(before.total_bytes > 0);
735 let cleared = cache.clear().unwrap();
736 assert_eq!(cleared.removed_entries, 3);
737 assert!(cleared.freed_bytes > 0);
738 let after = cache.stats();
739 assert_eq!(after.entries, 0);
740 assert_eq!(after.total_bytes, 0);
741 }
742
743 #[test]
744 fn max_bytes_evicts_oldest() {
745 let dir = tempfile::tempdir().unwrap();
746 let cache = DiskCache::new(dir.path().to_path_buf(), Duration::from_secs(3600), 700);
748 let u1 = Url::parse("https://docs.rs/a/1/a/index.html").unwrap();
749 let u2 = Url::parse("https://docs.rs/b/1/b/index.html").unwrap();
750 let body1 = vec![b'x'; 200];
751 let body2 = vec![b'y'; 200];
752 cache
753 .put(
754 &u1,
755 "text/html",
756 &HttpResponse {
757 status: StatusCode::OK,
758 final_url: u1.clone(),
759 body: Bytes::from(body1),
760 content_type: Some("text/html".into()),
761 },
762 )
763 .unwrap();
764 std::thread::sleep(Duration::from_millis(20));
765 cache
766 .put(
767 &u2,
768 "text/html",
769 &HttpResponse {
770 status: StatusCode::OK,
771 final_url: u2.clone(),
772 body: Bytes::from(body2),
773 content_type: Some("text/html".into()),
774 },
775 )
776 .unwrap();
777 let stats = cache.stats();
778 assert!(stats.entries <= 1, "stats={stats:?}");
779 assert!(stats.total_bytes <= 700, "stats={stats:?}");
780 assert!(cache.get(&u2, "text/html").is_some());
782 assert!(cache.get(&u1, "text/html").is_none());
783 }
784
785 #[test]
786 fn max_bytes_skips_body_larger_than_budget() {
787 let dir = tempfile::tempdir().unwrap();
788 let cache = DiskCache::new(dir.path().to_path_buf(), Duration::from_secs(3600), 100);
789 let url = Url::parse("https://docs.rs/big/1/big/index.html").unwrap();
790 let body = vec![b'z'; 500];
791 cache
792 .put(
793 &url,
794 "text/html",
795 &HttpResponse {
796 status: StatusCode::OK,
797 final_url: url.clone(),
798 body: Bytes::from(body),
799 content_type: Some("text/html".into()),
800 },
801 )
802 .unwrap();
803 let stats = cache.stats();
804 assert_eq!(stats.entries, 0, "stats={stats:?}");
805 assert_eq!(stats.total_bytes, 0, "stats={stats:?}");
806 assert!(cache.get(&url, "text/html").is_none());
807 }
808}