Skip to main content

docsrs_cli/cache/disk/
read.rs

1//! Serving a cached response: every guard that can turn a hit into a miss.
2//!
3//! A miss is always safe; a wrong hit is not. Every check here answers one
4//! question — "could this entry have been produced by the request we are
5//! serving?" — and a corrupt or stale entry is evicted on the spot rather than
6//! left to fail the same way on the next invocation.
7
8use std::fs;
9use std::io::Read;
10
11use bytes::Bytes;
12use reqwest::{StatusCode, Url};
13use tracing::debug;
14
15use crate::cache::hex::{input_checksum, key_hex, sha256_hex};
16use crate::cache::meta::read_meta_file;
17use crate::cache::types::{CACHE_PARSER_VERSION, DEFAULT_MAX_CACHE_BYTES};
18use crate::config::HARD_MAX_BODY_BYTES;
19use crate::http::HttpResponse;
20
21use super::{DiskCache, unix_now};
22
23impl DiskCache {
24    /// Look up a successful GET response. Returns `None` on miss, expire, or corrupt entry.
25    pub fn get(&self, url: &Url, accept: &str) -> Option<HttpResponse> {
26        // TTL 0 = never serve from disk (always re-fetch).
27        if self.ttl.as_secs() == 0 {
28            return None;
29        }
30        let input_sha = input_checksum(url.as_str(), CACHE_PARSER_VERSION, accept);
31        let key = key_hex(url.as_str(), CACHE_PARSER_VERSION, accept);
32        let (meta_path, body_path) = self.paths_for_key(&key)?;
33        if !meta_path.is_file() || !body_path.is_file() {
34            return None;
35        }
36        let Some(meta) = read_meta_file(&meta_path) else {
37            debug!(%key, "cache miss: meta unreadable or over cap");
38            return None;
39        };
40        // Best-effort eviction on miss paths: cleanup IO must not turn a cache miss
41        // into a hard error (get returns Option; put/clear use AppResult).
42        if meta.parser_version != CACHE_PARSER_VERSION {
43            debug!(%key, "cache miss: parser version mismatch");
44            let _ = self.remove_entry(&key);
45            return None;
46        }
47        if meta.url != url.as_str() || meta.accept != accept {
48            debug!(%key, "cache miss: url/accept mismatch");
49            let _ = self.remove_entry(&key);
50            return None;
51        }
52        if meta.input_sha256 != input_sha {
53            debug!(%key, "cache miss: input checksum mismatch");
54            let _ = self.remove_entry(&key);
55            return None;
56        }
57        let now = unix_now();
58        if now.saturating_sub(meta.stored_at_unix) >= self.ttl.as_secs() {
59            debug!(%key, "cache miss: expired");
60            let _ = self.remove_entry(&key);
61            return None;
62        }
63        // Refuse oversized on-disk bodies before allocating (OOM / corrupt entry guard).
64        let body_len = fs::metadata(&body_path).ok()?.len();
65        let budget = if self.max_bytes > 0 {
66            self.max_bytes
67        } else {
68            DEFAULT_MAX_CACHE_BYTES
69        };
70        let read_cap = budget.min(HARD_MAX_BODY_BYTES);
71        if body_len > read_cap {
72            debug!(%key, body_len, read_cap, "cache miss: body exceeds read budget");
73            let _ = self.remove_entry(&key);
74            return None;
75        }
76        let n = usize::try_from(body_len).ok()?;
77        let mut buf = Vec::new();
78        if let Err(e) = buf.try_reserve_exact(n) {
79            debug!(%key, body_len, error = %e, "cache miss: failed to reserve body buffer");
80            return None;
81        }
82        buf.resize(n, 0);
83        {
84            let mut file = fs::File::open(&body_path).ok()?;
85            if file.read_exact(&mut buf).is_err() {
86                debug!(%key, "cache miss: body read failed");
87                return None;
88            }
89        }
90        let body_sha = sha256_hex(&buf);
91        if body_sha != meta.body_sha256 {
92            debug!(%key, "cache miss: body checksum mismatch");
93            let _ = self.remove_entry(&key);
94            return None;
95        }
96        let final_url = Url::parse(&meta.final_url).ok()?;
97        // Poisoned meta could claim an off-allowlist final_url; refuse the hit.
98        if !crate::http::is_allowed_host(&final_url, self.allow_loopback) {
99            debug!(%key, final = %final_url, "cache miss: final_url not allowlisted");
100            let _ = self.remove_entry(&key);
101            return None;
102        }
103        let status = StatusCode::from_u16(meta.status).ok()?;
104        debug!(%key, "cache hit");
105        Some(HttpResponse {
106            status,
107            final_url,
108            body: Bytes::from(buf),
109            content_type: meta.content_type,
110            cache_hit: true,
111        })
112    }
113}