Skip to main content

euv_core/app/prewarm/
impl.rs

1use super::*;
2
3/// Constructor helpers for `PrewarmContextKey`.
4impl PrewarmContextKey {
5    /// Creates a normalized `PrewarmContextKey` binding `resource_version`, `theme_mode`, and display `dpr`.
6    ///
7    /// # Arguments
8    ///
9    /// - `u64` - Application or bundle resource version.
10    /// - `ThemeMode` - Active light or dark theme mode.
11    /// - `f32` - Active display scale factor.
12    ///
13    /// # Returns
14    ///
15    /// - `Self` - Normalized context key.
16    #[must_use]
17    pub fn from_context(resource_version: u64, theme_mode: ThemeMode, dpr: f32) -> Self {
18        Self {
19            resource_version,
20            theme_mode,
21            dpr_bits: dpr.max(0.5).to_bits(),
22        }
23    }
24}
25
26/// Builder helpers for `RoutePrewarmTask`.
27impl RoutePrewarmTask {
28    /// Creates a new bounded route pre-warm task descriptor.
29    ///
30    /// # Arguments
31    ///
32    /// - `String` - Target route key.
33    /// - `PrewarmWorkKind` - Pre-warm phase kind.
34    /// - `PrewarmContextKey` - Active context signature `(version, theme, DPR)`.
35    /// - `usize` - Estimated memory/upload footprint in bytes.
36    /// - `u64` - Estimated execution cost in microseconds.
37    ///
38    /// # Returns
39    ///
40    /// - `Self` - Ready pre-warm task descriptor with default priority `1`.
41    #[must_use]
42    pub fn new(
43        route_key: String,
44        kind: PrewarmWorkKind,
45        context: PrewarmContextKey,
46        estimated_bytes: usize,
47        estimated_us: u64,
48    ) -> Self {
49        Self {
50            route_key,
51            kind,
52            context,
53            estimated_bytes,
54            estimated_us: estimated_us.max(1),
55            priority: 1,
56        }
57    }
58
59    /// Sets task execution priority (`0` = highest).
60    ///
61    /// # Arguments
62    ///
63    /// - `Self` - Base task descriptor.
64    /// - `u8` - Priority level (`0` executes first).
65    ///
66    /// # Returns
67    ///
68    /// - `Self` - Updated task descriptor.
69    #[must_use]
70    pub fn with_priority(mut self, priority: u8) -> Self {
71        self.set_priority(priority);
72        self
73    }
74}
75
76/// Default bounded `RoutePrewarmer` initialized with conservative memory and per-frame slice caps.
77impl Default for RoutePrewarmer {
78    /// Creates a default `RoutePrewarmer` with 32 max tasks, 8 MiB memory cap, and 1 MiB/frame upload cap.
79    ///
80    /// # Returns
81    ///
82    /// - `Self` - Ready route pre-warmer.
83    fn default() -> Self {
84        Self::with_limits(
85            PREWARM_DEFAULT_MAX_TASKS,
86            PREWARM_DEFAULT_MAX_MEMORY_BYTES,
87            PREWARM_DEFAULT_MAX_UPLOAD_PER_FRAME,
88        )
89    }
90}
91
92/// Bounded queueing, budgeted slicing, context invalidation, and cancellation for `RoutePrewarmer`.
93impl RoutePrewarmer {
94    /// Creates a `RoutePrewarmer` with explicit queue, memory, and per-frame upload byte caps.
95    ///
96    /// # Arguments
97    ///
98    /// - `usize` - Maximum pending tasks (`>= 1`).
99    /// - `usize` - Maximum aggregate artifact memory in bytes (`>= 4096`).
100    /// - `usize` - Maximum bytes uploaded/processed per budgeted frame step (`>= 4096`).
101    ///
102    /// # Returns
103    ///
104    /// - `Self` - Configured route pre-warmer.
105    #[must_use]
106    pub fn with_limits(
107        max_pending_tasks: usize,
108        max_memory_bytes: usize,
109        max_upload_bytes_per_frame: usize,
110    ) -> Self {
111        Self {
112            max_pending_tasks: max_pending_tasks.max(1),
113            max_memory_bytes: max_memory_bytes.max(4096),
114            max_upload_bytes_per_frame: max_upload_bytes_per_frame.max(4096),
115            default_step_budget_us: PREWARM_DEFAULT_STEP_BUDGET_US,
116            active_context: PrewarmContextKey::from_context(1, ThemeMode::Light, 1.0),
117            enabled: true,
118            pending: Vec::new(),
119            ready: Vec::new(),
120            resident_bytes: 0,
121            enqueued_count: 0,
122            executed_tasks: 0,
123            cancelled_tasks: 0,
124            invalidated_artifacts: 0,
125            budget_deferrals: 0,
126        }
127    }
128
129    /// Enqueues `task` if pre-warming is enabled, context matches, queue has capacity, and no duplicate `(route, kind)` exists.
130    ///
131    /// # Arguments
132    ///
133    /// - `&Self` - Mutable route pre-warmer.
134    /// - `RoutePrewarmTask` - Candidate pre-warm task.
135    ///
136    /// # Returns
137    ///
138    /// - `bool` - `true` if accepted into the bounded queue.
139    pub fn enqueue(&mut self, task: RoutePrewarmTask) -> bool {
140        if !self.get_enabled() {
141            return false;
142        }
143        if task.get_context() != self.get_active_context() {
144            let Self {
145                cancelled_tasks, ..
146            } = self;
147            *cancelled_tasks = cancelled_tasks.saturating_add(1);
148            return false;
149        }
150        if self.get_pending().len() >= self.get_max_pending_tasks() {
151            return false;
152        }
153        let duplicate: bool = self
154            .get_pending()
155            .iter()
156            .any(|existing: &RoutePrewarmTask| {
157                existing.get_route_key() == task.get_route_key()
158                    && existing.get_kind() == task.get_kind()
159            });
160        if duplicate {
161            return false;
162        }
163        let Self {
164            pending,
165            enqueued_count,
166            ..
167        } = self;
168        pending.push(task);
169        pending.sort_by_key(|t: &RoutePrewarmTask| t.get_priority());
170        *enqueued_count = enqueued_count.saturating_add(1);
171        true
172    }
173
174    /// Invalidates all pending tasks and ready artifacts when `(resource_version, theme_mode, dpr)` changes.
175    ///
176    /// # Arguments
177    ///
178    /// - `&Self` - Mutable route pre-warmer.
179    /// - `PrewarmContextKey` - Newly active `(version, theme, DPR)` context key.
180    ///
181    /// # Returns
182    ///
183    /// - `usize` - Total stale pending tasks plus invalidated ready artifacts discarded.
184    pub fn invalidate_context(&mut self, next_context: PrewarmContextKey) -> usize {
185        if self.get_active_context() == next_context {
186            return 0;
187        }
188        let Self {
189            active_context,
190            pending,
191            ready,
192            resident_bytes,
193            cancelled_tasks,
194            invalidated_artifacts,
195            ..
196        } = self;
197        *active_context = next_context;
198        let dropped_pending: usize = pending.len();
199        let dropped_ready: usize = ready.len();
200        pending.clear();
201        ready.clear();
202        *resident_bytes = 0;
203        *cancelled_tasks = cancelled_tasks.saturating_add(dropped_pending as u64);
204        *invalidated_artifacts = invalidated_artifacts.saturating_add(dropped_ready as u64);
205        dropped_pending.saturating_add(dropped_ready)
206    }
207
208    /// Cancels all pending tasks and discards ready artifacts targeting `route_key`.
209    ///
210    /// # Arguments
211    ///
212    /// - `&Self` - Mutable route pre-warmer.
213    /// - `&str` - Route key to cancel.
214    ///
215    /// # Returns
216    ///
217    /// - `usize` - Total cancelled pending tasks and discarded artifacts for `route_key`.
218    pub fn cancel_route(&mut self, route_key: &str) -> usize {
219        let Self {
220            pending,
221            ready,
222            resident_bytes,
223            cancelled_tasks,
224            invalidated_artifacts,
225            ..
226        } = self;
227        let before_pending: usize = pending.len();
228        pending.retain(|t: &RoutePrewarmTask| t.get_route_key().as_str() != route_key);
229        let removed_pending: usize = before_pending.saturating_sub(pending.len());
230        let mut removed_ready: usize = 0;
231        let mut freed_bytes: usize = 0;
232        ready.retain(|art: &PrewarmedRouteArtifact| {
233            if art.get_route_key().as_str() == route_key {
234                removed_ready += 1;
235                freed_bytes = freed_bytes.saturating_add(art.get_resident_bytes());
236                false
237            } else {
238                true
239            }
240        });
241        *resident_bytes = resident_bytes.saturating_sub(freed_bytes);
242        *cancelled_tasks = cancelled_tasks.saturating_add(removed_pending as u64);
243        *invalidated_artifacts = invalidated_artifacts.saturating_add(removed_ready as u64);
244        removed_pending.saturating_add(removed_ready)
245    }
246
247    /// Immediately cancels every pending pre-warm task and drops all ready speculative artifacts (e.g. under memory pressure).
248    ///
249    /// # Arguments
250    ///
251    /// - `&Self` - Mutable route pre-warmer.
252    ///
253    /// # Returns
254    ///
255    /// - `usize` - Total cancelled tasks and evicted artifacts.
256    pub fn cancel_all(&mut self) -> usize {
257        let Self {
258            pending,
259            ready,
260            resident_bytes,
261            cancelled_tasks,
262            invalidated_artifacts,
263            ..
264        } = self;
265        let p_len: usize = pending.len();
266        let r_len: usize = ready.len();
267        pending.clear();
268        ready.clear();
269        *resident_bytes = 0;
270        *cancelled_tasks = cancelled_tasks.saturating_add(p_len as u64);
271        *invalidated_artifacts = invalidated_artifacts.saturating_add(r_len as u64);
272        p_len.saturating_add(r_len)
273    }
274
275    /// Executes queued pre-warm tasks strictly within `budget_us`, per-frame upload caps, and memory limits.
276    ///
277    /// # Arguments
278    ///
279    /// - `&Self` - Mutable route pre-warmer.
280    /// - `PrewarmContextKey` - Currently active `(version, theme, DPR)` context.
281    /// - `u64` - Remaining microsecond budget available on this frame (`0` uses `default_step_budget_us`).
282    ///
283    /// # Returns
284    ///
285    /// - `usize` - Number of tasks completed during this frame slice.
286    pub fn step_budgeted(&mut self, active_context: PrewarmContextKey, budget_us: u64) -> usize {
287        let _: usize = self.invalidate_context(active_context);
288        if !self.get_enabled() || self.get_pending().is_empty() {
289            return 0;
290        }
291        let max_us: u64 = if budget_us == 0 {
292            self.get_default_step_budget_us()
293        } else {
294            budget_us
295        };
296        let max_upload: usize = self.get_max_upload_bytes_per_frame();
297        let max_mem: usize = self.get_max_memory_bytes();
298        let mut spent_us: u64 = 0;
299        let mut spent_bytes: usize = 0;
300        let mut completed: usize = 0;
301        while !self.get_pending().is_empty() {
302            let next_us: u64 = self.get_pending()[0].get_estimated_us();
303            let next_bytes: usize = self.get_pending()[0].get_estimated_bytes();
304            let over_time: bool = spent_us.saturating_add(next_us) > max_us;
305            let over_upload: bool = spent_bytes.saturating_add(next_bytes) > max_upload;
306            if completed > 0 && (over_time || over_upload) {
307                let Self {
308                    budget_deferrals, ..
309                } = self;
310                *budget_deferrals = budget_deferrals.saturating_add(1);
311                break;
312            }
313            if over_time && next_us > max_us {
314                let Self {
315                    budget_deferrals, ..
316                } = self;
317                *budget_deferrals = budget_deferrals.saturating_add(1);
318                break;
319            }
320            let task: RoutePrewarmTask = self.get_mut_pending().remove(0);
321            if task.get_context() != active_context {
322                let Self {
323                    cancelled_tasks, ..
324                } = self;
325                *cancelled_tasks = cancelled_tasks.saturating_add(1);
326                continue;
327            }
328            let task_bytes: usize = task.get_estimated_bytes();
329            let Self {
330                ready,
331                resident_bytes,
332                executed_tasks,
333                invalidated_artifacts,
334                ..
335            } = self;
336            while !ready.is_empty() && resident_bytes.saturating_add(task_bytes) > max_mem {
337                let evicted: PrewarmedRouteArtifact = ready.remove(0);
338                *resident_bytes = resident_bytes.saturating_sub(evicted.get_resident_bytes());
339                *invalidated_artifacts = invalidated_artifacts.saturating_add(1);
340            }
341            let bit: u8 = 1_u8 << (task.get_kind() as u8);
342            if let Some(existing) = ready.iter_mut().find(|art: &&mut PrewarmedRouteArtifact| {
343                art.get_route_key() == task.get_route_key()
344            }) {
345                existing.set_completed_work_mask(existing.get_completed_work_mask() | bit);
346                existing
347                    .set_resident_bytes(existing.get_resident_bytes().saturating_add(task_bytes));
348                existing.set_prepared_items(existing.get_prepared_items().saturating_add(1));
349            } else {
350                ready.push(PrewarmedRouteArtifact {
351                    route_key: task.get_route_key().clone(),
352                    context: active_context,
353                    completed_work_mask: bit,
354                    resident_bytes: task_bytes,
355                    prepared_items: 1,
356                });
357            }
358            *resident_bytes = resident_bytes.saturating_add(task_bytes);
359            *executed_tasks = executed_tasks.saturating_add(1);
360            spent_us = spent_us.saturating_add(next_us);
361            spent_bytes = spent_bytes.saturating_add(task_bytes);
362            completed += 1;
363        }
364        completed
365    }
366
367    /// Consumes and returns a ready pre-warmed artifact for `route_key` ONLY when its `(version, theme, DPR)` context matches `active_context`.
368    ///
369    /// # Arguments
370    ///
371    /// - `&Self` - Mutable route pre-warmer.
372    /// - `&str` - Route key being entered.
373    /// - `PrewarmContextKey` - Currently active `(version, theme, DPR)` context.
374    ///
375    /// # Returns
376    ///
377    /// - `Option<PrewarmedRouteArtifact>` - Valid artifact if matched, or `None` if absent or stale.
378    pub fn take_ready_artifact(
379        &mut self,
380        route_key: &str,
381        active_context: PrewarmContextKey,
382    ) -> Option<PrewarmedRouteArtifact> {
383        let Self {
384            ready,
385            resident_bytes,
386            invalidated_artifacts,
387            ..
388        } = self;
389        let idx: usize = ready
390            .iter()
391            .position(|art: &PrewarmedRouteArtifact| art.get_route_key().as_str() == route_key)?;
392        let artifact: PrewarmedRouteArtifact = ready.remove(idx);
393        *resident_bytes = resident_bytes.saturating_sub(artifact.get_resident_bytes());
394        if artifact.get_context() != active_context {
395            *invalidated_artifacts = invalidated_artifacts.saturating_add(1);
396            return None;
397        }
398        Some(artifact)
399    }
400}