deps-core 4.0.0

Core abstractions for deps-lsp: caching, errors, and traits
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
//! Bounded-`DashMap` capacity policies shared across this crate's caches and, since this
//! module is `pub`, across ecosystem crates too.
//!
//! Every eviction policy that governs a plain, per-entry-timestamped `DashMap<K, V>` memo
//! lives here, named, so a new cache reaches for an existing policy instead of growing a
//! near-duplicate (`github::ReleaseDatesCache` and `deps_dev`'s two memos each used to carry
//! their own copy of [`crate::cache_policy::evict_expired_then_oldest`]'s body;
//! `osv::OsvClient`'s two caches shared one local copy of
//! [`crate::cache_policy::evict_oldest_batch`]'s; and `deps-github-actions`,
//! `deps-gitlab-ci`, and `deps-npm` each carried their own near-duplicate of
//! [`crate::cache_policy::evict_arbitrary_if_full`]/
//! [`crate::cache_policy::evict_expired_then_clear_all`]'s bodies, before this module
//! existed).
//!
//! [`crate::lockfile::LockFileCache`]'s eviction and [`crate::cache::HttpCache`]'s
//! byte-accounted eviction are deliberately **not** here:
//! - `LockFileCache` has no per-entry TTL, so
//!   [`crate::cache_policy::evict_expired_then_oldest`]'s sweep half does not apply to it;
//!   its eviction logs a `warn!` naming the victim key, which a generic helper
//!   would have to thread through as another closure parameter; and its capacity is
//!   per-instance (`with_capacity`), not a shared const, so there is no knob here to unify.
//! - `HttpCache` tracks cumulative retained bytes (`total_bytes: AtomicUsize`) alongside entry
//!   count — state a plain `DashMap<K, V>` capacity policy has no field for — so folding it in
//!   would either lose that accounting or force every other caller to carry an unused field.

use std::time::{Duration, Instant};

use dashmap::DashMap;

/// Percentage of a cache's capacity evicted when it is full, by [`evict_oldest_batch`] and by
/// `crate::cache::HttpCache::evict_entries` (which computes its own byte-budget analog of
/// this same fraction).
pub const CACHE_EVICTION_PERCENTAGE: usize = 10;

/// Evicts entries from `map` when it is already at `max_entries`, ahead of an insert that
/// would otherwise grow it further.
///
/// First every entry expired against its own TTL, then — only if that freed nothing — the
/// single oldest entry by `fetched_at`.
///
/// # Examples
///
/// ```
/// use dashmap::DashMap;
/// use deps_core::cache_policy::evict_expired_then_oldest;
/// use std::time::{Duration, Instant};
///
/// let map: DashMap<u32, Instant> = DashMap::new();
/// let now = Instant::now();
/// map.insert(1, now); // oldest
/// map.insert(2, now + Duration::from_secs(1));
///
/// // Neither entry is TTL-expired, so the single oldest one is evicted instead.
/// evict_expired_then_oldest(&map, 2, |fetched_at| *fetched_at, |_| Duration::from_secs(60));
///
/// assert!(!map.contains_key(&1));
/// assert!(map.contains_key(&2));
/// ```
pub fn evict_expired_then_oldest<K, V>(
    map: &DashMap<K, V>,
    max_entries: usize,
    fetched_at: impl Fn(&V) -> Instant,
    ttl: impl Fn(&V) -> Duration,
) where
    K: Eq + std::hash::Hash + Clone,
{
    evict_expired_then_oldest_at(map, max_entries, Instant::now(), fetched_at, ttl);
}

/// [`evict_expired_then_oldest`] against a caller-supplied `now`.
///
/// For maps stamped with a clock other than `std::time::Instant::now()` — e.g. a
/// `tokio::time::Instant` converted via `into_std()`, which under `start_paused` runs ahead of
/// the real clock, so a `now` read from the real clock would never see an entry expire.
///
/// # Examples
///
/// ```
/// use dashmap::DashMap;
/// use deps_core::cache_policy::evict_expired_then_oldest_at;
/// use std::time::{Duration, Instant};
///
/// let map: DashMap<u32, Instant> = DashMap::new();
/// let base = Instant::now();
/// map.insert(1, base);
/// map.insert(2, base + Duration::from_secs(50));
///
/// // At `base + 61s` only entry 1 is past its 60 s TTL.
/// let now = base + Duration::from_secs(61);
/// evict_expired_then_oldest_at(&map, 2, now, |at| *at, |_| Duration::from_secs(60));
///
/// assert!(!map.contains_key(&1));
/// assert!(map.contains_key(&2));
/// ```
pub fn evict_expired_then_oldest_at<K, V>(
    map: &DashMap<K, V>,
    max_entries: usize,
    now: Instant,
    fetched_at: impl Fn(&V) -> Instant,
    ttl: impl Fn(&V) -> Duration,
) where
    K: Eq + std::hash::Hash + Clone,
{
    if map.len() < max_entries {
        return;
    }
    map.retain(|_, v| now.saturating_duration_since(fetched_at(v)) < ttl(v));
    if map.len() >= max_entries
        && let Some(oldest) = map
            .iter()
            .min_by_key(|e| fetched_at(e.value()))
            .map(|e| e.key().clone())
    {
        map.remove(&oldest);
    }
}

