deps_core/cache/store.rs
1//! Entry storage, cache keys, byte accounting, and eviction for `HttpCache`.
2
3use super::CacheTier;
4use super::HttpCache;
5use super::MAX_CACHE_BYTES;
6use super::MAX_CACHE_ENTRIES;
7use super::MAX_CACHEABLE_ENTRY_BYTES;
8use super::auth::KeyAuth;
9use super::response::CachedResponse;
10use crate::cache_policy::CACHE_EVICTION_PERCENTAGE;
11#[cfg(feature = "test-util")]
12use bytes::Bytes;
13use std::borrow::Cow;
14use std::sync::atomic::Ordering;
15use std::time::Instant;
16
17impl HttpCache {
18 /// Byte length of [`Self::BASELINE_AUTH_KEY_PREFIX`], the variant tag and the 16-digit id
19 /// field.
20 const BASELINE_AUTH_KEY_HEAD_LEN: usize = 1 + 1 + 16;
21
22 /// Computes the cache-map key for `url` under `tier` — `Cow::Borrowed(url)` for an
23 /// anonymous, unpartitioned [`CacheTier::Baseline`] request (allocation-free, and identical
24 /// to every entry this cache wrote before this policy-tier split existed), or a prefixed
25 /// owned key otherwise.
26 ///
27 /// [`CacheTier::WorkspaceDeclared`] folds in a policy digit so a policy tightening can never
28 /// serve a body fetched under a looser policy (C5): the digit comes from `tier`'s own
29 /// snapshot — the exact same value the paired [`Transport`](super::transport::Transport)'s [`AddrGuard`](super::guard::AddrGuard) enforced for
30 /// this request, taken together at [`Transport::workspace`](super::transport::Transport::workspace) construction time — never a
31 /// separate live `self.policy` read, which would open a read-skew window between the guard
32 /// that let a fetch through and the key that fetch's body gets stored under.
33 ///
34 /// Callers must compute this once per request and thread the result through, never
35 /// recompute mid-request — a policy flip between two recomputations would read and write
36 /// under different keys for what should be one atomic operation.
37 ///
38 /// `auth` is folded in for [`CacheTier::Pinned`] and [`CacheTier::Baseline`], always with a
39 /// one-char variant tag (`A` credentialed, `U` anonymous) ahead of the partition, so the
40 /// same [`CredentialPartition`](super::CredentialPartition) used with and without a credential yields two entries. A
41 /// partition is encoded as a tag (`0`/`1`) before a fixed-width hex field rather than a `0`
42 /// sentinel: `auth_digest` is a non-cryptographic hash, so
43 /// `Some(0)` is a legitimate digest (issue #1025). Every field is fixed width, so no tag or
44 /// field can be confused with part of another field or `url`.
45 pub(super) fn cache_key<'a>(
46 &self,
47 url: &'a str,
48 tier: CacheTier,
49 auth: KeyAuth,
50 ) -> Cow<'a, str> {
51 match tier {
52 CacheTier::Baseline => match auth {
53 KeyAuth::Anonymous(None) => Cow::Borrowed(url),
54 KeyAuth::Anonymous(Some(partition)) => Cow::Owned(format!(
55 "{}U{:016x}{url}",
56 Self::BASELINE_AUTH_KEY_PREFIX,
57 partition.get()
58 )),
59 KeyAuth::Credential(partition) => Cow::Owned(format!(
60 "{}A{:016x}{url}",
61 Self::BASELINE_AUTH_KEY_PREFIX,
62 partition.get()
63 )),
64 },
65 CacheTier::WorkspaceDeclared(snapshot) => {
66 Cow::Owned(format!("{}{}{url}", Self::WS_KEY_PREFIX, snapshot.to_u8()))
67 }
68 CacheTier::Pinned { digest } => {
69 let (partition_tag, id) = match auth {
70 KeyAuth::Anonymous(None) => ('0', 0),
71 KeyAuth::Anonymous(Some(p)) | KeyAuth::Credential(p) => ('1', p.get()),
72 };
73 let variant_tag = if auth.is_credentialed() { 'A' } else { 'U' };
74 Cow::Owned(format!(
75 "{}{digest:016x}{partition_tag}{id:016x}{variant_tag}{url}",
76 Self::PINNED_KEY_PREFIX,
77 ))
78 }
79 }
80 }
81
82 /// Inserts (or replaces) a cache entry, keeping [`Self::total_bytes`] in sync.
83 ///
84 /// `DashMap::insert` returns the replaced value, if any, so the byte
85 /// delta is computed from a single insert rather than a separate
86 /// lookup-then-insert (which would race with concurrent writers).
87 ///
88 /// A body larger than [`MAX_CACHEABLE_ENTRY_BYTES`] is not inserted at
89 /// all (the caller already has it from the network response; only
90 /// caching is skipped), and any stale entry previously cached for this
91 /// URL is dropped rather than left to serve increasingly outdated data.
92 pub(super) fn store_entry(&self, url: String, response: CachedResponse) {
93 let new_len = response.body.len();
94
95 if new_len > MAX_CACHEABLE_ENTRY_BYTES {
96 if let Some((_, old)) = self.entries.remove(&url) {
97 self.total_bytes
98 .fetch_sub(old.body.len(), Ordering::Relaxed);
99 }
100 return;
101 }
102
103 let old_len = self
104 .entries
105 .insert(url, response)
106 .map_or(0, |old| old.body.len());
107 self.total_bytes.fetch_add(new_len, Ordering::Relaxed);
108 self.total_bytes.fetch_sub(old_len, Ordering::Relaxed);
109 }
110
111 /// Clears all cached entries.
112 ///
113 /// This removes all cached responses, forcing the next request for
114 /// any URL to fetch fresh data from the network.
115 pub fn clear(&self) {
116 self.entries.clear();
117 self.total_bytes.store(0, Ordering::Relaxed);
118 }
119
120 /// Drops every baseline-tier entry whose URL starts with `url_prefix`, returning how many.
121 ///
122 /// For a caller whose request credential or trust changed: drops bare-URL entries and
123 /// `auth_id`-partitioned ones alike, as memory hygiene for bodies fetched under a state that
124 /// no longer applies.
125 ///
126 /// # Examples
127 ///
128 /// ```
129 /// use deps_core::cache::HttpCache;
130 ///
131 /// assert_eq!(HttpCache::new().evict_url_prefix("https://registry.example/api/"), 0);
132 /// ```
133 pub fn evict_url_prefix(&self, url_prefix: &str) -> usize {
134 self.evict_entries_where(|key| {
135 let url = if key.starts_with(Self::BASELINE_AUTH_KEY_PREFIX) {
136 key.get(Self::BASELINE_AUTH_KEY_HEAD_LEN..)
137 } else {
138 Some(key)
139 };
140 url.is_some_and(|url| url.starts_with(url_prefix))
141 })
142 }
143
144 /// Removes every entry whose key satisfies `matches`, keeping [`Self::total_bytes`] in sync;
145 /// returns how many were removed.
146 pub(super) fn evict_entries_where(&self, matches: impl Fn(&str) -> bool) -> usize {
147 let mut freed_bytes = 0usize;
148 let mut evicted = 0usize;
149 self.entries.retain(|key, value| {
150 let drop_entry = matches(key);
151 if drop_entry {
152 freed_bytes += value.body.len();
153 evicted += 1;
154 }
155 !drop_entry
156 });
157 self.total_bytes.fetch_sub(freed_bytes, Ordering::Relaxed);
158 evicted
159 }
160
161 /// Returns the number of cached entries.
162 pub fn len(&self) -> usize {
163 self.entries.len()
164 }
165
166 /// Returns `true` if the cache contains no entries.
167 pub fn is_empty(&self) -> bool {
168 self.entries.is_empty()
169 }
170
171 /// Returns the total bytes retained across all cached response bodies.
172 pub fn total_bytes(&self) -> usize {
173 self.total_bytes.load(Ordering::Relaxed)
174 }
175
176 /// Evicts the oldest cache entries when either capacity limit is reached.
177 ///
178 /// When the entry count is at or over `MAX_CACHE_ENTRIES`, evicts at
179 /// least `CACHE_EVICTION_PERCENTAGE`% of entries (by count). Note this
180 /// is a *fix*, not a preserved behavior: the original count-only
181 /// eviction built its bounded min-heap with an inverted comparison
182 /// (`peek()` returns the oldest entry, but the old code treated it as
183 /// the newest-of-the-oldest-so-far and only replaced it when a *newer*
184 /// candidate came along that was still older than it — backwards), so
185 /// it evicted roughly the first `target_removals` entries in DashMap
186 /// hash-iteration order, not the oldest ones. This version evicts
187 /// genuinely oldest-first.
188 ///
189 /// Independently, if the tracked byte total is over [`MAX_CACHE_BYTES`]
190 /// — which can happen with far fewer than `MAX_CACHE_ENTRIES` entries if
191 /// a few responses are large — eviction keeps removing the next-oldest
192 /// entries until the byte budget is satisfied too. A cache that is over
193 /// the byte budget but well under the entry-count threshold only evicts
194 /// as many entries as the byte budget requires, not a fixed count-based
195 /// batch.
196 ///
197 /// Builds a min-heap over all entry keys by `fetched_at` (O(N)), then
198 /// pops the oldest one at a time (O(R log N) for R removals) — unlike a
199 /// heap bounded to a fixed top-K, the removal count isn't known upfront
200 /// since it depends on the byte budget as well as the count target.
201 ///
202 /// Every byte-count adjustment here is a relative `fetch_sub` applied to
203 /// exactly the entry [`DashMap::remove`](dashmap::DashMap::remove) actually returned — never a
204 /// snapshot-then-absolute-`store` of a locally computed total. The
205 /// latter would silently discard any [`Self::store_entry`] delta that
206 /// lands between this method's start and its end (lost-update race), and
207 /// under adversarial timing could even underflow `total_bytes` to
208 /// `usize::MAX`, permanently wedging every future request into
209 /// evicting the entire cache. Reading `total_bytes` fresh on every loop
210 /// iteration (rather than maintaining a local mirror) keeps this
211 /// correct under concurrent `evict_entries`/`store_entry` calls: two
212 /// callers can race to remove the same key — the second `remove` simply
213 /// returns `None` and is a no-op, not a double-subtraction.
214 pub(super) fn evict_entries(&self) {
215 use std::cmp::Reverse;
216 use std::collections::BinaryHeap;
217
218 let count_target_removals = if self.entries.len() >= MAX_CACHE_ENTRIES {
219 (MAX_CACHE_ENTRIES / CACHE_EVICTION_PERCENTAGE).max(1)
220 } else {
221 0
222 };
223
224 let mut oldest: BinaryHeap<Reverse<(Instant, String)>> = self
225 .entries
226 .iter()
227 .map(|entry| Reverse((entry.value().fetched_at, entry.key().clone())))
228 .collect();
229
230 let mut removed = 0usize;
231
232 while removed < count_target_removals
233 || self.total_bytes.load(Ordering::Relaxed) > MAX_CACHE_BYTES
234 {
235 let Some(Reverse((_, url))) = oldest.pop() else {
236 break;
237 };
238 if let Some((_, old)) = self.entries.remove(&url) {
239 self.total_bytes
240 .fetch_sub(old.body.len(), Ordering::Relaxed);
241 }
242 removed += 1;
243 }
244
245 tracing::debug!(
246 "evicted {removed} cache entries ({} bytes remaining)",
247 self.total_bytes.load(Ordering::Relaxed)
248 );
249 }
250
251 /// Benchmark-only helper: Direct cache lookup without network requests.
252 #[cfg(feature = "test-util")]
253 #[doc(hidden)]
254 pub fn get_for_bench(&self, url: &str) -> Option<Bytes> {
255 self.entries.get(url).map(|entry| entry.body.clone())
256 }
257
258 /// Benchmark-only helper: Direct cache insertion.
259 #[cfg(feature = "test-util")]
260 #[doc(hidden)]
261 pub fn insert_for_bench(&self, url: String, response: CachedResponse) {
262 self.store_entry(url, response);
263 }
264}