deps_core/cache/mod.rs
1//! HTTP response cache shared by every ecosystem's registry client.
2//!
3//! Wraps outbound registry requests with RFC 7232 conditional-request
4//! validation (`ETag`/`If-None-Match`, `Last-Modified`/`If-Modified-Since`) so
5//! that unchanged registry data is served from a bounded in-memory cache
6//! instead of re-fetched. Entry count and total retained bytes are both
7//! capped to keep memory use predictable under long-running LSP sessions.
8
9use crate::error::{DepsError, Result};
10use crate::net_policy::{RegistryAccessPolicy, TrustedPrefix, WorkspaceRegistryAccess};
11use crate::redact::RedactedUrl;
12pub use auth::{CredentialHeader, RateLimitRevocation, RequestAuth, RequestHeader};
13pub use body::BodyLimit;
14use dashmap::DashMap;
15pub use response::{CachedResponse, CredentialPartition, RevalidationFailure};
16use std::hash::Hash;
17use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
18use std::sync::{Arc, RwLock};
19use transport::Transport;
20
21mod auth;
22mod body;
23mod errors;
24mod fetch;
25mod guard;
26mod pool;
27mod redirect;
28mod resolver;
29mod response;
30mod store;
31mod transport;
32
33/// Maximum number of cached entries to prevent unbounded memory growth.
34const MAX_CACHE_ENTRIES: usize = 1000;
35
36/// Maximum total bytes retained across all cached response bodies.
37///
38/// `MAX_CACHE_ENTRIES` alone bounds entry *count*, not size: since a single
39/// response body may be as large as [`MAX_RESPONSE_BYTES`](self::body::MAX_RESPONSE_BYTES) (32 MiB), a cache
40/// full of near-cap entries could retain tens of gigabytes even though real
41/// registry payloads are typically well under 1 MB. This budget is a
42/// defense-in-depth cap (CWE-400) against that worst case, evicted
43/// alongside the count-based limit in [`HttpCache::evict_entries`]. 64 MiB
44/// comfortably holds thousands of typical registry responses while still
45/// bounding the pathological case.
46///
47/// This is a best-effort bound, not a hard guarantee: it is checked once
48/// per request in [`HttpCache::get_cached_via`], so multiple
49/// requests already in flight when the budget is crossed can each finish
50/// inserting before the next check fires. [`MAX_CACHEABLE_ENTRY_BYTES`]
51/// keeps that per-request overshoot small (at most one admission-cap-sized
52/// insert per concurrent in-flight request) rather than bounding it exactly.
53const MAX_CACHE_BYTES: usize = 64 * 1024 * 1024;
54
55/// Maximum size of a single response body that will be retained in the
56/// cache; larger bodies are still returned to the caller, just never
57/// stored.
58///
59/// Without this cap, [`MAX_CACHE_BYTES`] alone lets a handful of
60/// large-but-legitimate responses (up to [`MAX_RESPONSE_BYTES`](self::body::MAX_RESPONSE_BYTES), 32 MiB
61/// each) evict the *entire* rest of the cache: at a 2x ratio between the
62/// two constants, just two max-size entries would saturate the whole
63/// budget. Set to an eighth of [`MAX_CACHE_BYTES`] (8 MiB) so no single
64/// entry can claim more than 1/8 of the budget — a handful of large
65/// responses degrade to "not cached" instead of "evicts the small-payload
66/// working set".
67const MAX_CACHEABLE_ENTRY_BYTES: usize = MAX_CACHE_BYTES / 8;
68
69/// Whether [`HttpCache`] may issue outbound network requests (issue #483).
70///
71/// Passed to [`HttpCache::set_offline`]. `Offline` also overrides
72/// [`CacheMode`] to behave as [`CacheMode::Enabled`] — see that method's docs.
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub enum NetworkMode {
75 /// Outbound registry requests are attempted normally.
76 Online,
77 /// All outbound requests are blocked; only cached/warm entries are served.
78 Offline,
79}
80
81impl NetworkMode {
82 /// Builds a `NetworkMode` from a `network.offline` config/CLI flag (`true` means
83 /// [`Self::Offline`]).
84 ///
85 /// The single, explicitly named conversion point from that boundary's `bool`
86 /// representation (issue #1436 S1) — deliberately not a `From<bool>` impl, which would
87 /// let any unrelated `bool` (e.g. a `cache.enabled` flag transposed at the call site)
88 /// silently convert too, defeating the point of typing this API in the first place.
89 #[must_use]
90 pub fn from_offline_flag(offline: bool) -> Self {
91 if offline { Self::Offline } else { Self::Online }
92 }
93
94 /// Whether outbound network requests may be attempted (`self` is [`Self::Online`]).
95 ///
96 /// Centralizes the `network == NetworkMode::Online` check every call site otherwise
97 /// reimplements inline (issue #1557 code-review finding).
98 ///
99 /// # Examples
100 ///
101 /// ```
102 /// use deps_core::NetworkMode;
103 ///
104 /// assert!(NetworkMode::Online.is_online());
105 /// assert!(!NetworkMode::Offline.is_online());
106 /// ```
107 #[must_use]
108 pub const fn is_online(self) -> bool {
109 matches!(self, Self::Online)
110 }
111
112 /// Whether outbound network requests are blocked (`self` is [`Self::Offline`]).
113 ///
114 /// # Examples
115 ///
116 /// ```
117 /// use deps_core::NetworkMode;
118 ///
119 /// assert!(NetworkMode::Offline.is_offline());
120 /// assert!(!NetworkMode::Online.is_offline());
121 /// ```
122 #[must_use]
123 pub const fn is_offline(self) -> bool {
124 matches!(self, Self::Offline)
125 }
126}
127
128/// Whether [`HttpCache`] uses its entry-map cache to serve warm entries (issue #482).
129///
130/// Passed to [`HttpCache::set_cache_enabled`]. See that method's docs for the override
131/// [`NetworkMode::Offline`] has on this value.
132#[derive(Debug, Clone, Copy, PartialEq, Eq)]
133pub enum CacheMode {
134 /// The entry map is consulted and populated as usual.
135 Enabled,
136 /// The entry map is bypassed entirely, except while [`NetworkMode::Offline`] overrides
137 /// this to behave as `Enabled`.
138 Disabled,
139}
140
141impl CacheMode {
142 /// Builds a `CacheMode` from a `cache.enabled` config/CLI flag (`true` means
143 /// [`Self::Enabled`]).
144 ///
145 /// The single, explicitly named conversion point from that boundary's `bool`
146 /// representation — see [`NetworkMode::from_offline_flag`]'s doc for why this is a named
147 /// constructor rather than a `From<bool>` impl.
148 #[must_use]
149 pub fn from_enabled_flag(enabled: bool) -> Self {
150 if enabled {
151 Self::Enabled
152 } else {
153 Self::Disabled
154 }
155 }
156}
157
158/// Which cache-key namespace and [`AddrGuard`](self::guard::AddrGuard) tier a [`Transport`] enforces.
159///
160/// `Baseline` is every non-workspace request (all 11 ecosystems' registry/redirect/API
161/// traffic); `WorkspaceDeclared` is Cargo's workspace-declared-registry traffic, carrying the
162/// same [`WorkspaceRegistryAccess`] **value snapshot** an [`AddrGuard::WorkspaceDeclared`](self::guard::AddrGuard::WorkspaceDeclared)
163/// carries (see that variant's docs) — [`HttpCache::cache_key`] reads the digit from this
164/// snapshot, never from a live `Arc<RegistryAccessPolicy>` read, so a request's cache key and
165/// its guard always agree on which policy era they were constructed under.
166#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
167enum CacheTier {
168 Baseline,
169 WorkspaceDeclared(WorkspaceRegistryAccess),
170 /// An origin-pinned, connect-address-guarded tier (issue #561/#562) — see
171 /// [`Transport::origin_pinned_guarded`]. `digest` identifies the `(trusted_origin,
172 /// policy_snapshot)` pair this transport was built for (**never** a credential identity —
173 /// that is the request's [`RequestAuth`], folded into the cache key only).
174 Pinned {
175 digest: u64,
176 },
177}
178
179/// HTTP cache with ETag and Last-Modified validation.
180///
181/// Implements RFC 7232 conditional requests to minimize network traffic.
182/// All responses are cached with their validation headers, and subsequent
183/// requests use `If-None-Match` (ETag) or `If-Modified-Since` headers
184/// to check for updates.
185///
186/// The cache uses `Bytes` for response bodies, enabling efficient sharing
187/// of cached data across multiple consumers without copying. `Bytes` is
188/// an Arc-like type optimized for network I/O.
189///
190/// # Examples
191///
192/// ```no_run
193/// use deps_core::cache::HttpCache;
194///
195/// # async fn example() -> deps_core::error::Result<()> {
196/// let cache = HttpCache::new();
197///
198/// // First request - fetches from network
199/// let data1 = cache.get_cached("https://index.crates.io/se/rd/serde").await?;
200///
201/// // Second request - uses conditional GET (304 Not Modified if unchanged)
202/// let data2 = cache.get_cached("https://index.crates.io/se/rd/serde").await?;
203/// # Ok(())
204/// # }
205/// ```
206///
207/// # Cache key
208///
209/// Entries are keyed by URL alone (see `Self::cache_key`, private) — `extra_headers` (see
210/// [`HttpCache::get_cached_with_headers`]) play no part in the cache key.
211/// This is safe only as long as "same URL" implies "same representation":
212/// a content-negotiating header (e.g. a per-request `Accept`) that can vary
213/// the response body for an otherwise-identical URL requires giving each
214/// distinct representation its own URL (e.g. a query parameter or distinct
215/// path), not just a distinct header value, or callers requesting different
216/// representations of the same URL will silently share one cache entry.
217///
218/// Likewise, the key doesn't encode *which* client (and so which redirect policy)
219/// produced an entry — [`HttpCache::get_cached`] and [`HttpCache::get_cached_trusted_origin`]
220/// share one entry map. No caller today requests the same URL through both, but one that did
221/// could observe the other's cached (and differently redirect-validated) body.
222///
223/// [`Self::get_cached_workspace`] is the one exception: it is namespaced under a distinct,
224/// policy-scoped key prefix (see `Self::cache_key`, private) so a body fetched under a looser
225/// [`crate::net_policy::WorkspaceRegistryAccess`] can never be served back once the policy
226/// tightens.
227pub struct HttpCache {
228 entries: DashMap<String, CachedResponse>,
229 /// Running total of `body.len()` across all `entries`, kept in sync by
230 /// [`HttpCache::store_entry`], [`HttpCache::evict_entries`], and
231 /// [`HttpCache::clear`] via relative `fetch_add`/`fetch_sub` only —
232 /// never an absolute `store` after the initial `0`, since that would
233 /// silently discard any concurrent relative update racing with it. Used
234 /// to trigger byte-bounded eviction without summing every entry on each
235 /// check; advisory (see [`MAX_CACHE_BYTES`]), not an exact live count
236 /// under concurrent access.
237 total_bytes: AtomicUsize,
238 /// The shared, unauthenticated transport used by every non-workspace request.
239 baseline: Transport,
240 /// Per-`(trusted_origin, tier)` transport pool backing [`Self::get_cached_trusted_origin`]
241 /// and [`Self::get_cached_pinned`] alike (issue #561/#562, FR-017), keyed by the exact
242 /// `trusted_origin` prefix string passed to that call, paired with the [`CacheTier`] it was
243 /// built for. reqwest's redirect policy is fixed per-`Client`, so a distinct client is
244 /// unavoidable per distinct origin; pooled here so repeated calls against the same
245 /// `(origin, tier)` reuse one transport (and its connection pool) instead of rebuilding on
246 /// every call. Deliberately **uncapped** — see [`Self::set_registry_policy`]'s docs for why
247 /// a capacity cap was considered and dropped for this pool.
248 trusted_clients: DashMap<(TrustedPrefix, CacheTier), Transport>,
249 /// Live-updatable Cargo workspace-registry policy the `workspace` transport field below
250 /// and cache-key namespace are derived from. Kept alongside that field (not just read once
251 /// at construction) so [`Self::cache_key`] and [`Self::set_registry_policy`] both read the
252 /// same discriminant.
253 policy: Arc<RegistryAccessPolicy>,
254 /// The transport for [`Self::get_cached_workspace`], rebuilt in place by
255 /// [`Self::set_registry_policy`] on every actual policy transition.
256 workspace: RwLock<Transport>,
257 /// Test-only counter of how many times [`Self::set_registry_policy`] has actually rebuilt
258 /// the `workspace` transport field above (as opposed to no-op'ing on an unchanged value) —
259 /// asserts C4's rebuild-only-on-change behavior directly.
260 #[cfg(test)]
261 workspace_rebuilds: AtomicUsize,
262 /// Live-updatable "no outbound requests" flag (issue #483). Enforced by
263 /// [`Self::ensure_online`] at all 4 send sites. See [`Self::set_offline`]'s docs for
264 /// the override this has on `cache_enabled` below.
265 offline: AtomicBool,
266 /// Live-updatable entry-map toggle (issue #482): `false` bypasses the entry map
267 /// entirely (see `get_cached_via`). Overridden to effectively `true`
268 /// whenever `offline` is set — see [`Self::set_offline`]'s docs.
269 cache_enabled: AtomicBool,
270}
271
272impl HttpCache {
273 /// Creates a new HTTP cache with default configuration and the default
274 /// [`crate::net_policy::WorkspaceRegistryAccess`] policy (`PublicOnly`).
275 ///
276 /// The cache uses a configurable timeout for all requests and identifies
277 /// itself with an auto-versioned user agent.
278 pub fn new() -> Self {
279 Self::with_policy(Arc::new(RegistryAccessPolicy::default()))
280 }
281
282 /// The registry-access policy this cache enforces and reports guarded traffic to.
283 #[must_use]
284 pub const fn registry_policy(&self) -> &Arc<RegistryAccessPolicy> {
285 &self.policy
286 }
287
288 /// Creates a new HTTP cache whose [`Self::get_cached_workspace`] requests are governed by
289 /// `policy`'s live value.
290 ///
291 /// A later [`Self::set_registry_policy`] call rebuilds the workspace transport (and its
292 /// cache-key namespace) in place, so every caller holding this `HttpCache` sees the new
293 /// policy take effect immediately, with no need to reconstruct the cache.
294 ///
295 /// # Examples
296 ///
297 /// ```
298 /// use deps_core::HttpCache;
299 /// use deps_core::net_policy::RegistryAccessPolicy;
300 /// use std::sync::Arc;
301 ///
302 /// let policy = Arc::new(RegistryAccessPolicy::default());
303 /// let cache = HttpCache::with_policy(Arc::clone(&policy));
304 /// assert!(cache.is_empty());
305 /// ```
306 pub fn with_policy(policy: Arc<RegistryAccessPolicy>) -> Self {
307 let workspace = Transport::workspace(&policy);
308 Self {
309 entries: DashMap::new(),
310 total_bytes: AtomicUsize::new(0),
311 baseline: Transport::baseline(),
312 trusted_clients: DashMap::new(),
313 policy,
314 workspace: RwLock::new(workspace),
315 #[cfg(test)]
316 workspace_rebuilds: AtomicUsize::new(0),
317 offline: AtomicBool::new(false),
318 cache_enabled: AtomicBool::new(true),
319 }
320 }
321
322 /// Sets whether outbound network requests are permitted (issue #483).
323 ///
324 /// Enforced by `Self::ensure_online` (private) at every one of this module's 4 send sites —
325 /// effective for every call after this returns. While `mode` is [`NetworkMode::Offline`],
326 /// this also overrides `cache_enabled` (see [`Self::set_cache_enabled`]) to behave as
327 /// [`CacheMode::Enabled`] on both the read and write path in `get_cached_via`:
328 /// without this, a warm entry fetched before going offline could never have been stored in
329 /// the first place if caching was disabled, leaving the offline warm-cache path with
330 /// nothing to serve — the exact combination `cache.enabled: false` + `network.offline: true`
331 /// is meant to survive.
332 pub fn set_offline(&self, mode: NetworkMode) {
333 self.offline
334 .store(mode == NetworkMode::Offline, Ordering::Relaxed);
335 }
336
337 /// Returns whether outbound network requests are currently blocked.
338 #[must_use]
339 pub fn is_offline(&self) -> bool {
340 self.offline.load(Ordering::Relaxed)
341 }
342
343 /// Sets whether the entry-map cache is used (issue #482). See [`Self::set_offline`]'s
344 /// docs for the override `offline` has on this flag while set.
345 pub fn set_cache_enabled(&self, mode: CacheMode) {
346 self.cache_enabled
347 .store(mode == CacheMode::Enabled, Ordering::Relaxed);
348 }
349
350 /// Returns `Err(DepsError::Offline)` when `network.offline` is set, without making any
351 /// request — the last check before a socket opens at each of this module's 4 send
352 /// sites, placed beside the existing [`ensure_https`](self::guard::ensure_https) call at each.
353 fn ensure_online(&self, url: &str) -> Result<()> {
354 if self.is_offline() {
355 return Err(DepsError::Offline {
356 url: RedactedUrl::new(url),
357 });
358 }
359 Ok(())
360 }
361}
362
363impl Default for HttpCache {
364 fn default() -> Self {
365 Self::new()
366 }
367}
368
369#[cfg(test)]
370mod tests;