/// Evicts the oldest `1/CACHE_EVICTION_PERCENTAGE` (see [`CACHE_EVICTION_PERCENTAGE`]) of
/// `max_entries` — i.e. of the cache's capacity, not necessarily of `map.len()` — by
/// `fetched_at`.
///
/// Caller must only invoke this when `map` is already at `max_entries`: unlike
/// [`evict_expired_then_oldest`], this does not check `map.len()` itself, so calling it
/// unconditionally on a map far below capacity can evict entries needlessly.
///
/// # Examples
///
/// ```
/// use dashmap::DashMap;
/// use deps_core::cache_policy::{CACHE_EVICTION_PERCENTAGE, evict_oldest_batch};
/// use std::time::{Duration, Instant};
///
/// let map: DashMap<u32, Instant> = DashMap::new();
/// let now = Instant::now();
/// for key in 0..CACHE_EVICTION_PERCENTAGE as u32 {
///     map.insert(key, now + Duration::from_secs(u64::from(key)));
/// }
///
/// // At capacity, 1/CACHE_EVICTION_PERCENTAGE of max_entries is evicted: here, just the
/// // single oldest entry (key `0`).
/// evict_oldest_batch(&map, CACHE_EVICTION_PERCENTAGE, |fetched_at| *fetched_at);
///
/// assert!(!map.contains_key(&0));
/// assert_eq!(map.len(), CACHE_EVICTION_PERCENTAGE - 1);
/// ```
pub fn evict_oldest_batch<K, V>(
    map: &DashMap<K, V>,
    max_entries: usize,
    fetched_at: impl Fn(&V) -> Instant,
) where
    K: Eq + std::hash::Hash + Clone + Ord,
{
    evict_oldest_batch_where(map, max_entries, fetched_at, |_| true);
}

/// [`evict_oldest_batch`] restricted to entries `evictable` accepts.
///
/// The batch size is still `1/CACHE_EVICTION_PERCENTAGE` of `max_entries`, but only accepted
/// entries are candidates, so a map full of protected entries evicts nothing. Ties on
/// `fetched_at` break by key order, which keeps the victims deterministic.
///
/// # Examples
///
/// ```
/// use dashmap::DashMap;
/// use deps_core::cache_policy::evict_oldest_batch_where;
/// use std::time::{Duration, Instant};
///
/// let map: DashMap<u32, (Instant, bool)> = DashMap::new();
/// let now = Instant::now();
/// map.insert(0, (now, false)); // oldest, but protected
/// map.insert(1, (now + Duration::from_secs(1), true));
///
/// evict_oldest_batch_where(&map, 10, |(at, _)| *at, |(_, evictable)| *evictable);
///
/// assert!(map.contains_key(&0));
/// assert!(!map.contains_key(&1));
/// ```
pub fn evict_oldest_batch_where<K, V>(
    map: &DashMap<K, V>,
    max_entries: usize,
    fetched_at: impl Fn(&V) -> Instant,
    evictable: impl Fn(&V) -> bool,
) where
    K: Eq + std::hash::Hash + Clone + Ord,
{
    use std::cmp::Reverse;
    use std::collections::BinaryHeap;

    let target_removals = (max_entries / CACHE_EVICTION_PERCENTAGE).max(1);
    let mut oldest: BinaryHeap<Reverse<(Instant, K)>> = map
        .iter()
        .filter(|entry| evictable(entry.value()))
        .map(|entry| Reverse((fetched_at(entry.value()), entry.key().clone())))
        .collect();

    for _ in 0..target_removals {
        let Some(Reverse((_, key))) = oldest.pop() else {
            break;
        };
        map.remove(&key);
    }
}

