capsule_sdk/cache_budget.rs
1//! The client cache budget driven by the connection class (SSoT: design/filesystem/client §
2//! Automatic cache management, and design/networking § Connection Classes).
3//!
4//! Three pieces, each with one job:
5//!
6//! - [`ConnectionClassSource`] — the **port** a client samples its current [`ConnectionClass`]
7//! through. [`InMemoryConnectionClass`] is the deterministic adapter tests (and any caller that
8//! learns the class out of band, such as a mobile shell pushing OS callbacks) set by hand;
9//! [`DesktopConnectionClass`] is the desktop adapter, which classifies whatever [`PathSignals`]
10//! its probe can read and reports `unmetered` when it can tell nothing.
11//! - [`plan_for`] — the **pure policy**: a class and the user's base budget in, a [`CachePlan`]
12//! (the retention byte budget plus whether bulk transfers defer) out.
13//! - [`CacheBudget`] — the **orchestration** that samples the port, re-plans when the class
14//! changes mid-session, and hands the planned budget to the eviction sweep
15//! ([`capsule_library::library::cache_sweep`]). The sweep is passed in as a closure so this module
16//! names no storage type; the sweep alone decides what is evictable, so pinned representations
17//! and device-owned originals survive every re-plan.
18
19use std::sync::Mutex;
20
21use capsule_library::import::UploadPolicy;
22use capsule_library::library::EvictionReport;
23use tracing::{debug, info, instrument};
24
25use crate::net::{ConnectionClass, PathSignals};
26
27/// The default base cache budget, 2 GiB: the reclaimable bytes an unmetered client retains
28/// before the sweep evicts. The user setting overrides it; other classes scale it through
29/// [`ConnectionClass::cache_retention_budget`].
30pub const DEFAULT_BASE_CACHE_BUDGET: u64 = 2 * 1024 * 1024 * 1024;
31
32/// The port a client samples its current connection class through.
33pub trait ConnectionClassSource: Send + Sync {
34 /// The class of the link right now.
35 fn current(&self) -> ConnectionClass;
36}
37
38/// A deterministic, settable class source. Tests drive class changes through it; a platform
39/// shell that is told the class by OS callbacks can push them through it as well.
40#[derive(Debug)]
41pub struct InMemoryConnectionClass {
42 class: Mutex<ConnectionClass>,
43}
44
45impl InMemoryConnectionClass {
46 /// A source that reports `class` until [`set`](Self::set) changes it.
47 #[must_use]
48 pub fn new(class: ConnectionClass) -> Self {
49 Self {
50 class: Mutex::new(class),
51 }
52 }
53
54 /// Change the reported class.
55 pub fn set(&self, class: ConnectionClass) {
56 *self
57 .class
58 .lock()
59 .unwrap_or_else(std::sync::PoisonError::into_inner) = class;
60 }
61}
62
63impl ConnectionClassSource for InMemoryConnectionClass {
64 fn current(&self) -> ConnectionClass {
65 *self
66 .class
67 .lock()
68 .unwrap_or_else(std::sync::PoisonError::into_inner)
69 }
70}
71
72/// Reads the OS path signals on desktop, or `None` when the OS exposes nothing usable.
73pub type PathProbe = Box<dyn Fn() -> Option<PathSignals> + Send + Sync>;
74
75/// The desktop class source. Desktop operating systems expose no portable metered or data-saver
76/// signal, so the default probe reads nothing and the source reports
77/// [`ConnectionClass::Unmetered`]: a wired or Wi-Fi desktop is the networking table's
78/// "OS reports not expensive / not metered" case. A platform that can read real signals installs
79/// a probe with [`with_probe`](Self::with_probe), and whatever it reports is classified by
80/// [`ConnectionClass::from_signals`].
81pub struct DesktopConnectionClass {
82 probe: PathProbe,
83}
84
85impl DesktopConnectionClass {
86 /// The default desktop source: no OS probe, so always unmetered.
87 #[must_use]
88 pub fn new() -> Self {
89 Self {
90 probe: Box::new(|| None),
91 }
92 }
93
94 /// A desktop source that classifies what `probe` reads, falling back to unmetered whenever it
95 /// returns `None`.
96 #[must_use]
97 pub fn with_probe(probe: PathProbe) -> Self {
98 Self { probe }
99 }
100}
101
102impl Default for DesktopConnectionClass {
103 fn default() -> Self {
104 Self::new()
105 }
106}
107
108impl std::fmt::Debug for DesktopConnectionClass {
109 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
110 f.debug_struct("DesktopConnectionClass")
111 .finish_non_exhaustive()
112 }
113}
114
115impl ConnectionClassSource for DesktopConnectionClass {
116 fn current(&self) -> ConnectionClass {
117 (self.probe)().map_or(ConnectionClass::Unmetered, ConnectionClass::from_signals)
118 }
119}
120
121/// What the client does with its cache and bulk transfers on one connection class.
122#[derive(Debug, Clone, Copy, PartialEq, Eq)]
123pub struct CachePlan {
124 /// The class the plan was made for.
125 pub class: ConnectionClass,
126 /// The reclaimable bytes retained before the sweep evicts.
127 pub budget_bytes: u64,
128 /// Whether bulk transfers (prefetch, original fetches, above-index uploads) wait for an
129 /// unmetered link. Everything but `unmetered` defers, as the networking table states for
130 /// `metered` and as the byte-conscious `constrained`, unreliable `adverse` and path-less
131 /// `offline` classes require.
132 pub defer_bulk: bool,
133}
134
135impl CachePlan {
136 /// The budget in the signed width the sweep takes, saturating at `i64::MAX`.
137 #[must_use]
138 pub fn sweep_budget(&self) -> i64 {
139 i64::try_from(self.budget_bytes).unwrap_or(i64::MAX)
140 }
141
142 /// The upload policy a push runs under on this plan, given the one the user `requested`.
143 ///
144 /// A plan that defers bulk transfers demotes [`UploadPolicy::Full`] to
145 /// [`UploadPolicy::Staged`], so the bulk tiers (preview and original) wait for an unmetered
146 /// link through the staged scheduler's tier gate while the index tier still publishes the
147 /// asset. A plan that permits bulk work keeps whatever was requested.
148 #[must_use]
149 pub fn upload_policy(&self, requested: UploadPolicy) -> UploadPolicy {
150 if self.defer_bulk {
151 UploadPolicy::Staged
152 } else {
153 requested
154 }
155 }
156}
157
158/// The cache plan for `class` from the user's `base_budget_bytes`. Pure.
159#[must_use]
160pub fn plan_for(class: ConnectionClass, base_budget_bytes: u64) -> CachePlan {
161 CachePlan {
162 class,
163 budget_bytes: class.cache_retention_budget(base_budget_bytes),
164 defer_bulk: !class.is_non_metered(),
165 }
166}
167
168/// What one [`CacheBudget::sweep`] did.
169#[derive(Debug, PartialEq)]
170pub struct CacheSweepOutcome {
171 /// The plan the sweep ran under.
172 pub plan: CachePlan,
173 /// Whether the class changed since the previous sweep, forcing a re-plan.
174 pub replanned: bool,
175 /// What the sweep reclaimed.
176 pub report: EvictionReport,
177}
178
179/// Keeps the cache within the budget the current connection class allows.
180pub struct CacheBudget<S: ConnectionClassSource> {
181 source: S,
182 base_budget_bytes: u64,
183 plan: Option<CachePlan>,
184}
185
186impl<S: ConnectionClassSource> CacheBudget<S> {
187 /// A budget over `source` with the user's base budget.
188 #[must_use]
189 pub fn new(source: S, base_budget_bytes: u64) -> Self {
190 Self {
191 source,
192 base_budget_bytes,
193 plan: None,
194 }
195 }
196
197 /// The class source this budget samples.
198 pub fn source(&self) -> &S {
199 &self.source
200 }
201
202 /// Sample the class and return the current plan, re-planning when the class changed. The
203 /// boolean is `true` on a re-plan (including the first one).
204 #[instrument(level = "debug", skip(self), fields(base = self.base_budget_bytes))]
205 pub fn current_plan(&mut self) -> (CachePlan, bool) {
206 let class = self.source.current();
207 match self.plan {
208 Some(plan) if plan.class == class => (plan, false),
209 previous => {
210 let plan = plan_for(class, self.base_budget_bytes);
211 info!(
212 from = ?previous.map(|p| p.class),
213 to = ?class,
214 budget_bytes = plan.budget_bytes,
215 defer_bulk = plan.defer_bulk,
216 "cache budget re-planned for connection class"
217 );
218 self.plan = Some(plan);
219 (plan, true)
220 }
221 }
222 }
223
224 /// Whether bulk transfers should wait right now.
225 pub fn defer_bulk(&mut self) -> bool {
226 self.current_plan().0.defer_bulk
227 }
228
229 /// Re-plan if the class changed, then run `sweep` (normally
230 /// `|budget| capsule_library::library::cache_sweep(&db, budget)`) under the planned budget.
231 ///
232 /// # Errors
233 ///
234 /// Whatever the sweep returns; the plan is kept either way.
235 #[instrument(level = "debug", skip(self, sweep))]
236 pub fn sweep<E>(
237 &mut self,
238 sweep: impl FnOnce(i64) -> Result<EvictionReport, E>,
239 ) -> Result<CacheSweepOutcome, E> {
240 let (plan, replanned) = self.current_plan();
241 let report = sweep(plan.sweep_budget())?;
242 debug!(
243 class = ?plan.class,
244 budget_bytes = plan.budget_bytes,
245 evicted = report.evicted.len(),
246 bytes_reclaimed = report.bytes_reclaimed,
247 "cache sweep finished"
248 );
249 Ok(CacheSweepOutcome {
250 plan,
251 replanned,
252 report,
253 })
254 }
255}
256
257#[cfg(test)]
258mod tests;