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
use super::*;
/// Constructor helpers for `PrewarmContextKey`.
impl PrewarmContextKey {
/// Creates a normalized `PrewarmContextKey` binding `resource_version`, `theme_mode`, and display `dpr`.
///
/// # Arguments
///
/// - `u64` - Application or bundle resource version.
/// - `ThemeMode` - Active light or dark theme mode.
/// - `f32` - Active display scale factor.
///
/// # Returns
///
/// - `Self` - Normalized context key.
#[must_use]
pub fn from_context(resource_version: u64, theme_mode: ThemeMode, dpr: f32) -> Self {
Self {
resource_version,
theme_mode,
dpr_bits: dpr.max(0.5).to_bits(),
}
}
}
/// Builder helpers for `RoutePrewarmTask`.
impl RoutePrewarmTask {
/// Creates a new bounded route pre-warm task descriptor.
///
/// # Arguments
///
/// - `String` - Target route key.
/// - `PrewarmWorkKind` - Pre-warm phase kind.
/// - `PrewarmContextKey` - Active context signature `(version, theme, DPR)`.
/// - `usize` - Estimated memory/upload footprint in bytes.
/// - `u64` - Estimated execution cost in microseconds.
///
/// # Returns
///
/// - `Self` - Ready pre-warm task descriptor with default priority `1`.
#[must_use]
pub fn new(
route_key: String,
kind: PrewarmWorkKind,
context: PrewarmContextKey,
estimated_bytes: usize,
estimated_us: u64,
) -> Self {
Self {
route_key,
kind,
context,
estimated_bytes,
estimated_us: estimated_us.max(1),
priority: 1,
}
}
/// Sets task execution priority (`0` = highest).
///
/// # Arguments
///
/// - `Self` - Base task descriptor.
/// - `u8` - Priority level (`0` executes first).
///
/// # Returns
///
/// - `Self` - Updated task descriptor.
#[must_use]
pub fn with_priority(mut self, priority: u8) -> Self {
self.set_priority(priority);
self
}
}
/// Default bounded `RoutePrewarmer` initialized with conservative memory and per-frame slice caps.
impl Default for RoutePrewarmer {
/// Creates a default `RoutePrewarmer` with 32 max tasks, 8 MiB memory cap, and 1 MiB/frame upload cap.
///
/// # Returns
///
/// - `Self` - Ready route pre-warmer.
fn default() -> Self {
Self::with_limits(
PREWARM_DEFAULT_MAX_TASKS,
PREWARM_DEFAULT_MAX_MEMORY_BYTES,
PREWARM_DEFAULT_MAX_UPLOAD_PER_FRAME,
)
}
}
/// Bounded queueing, budgeted slicing, context invalidation, and cancellation for `RoutePrewarmer`.
impl RoutePrewarmer {
/// Creates a `RoutePrewarmer` with explicit queue, memory, and per-frame upload byte caps.
///
/// # Arguments
///
/// - `usize` - Maximum pending tasks (`>= 1`).
/// - `usize` - Maximum aggregate artifact memory in bytes (`>= 4096`).
/// - `usize` - Maximum bytes uploaded/processed per budgeted frame step (`>= 4096`).
///
/// # Returns
///
/// - `Self` - Configured route pre-warmer.
#[must_use]
pub fn with_limits(
max_pending_tasks: usize,
max_memory_bytes: usize,
max_upload_bytes_per_frame: usize,
) -> Self {
Self {
max_pending_tasks: max_pending_tasks.max(1),
max_memory_bytes: max_memory_bytes.max(4096),
max_upload_bytes_per_frame: max_upload_bytes_per_frame.max(4096),
default_step_budget_us: PREWARM_DEFAULT_STEP_BUDGET_US,
active_context: PrewarmContextKey::from_context(1, ThemeMode::Light, 1.0),
enabled: true,
pending: Vec::new(),
ready: Vec::new(),
resident_bytes: 0,
enqueued_count: 0,
executed_tasks: 0,
cancelled_tasks: 0,
invalidated_artifacts: 0,
budget_deferrals: 0,
}
}
/// Enqueues `task` if pre-warming is enabled, context matches, queue has capacity, and no duplicate `(route, kind)` exists.
///
/// # Arguments
///
/// - `&Self` - Mutable route pre-warmer.
/// - `RoutePrewarmTask` - Candidate pre-warm task.
///
/// # Returns
///
/// - `bool` - `true` if accepted into the bounded queue.
pub fn enqueue(&mut self, task: RoutePrewarmTask) -> bool {
if !self.get_enabled() {
return false;
}
if task.get_context() != self.get_active_context() {
let Self {
cancelled_tasks, ..
} = self;
*cancelled_tasks = cancelled_tasks.saturating_add(1);
return false;
}
if self.get_pending().len() >= self.get_max_pending_tasks() {
return false;
}
let duplicate: bool = self
.get_pending()
.iter()
.any(|existing: &RoutePrewarmTask| {
existing.get_route_key() == task.get_route_key()
&& existing.get_kind() == task.get_kind()
});
if duplicate {
return false;
}
let Self {
pending,
enqueued_count,
..
} = self;
pending.push(task);
pending.sort_by_key(|t: &RoutePrewarmTask| t.get_priority());
*enqueued_count = enqueued_count.saturating_add(1);
true
}
/// Invalidates all pending tasks and ready artifacts when `(resource_version, theme_mode, dpr)` changes.
///
/// # Arguments
///
/// - `&Self` - Mutable route pre-warmer.
/// - `PrewarmContextKey` - Newly active `(version, theme, DPR)` context key.
///
/// # Returns
///
/// - `usize` - Total stale pending tasks plus invalidated ready artifacts discarded.
pub fn invalidate_context(&mut self, next_context: PrewarmContextKey) -> usize {
if self.get_active_context() == next_context {
return 0;
}
let Self {
active_context,
pending,
ready,
resident_bytes,
cancelled_tasks,
invalidated_artifacts,
..
} = self;
*active_context = next_context;
let dropped_pending: usize = pending.len();
let dropped_ready: usize = ready.len();
pending.clear();
ready.clear();
*resident_bytes = 0;
*cancelled_tasks = cancelled_tasks.saturating_add(dropped_pending as u64);
*invalidated_artifacts = invalidated_artifacts.saturating_add(dropped_ready as u64);
dropped_pending.saturating_add(dropped_ready)
}
/// Cancels all pending tasks and discards ready artifacts targeting `route_key`.
///
/// # Arguments
///
/// - `&Self` - Mutable route pre-warmer.
/// - `&str` - Route key to cancel.
///
/// # Returns
///
/// - `usize` - Total cancelled pending tasks and discarded artifacts for `route_key`.
pub fn cancel_route(&mut self, route_key: &str) -> usize {
let Self {
pending,
ready,
resident_bytes,
cancelled_tasks,
invalidated_artifacts,
..
} = self;
let before_pending: usize = pending.len();
pending.retain(|t: &RoutePrewarmTask| t.get_route_key().as_str() != route_key);
let removed_pending: usize = before_pending.saturating_sub(pending.len());
let mut removed_ready: usize = 0;
let mut freed_bytes: usize = 0;
ready.retain(|art: &PrewarmedRouteArtifact| {
if art.get_route_key().as_str() == route_key {
removed_ready += 1;
freed_bytes = freed_bytes.saturating_add(art.get_resident_bytes());
false
} else {
true
}
});
*resident_bytes = resident_bytes.saturating_sub(freed_bytes);
*cancelled_tasks = cancelled_tasks.saturating_add(removed_pending as u64);
*invalidated_artifacts = invalidated_artifacts.saturating_add(removed_ready as u64);
removed_pending.saturating_add(removed_ready)
}
/// Immediately cancels every pending pre-warm task and drops all ready speculative artifacts (e.g. under memory pressure).
///
/// # Arguments
///
/// - `&Self` - Mutable route pre-warmer.
///
/// # Returns
///
/// - `usize` - Total cancelled tasks and evicted artifacts.
pub fn cancel_all(&mut self) -> usize {
let Self {
pending,
ready,
resident_bytes,
cancelled_tasks,
invalidated_artifacts,
..
} = self;
let p_len: usize = pending.len();
let r_len: usize = ready.len();
pending.clear();
ready.clear();
*resident_bytes = 0;
*cancelled_tasks = cancelled_tasks.saturating_add(p_len as u64);
*invalidated_artifacts = invalidated_artifacts.saturating_add(r_len as u64);
p_len.saturating_add(r_len)
}
/// Executes queued pre-warm tasks strictly within `budget_us`, per-frame upload caps, and memory limits.
///
/// # Arguments
///
/// - `&Self` - Mutable route pre-warmer.
/// - `PrewarmContextKey` - Currently active `(version, theme, DPR)` context.
/// - `u64` - Remaining microsecond budget available on this frame (`0` uses `default_step_budget_us`).
///
/// # Returns
///
/// - `usize` - Number of tasks completed during this frame slice.
pub fn step_budgeted(&mut self, active_context: PrewarmContextKey, budget_us: u64) -> usize {
let _: usize = self.invalidate_context(active_context);
if !self.get_enabled() || self.get_pending().is_empty() {
return 0;
}
let max_us: u64 = if budget_us == 0 {
self.get_default_step_budget_us()
} else {
budget_us
};
let max_upload: usize = self.get_max_upload_bytes_per_frame();
let max_mem: usize = self.get_max_memory_bytes();
let mut spent_us: u64 = 0;
let mut spent_bytes: usize = 0;
let mut completed: usize = 0;
while !self.get_pending().is_empty() {
let next_us: u64 = self.get_pending()[0].get_estimated_us();
let next_bytes: usize = self.get_pending()[0].get_estimated_bytes();
let over_time: bool = spent_us.saturating_add(next_us) > max_us;
let over_upload: bool = spent_bytes.saturating_add(next_bytes) > max_upload;
if completed > 0 && (over_time || over_upload) {
let Self {
budget_deferrals, ..
} = self;
*budget_deferrals = budget_deferrals.saturating_add(1);
break;
}
if over_time && next_us > max_us {
let Self {
budget_deferrals, ..
} = self;
*budget_deferrals = budget_deferrals.saturating_add(1);
break;
}
let task: RoutePrewarmTask = self.get_mut_pending().remove(0);
if task.get_context() != active_context {
let Self {
cancelled_tasks, ..
} = self;
*cancelled_tasks = cancelled_tasks.saturating_add(1);
continue;
}
let task_bytes: usize = task.get_estimated_bytes();
let Self {
ready,
resident_bytes,
executed_tasks,
invalidated_artifacts,
..
} = self;
while !ready.is_empty() && resident_bytes.saturating_add(task_bytes) > max_mem {
let evicted: PrewarmedRouteArtifact = ready.remove(0);
*resident_bytes = resident_bytes.saturating_sub(evicted.get_resident_bytes());
*invalidated_artifacts = invalidated_artifacts.saturating_add(1);
}
let bit: u8 = 1_u8 << (task.get_kind() as u8);
if let Some(existing) = ready.iter_mut().find(|art: &&mut PrewarmedRouteArtifact| {
art.get_route_key() == task.get_route_key()
}) {
existing.set_completed_work_mask(existing.get_completed_work_mask() | bit);
existing
.set_resident_bytes(existing.get_resident_bytes().saturating_add(task_bytes));
existing.set_prepared_items(existing.get_prepared_items().saturating_add(1));
} else {
ready.push(PrewarmedRouteArtifact {
route_key: task.get_route_key().clone(),
context: active_context,
completed_work_mask: bit,
resident_bytes: task_bytes,
prepared_items: 1,
});
}
*resident_bytes = resident_bytes.saturating_add(task_bytes);
*executed_tasks = executed_tasks.saturating_add(1);
spent_us = spent_us.saturating_add(next_us);
spent_bytes = spent_bytes.saturating_add(task_bytes);
completed += 1;
}
completed
}
/// Consumes and returns a ready pre-warmed artifact for `route_key` ONLY when its `(version, theme, DPR)` context matches `active_context`.
///
/// # Arguments
///
/// - `&Self` - Mutable route pre-warmer.
/// - `&str` - Route key being entered.
/// - `PrewarmContextKey` - Currently active `(version, theme, DPR)` context.
///
/// # Returns
///
/// - `Option<PrewarmedRouteArtifact>` - Valid artifact if matched, or `None` if absent or stale.
pub fn take_ready_artifact(
&mut self,
route_key: &str,
active_context: PrewarmContextKey,
) -> Option<PrewarmedRouteArtifact> {
let Self {
ready,
resident_bytes,
invalidated_artifacts,
..
} = self;
let idx: usize = ready
.iter()
.position(|art: &PrewarmedRouteArtifact| art.get_route_key().as_str() == route_key)?;
let artifact: PrewarmedRouteArtifact = ready.remove(idx);
*resident_bytes = resident_bytes.saturating_sub(artifact.get_resident_bytes());
if artifact.get_context() != active_context {
*invalidated_artifacts = invalidated_artifacts.saturating_add(1);
return None;
}
Some(artifact)
}
}