/// Evicts a single arbitrary entry from `map` when it is already at `max_entries`, ahead of
/// an insert that would otherwise grow it further.
///
/// The victim is the single oldest-inserted entry, approximated by removing an arbitrary
/// entry: suited to a map with no per-entry timestamp (e.g. a tag/SHA cross-reference), where
/// a repeated fetch simply repopulates whichever entry was dropped. Reach for
/// [`evict_expired_then_oldest`] or [`evict_expired_then_clear_all`] instead when entries do
/// carry a `fetched_at`. The O(n) scan runs only on an insert that finds the map full.
///
/// **Must not be used for an in-flight coalescing lock map** (e.g. a
/// `DashMap<K, Arc<Mutex<()>>>` tracking requests currently in flight): removing an arbitrary
/// entry there can evict one whose lock is still held by another waiter, silently defeating
/// coalescing under exactly the load it targets. That case needs a policy that only evicts an
/// entry whose `Arc::strong_count()` is `1` — see `deps_github_actions::registry`'s
/// `evict_in_flight_if_full` for that pattern.
///
/// # Examples
///
/// ```
/// use dashmap::DashMap;
/// use deps_core::cache_policy::evict_arbitrary_if_full;
///
/// let map: DashMap<u32, &str> = DashMap::new();
/// map.insert(1, "a");
/// map.insert(2, "b");
/// evict_arbitrary_if_full(&map, 2);
/// assert_eq!(map.len(), 1);
/// ```
pub fn evict_arbitrary_if_full<K, V>(map: &DashMap<K, V>, max_entries: usize)
where
    K: Eq + std::hash::Hash + Clone,
{
    if map.len() < max_entries {
        return;
    }
    // The victim key is resolved in its own `let` binding, fully dropping the iterator (and
    // whatever shard guard it holds) before `remove` runs — folding this into a single
    // `if let Some(key) = map.iter()....` risks the iterator's temporary being scope-extended
    // across the `remove` call (Rust's `if let` temporary-lifetime-extension rule), which can
    // deadlock against `DashMap`'s internal per-shard locking.
    let victim = map.iter().next().map(|e| e.key().clone());
    if let Some(key) = victim {
        map.remove(&key);
    }
}

/// Drops every entry in `map` expired against its own TTL; if that alone did not bring `map`
/// back under `max_entries`, clears the whole map.
///
/// Caller must only invoke this when `map` is already at `max_entries`: unlike
/// [`evict_expired_then_oldest`], this does not check `map.len()` itself before running the
/// TTL sweep, so calling it unconditionally on a map far below capacity discards expired
/// entries needlessly (though never live ones, since the sweep only ever removes entries
/// whose own TTL has elapsed).
///
/// # Examples
///
/// ```
/// use dashmap::DashMap;
/// use deps_core::cache_policy::evict_expired_then_clear_all;
/// use std::time::{Duration, Instant};
///
/// let map: DashMap<u32, Instant> = DashMap::new();
/// map.insert(1, Instant::now());
/// evict_expired_then_clear_all(&map, 2, |fetched_at| *fetched_at, Duration::from_secs(60));
/// assert_eq!(map.len(), 1);
/// ```
pub fn evict_expired_then_clear_all<K, V>(
    map: &DashMap<K, V>,
    max_entries: usize,
    fetched_at: impl Fn(&V) -> Instant,
    ttl: Duration,
) where
    K: Eq + std::hash::Hash,
{
    let now = Instant::now();
    map.retain(|_, v| now.saturating_duration_since(fetched_at(v)) < ttl);
    if map.len() >= max_entries {
        map.clear();
    }
}

#[cfg(test)]
mod tests {
    use super::{
        CACHE_EVICTION_PERCENTAGE, evict_arbitrary_if_full, evict_expired_then_clear_all,
        evict_oldest_batch,
    };
    use dashmap::DashMap;
    use std::time::{Duration, Instant};

    struct Entry {
        fetched_at: Instant,
    }

    fn map_with_ages(count: usize) -> DashMap<usize, Entry> {
        let map = DashMap::new();
        let base = Instant::now();
        for i in 0..count {
            map.insert(
                i,
                Entry {
                    // Higher key => more recently fetched, so key `0` is oldest.
                    fetched_at: base + Duration::from_secs(i as u64),
                },
            );
        }
        map
    }

    #[test]
    fn removes_exactly_the_target_count() {
        let map = map_with_ages(100);
        evict_oldest_batch(&map, 100, |e| e.fetched_at);
        assert_eq!(map.len(), 90);
    }

