| 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | |
| 3 | //! Local snapshot-cache eviction, sans-IO. |
| 4 | //! |
| 5 | //! Idle eviction preserves each cell's SQLite file so a same-node wake is |
| 6 | //! a rename instead of a remote restore, which saves tens of serial storage |
| 7 | //! round trips per wake. The cost is that a node accumulates one file per |
| 8 | //! cell it has ever hosted, which is unbounded while the durable population |
| 9 | //! is unbounded. |
| 10 | //! |
| 11 | //! The bound can be crude because the cache is PURE OPTIMIZATION: every |
| 12 | //! entry is a copy of state the bucket already holds, so deleting any entry |
| 13 | //! is always correct and costs only a future restore. That makes |
| 14 | //! least-recently-used the whole policy — no fencing, no durability, no |
| 15 | //! ordering constraint to respect. |
| 16 | |
| 17 | /// One cached file, as the executor observed it. |
| 18 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 19 | pub struct CacheEntry { |
| 20 | /// Monotonic-ish recency; larger is more recently used. The executor |
| 21 | /// supplies mtime, which a rename-in refreshes. |
| 22 | pub last_used_ms: i64, |
| 23 | pub bytes: u64, |
| 24 | } |
| 25 | |
| 26 | /// Which entries to delete so the cache fits `max_bytes`, oldest first. |
| 27 | /// Returns indices into `entries`. An empty result means the cache already |
| 28 | /// fits — the common case, and it must never do I/O-worthy work then. |
| 29 | pub fn plan_eviction(entries: &[CacheEntry], max_bytes: u64) -> Vec<usize> { |
| 30 | let total: u64 = entries.iter().map(|entry| entry.bytes).sum(); |
| 31 | if total <= max_bytes { |
| 32 | return Vec::new(); |
| 33 | } |
| 34 | // Most recently used first; evict from the tail until it fits. |
| 35 | let mut order: Vec<usize> = (0..entries.len()).collect(); |
| 36 | order.sort_by_key(|&i| std::cmp::Reverse((entries[i].last_used_ms, i))); |
| 37 | let mut kept = 0_u64; |
| 38 | let mut evict = Vec::new(); |
| 39 | for i in order { |
| 40 | let next = kept.saturating_add(entries[i].bytes); |
| 41 | if next <= max_bytes { |
| 42 | kept = next; |
| 43 | } else { |
| 44 | evict.push(i); |
| 45 | } |
| 46 | } |
| 47 | evict.sort_unstable(); |
| 48 | evict |
| 49 | } |