    #[test]
    fn removes_oldest_entries_and_keeps_newest() {
        let map = map_with_ages(100);
        let target_removals = (100 / CACHE_EVICTION_PERCENTAGE).max(1);
        evict_oldest_batch(&map, 100, |e| e.fetched_at);

        for key in 0..target_removals {
            assert!(!map.contains_key(&key), "expected key {key} to be evicted");
        }
        for key in target_removals..100 {
            assert!(map.contains_key(&key), "expected key {key} to survive");
        }
    }

    #[test]
    fn floors_target_removals_at_one_below_percentage_threshold() {
        let map = map_with_ages(5);
        evict_oldest_batch(&map, 5, |e| e.fetched_at);
        assert_eq!(map.len(), 5 - 1);
        assert!(!map.contains_key(&0));
    }

    #[test]
    fn empties_without_panicking_when_smaller_than_target() {
        let map = map_with_ages(3);
        // max_entries is much larger than the map itself, so the target removal count
        // (max_entries / CACHE_EVICTION_PERCENTAGE) exceeds map.len().
        evict_oldest_batch(&map, 1000, |e| e.fetched_at);
        assert!(map.is_empty());
    }

    #[test]
    fn no_op_on_empty_map() {
        let map: DashMap<usize, Entry> = DashMap::new();
        evict_oldest_batch(&map, 1000, |e| e.fetched_at);
        assert!(map.is_empty());
    }

    #[test]
    fn removes_one_when_max_entries_equals_percentage() {
        let map = map_with_ages(CACHE_EVICTION_PERCENTAGE);
        evict_oldest_batch(&map, CACHE_EVICTION_PERCENTAGE, |e| e.fetched_at);
        assert_eq!(map.len(), CACHE_EVICTION_PERCENTAGE - 1);
        assert!(!map.contains_key(&0));
    }

    /// Exercises the `K: Ord` bound's only reason to exist: breaking a tie between two entries
    /// with the *same* `fetched_at`. Uses `String` keys (not `usize`) so key order cannot be
    /// mistaken for insertion order.
    #[test]
    fn ties_on_fetched_at_break_by_key_order() {
        let map: DashMap<String, Entry> = DashMap::new();
        let same_instant = Instant::now();
        map.insert(
            "b".to_string(),
            Entry {
                fetched_at: same_instant,
            },
        );
        map.insert(
            "a".to_string(),
            Entry {
                fetched_at: same_instant,
            },
        );

        evict_oldest_batch(&map, CACHE_EVICTION_PERCENTAGE, |e| e.fetched_at);

        assert!(
            !map.contains_key("a"),
            "the lexicographically smaller key breaks the tie"
        );
        assert!(map.contains_key("b"));
    }

    #[test]
    fn evict_arbitrary_if_full_removes_exactly_one_at_capacity() {
        let map: DashMap<u32, &str> = DashMap::new();
        map.insert(1, "a");
        map.insert(2, "b");
        evict_arbitrary_if_full(&map, 2);
        assert_eq!(map.len(), 1);
    }

    #[test]
    fn evict_arbitrary_if_full_below_capacity_is_a_no_op() {
        let map: DashMap<u32, &str> = DashMap::new();
        map.insert(1, "a");
        evict_arbitrary_if_full(&map, 2);
        assert_eq!(map.len(), 1);
    }

    #[test]
    fn evict_arbitrary_if_full_empty_map_is_a_no_op() {
        let map: DashMap<u32, &str> = DashMap::new();
        evict_arbitrary_if_full(&map, 2);
        assert!(map.is_empty());
    }

    #[test]
    fn evict_expired_then_clear_all_drops_only_expired_entries() {
        let map: DashMap<&str, Instant> = DashMap::new();
        map.insert(
            "expired",
            Instant::now().checked_sub(Duration::from_secs(61)).unwrap(),
        );
        map.insert("fresh", Instant::now());

        evict_expired_then_clear_all(&map, 256, |v| *v, Duration::from_secs(60));

        assert!(!map.contains_key("expired"));
        assert!(map.contains_key("fresh"));
    }

    #[test]
    fn evict_expired_then_clear_all_clears_all_when_still_at_capacity_after_ttl_sweep() {
        let map: DashMap<usize, Instant> = DashMap::new();
        let max_entries = 8;
        for i in 0..max_entries {
            map.insert(i, Instant::now());
        }

        evict_expired_then_clear_all(&map, max_entries, |v| *v, Duration::from_secs(60));

        assert!(map.is_empty());
    }
}