Skip to main content

euv_core/scene/lifecycle/
impl.rs

1use super::*;
2
3/// No-op `Lifecycle` implementation allowing raw `NodeId` handles to participate seamlessly in `Component` APIs.
4impl Lifecycle for NodeId {}
5
6/// Zero-overhead `Component` implementation returning an already-mounted `NodeId` unchanged.
7impl Component for NodeId {
8    /// Returns this `NodeId` handle unchanged.
9    ///
10    /// # Arguments
11    ///
12    /// - `&Self` - Already-mounted scene node handle.
13    ///
14    /// # Returns
15    ///
16    /// - `NodeId` - Same scene node handle.
17    fn render(&self) -> NodeId {
18        *self
19    }
20
21    /// Returns this `NodeId` directly without heap allocation or duplicate lifecycle attachment.
22    ///
23    /// # Arguments
24    ///
25    /// - `Self` - Already-mounted scene node handle.
26    ///
27    /// # Returns
28    ///
29    /// - `NodeId` - Same scene node handle.
30    fn mount(self) -> NodeId {
31        self
32    }
33}
34
35/// Default bounded cold-page retention policy (`4` frozen pages, `32 MiB` retained ceiling).
36impl Default for PageBudgetPolicy {
37    /// Creates the default bounded cold-page retention policy.
38    ///
39    /// # Returns
40    ///
41    /// - `Self` - Default page budget policy.
42    fn default() -> Self {
43        Self {
44            max_frozen_pages: PAGE_DEFAULT_MAX_FROZEN,
45            max_retained_bytes: PAGE_DEFAULT_MAX_RETAINED_BYTES,
46            max_snapshot_bytes: PAGE_DEFAULT_MAX_SNAPSHOT_BYTES,
47        }
48    }
49}
50
51/// Builder helpers for versioned `PageSnapshot`.
52impl PageSnapshot {
53    /// Creates a schema-versioned `PageSnapshot` capturing scroll, focus, and optional unsaved draft state.
54    ///
55    /// # Arguments
56    ///
57    /// - `String` - Canonical route identifier.
58    /// - `u64` - Source page generation.
59    /// - `Point` - Saved primary scroll offset.
60    /// - `Option<String>` - Optional focused element key.
61    /// - `String` - Serialized draft payload (empty when no draft).
62    /// - `(bool, bool)` - Tuple `(has_unsaved_draft, draft_persisted)` tracking unsaved draft protection status.
63    /// - `u64` - Host state revision at capture time.
64    ///
65    /// # Returns
66    ///
67    /// - `Self` - Ready versioned snapshot.
68    #[must_use]
69    pub fn capture(
70        route_key: String,
71        generation: u64,
72        scroll_offset: Point,
73        focus_key: Option<String>,
74        draft_payload: String,
75        unsaved_flags: (bool, bool),
76        host_state_revision: u64,
77    ) -> Self {
78        let (has_unsaved_draft, draft_persisted): (bool, bool) = unsaved_flags;
79        let (has_focus_key, focus_str): (bool, String) = match focus_key {
80            Some(entry_index) if !entry_index.is_empty() => (true, entry_index),
81            _ => (false, String::new()),
82        };
83        let estimated_bytes: usize = 64_usize
84            .saturating_add(route_key.len())
85            .saturating_add(focus_str.len())
86            .saturating_add(draft_payload.len());
87        Self {
88            schema_version: PAGE_SNAPSHOT_SCHEMA_VERSION,
89            route_key,
90            generation,
91            scroll_offset,
92            focus_key: focus_str,
93            has_focus_key,
94            draft_payload,
95            has_unsaved_draft,
96            draft_persisted,
97            host_state_revision,
98            estimated_bytes,
99        }
100    }
101}
102
103/// Default empty `PageLifecycleController` initialized with `PageBudgetPolicy::default()`.
104impl Default for PageLifecycleController {
105    /// Creates a new `PageLifecycleController` with default cold-page budgets.
106    ///
107    /// # Returns
108    ///
109    /// - `Self` - Initialized page lifecycle controller.
110    fn default() -> Self {
111        Self::with_budget(PageBudgetPolicy::default())
112    }
113}
114
115/// Deterministic `Freeze`, `Resume`, `Evict`, `Destroy`, generation-guard, and boundary-event operations for `PageLifecycleController`.
116impl PageLifecycleController {
117    /// Creates a `PageLifecycleController` configured with explicit `budget` limits.
118    ///
119    /// # Arguments
120    ///
121    /// - `PageBudgetPolicy` - Cold-page count and retained-byte retention policy.
122    ///
123    /// # Returns
124    ///
125    /// - `Self` - Configured page lifecycle controller.
126    #[must_use]
127    pub fn with_budget(budget: PageBudgetPolicy) -> Self {
128        Self {
129            budget,
130            pages: HashMap::new(),
131            next_page_id: 1,
132            active_clock: 0,
133            host_revision: 1,
134            stale_callbacks_blocked: 0,
135            os_background_events: 0,
136            os_foreground_events: 0,
137            surface_lost_events: 0,
138            surface_recreated_events: 0,
139            total_destroyed_pages: 0,
140        }
141    }
142
143    /// Registers a newly active page or child sub-page and returns its initial `PageGenerationToken`.
144    ///
145    /// # Arguments
146    ///
147    /// - `&Self` - Mutable page lifecycle controller.
148    /// - `String` - Canonical route identifier.
149    /// - `PageRetention` - Retention strategy (`Freeze`, `Destroy`, `Alive`).
150    /// - `Option<u64>` - Optional parent `page_id` for deterministic parent-child lifecycle propagation.
151    /// - `usize` - Core retained state memory footprint in bytes.
152    /// - `usize` - Reconstructible cache memory footprint in bytes (evicted before page eviction).
153    ///
154    /// # Returns
155    ///
156    /// - `PageGenerationToken` - Generation-guarded handle for async callbacks and ownership tracking.
157    pub fn register_page(
158        &mut self,
159        route_key: String,
160        retention: PageRetention,
161        parent_page_id: Option<u64>,
162        retained_bytes: usize,
163        reconstructible_cache_bytes: usize,
164    ) -> PageGenerationToken {
165        let page_id: u64 = self.get_next_page_id();
166        let next_tick: u64 = self.get_active_clock().wrapping_add(1);
167        let host_rev: u64 = self.get_host_revision();
168        let Self {
169            pages,
170            next_page_id,
171            active_clock,
172            ..
173        } = self;
174        *next_page_id = page_id.wrapping_add(1).max(1);
175        *active_clock = next_tick;
176        let (has_parent, pid): (bool, u64) = match parent_page_id {
177            Some(point_val) => (true, point_val),
178            None => (false, 0),
179        };
180        let entry: PageLifecycleEntry = PageLifecycleEntry {
181            page_id,
182            route_key,
183            generation: 1,
184            parent_page_id: pid,
185            has_parent,
186            phase: LifecyclePhase::Active,
187            retention,
188            retained_bytes,
189            reconstructible_cache_bytes,
190            last_active_tick: next_tick,
191            freeze_count: 0,
192            resume_count: 0,
193            evict_count: 0,
194            host_synced_revision: host_rev,
195            snapshot: PageSnapshot::default(),
196            has_snapshot: false,
197            os_background_suspended: false,
198            surface_lost_generation: 0,
199            has_surface_lost: false,
200        };
201        let _: Option<PageLifecycleEntry> = pages.insert(page_id, entry);
202        PageGenerationToken::new(page_id, 1)
203    }
204
205    /// Returns `true` when `token` matches the current live non-evicted, non-destroyed page generation.
206    ///
207    /// # Arguments
208    ///
209    /// - `&Self` - Page lifecycle controller reference.
210    /// - `PageGenerationToken` - Candidate generation token held by an async task or timer.
211    ///
212    /// # Returns
213    ///
214    /// - `bool` - `true` when writes from `token` are still authorized.
215    #[must_use]
216    pub fn is_token_current(&self, token: PageGenerationToken) -> bool {
217        match self.get_pages().get(&token.get_page_id()) {
218            Some(entry) => {
219                entry.get_generation() == token.get_generation()
220                    && !matches!(
221                        entry.get_phase(),
222                        LifecyclePhase::Evicted | LifecyclePhase::Destroyed
223                    )
224            }
225            None => false,
226        }
227    }
228
229    /// Runs `callback` ONLY when `token` belongs to a live `Active` page of the exact matching generation; otherwise blocks and counts it.
230    ///
231    /// # Arguments
232    ///
233    /// - `&Self` - Mutable page lifecycle controller.
234    /// - `PageGenerationToken` - Generation token captured when the async request started.
235    /// - `CallbackFn` - State commit closure executed only when `token` is still current and active.
236    ///
237    /// # Returns
238    ///
239    /// - `bool` - `true` when the callback executed; `false` when rejected by the generation guard.
240    pub fn try_commit_async_callback<CallbackFn>(
241        &mut self,
242        token: PageGenerationToken,
243        callback: CallbackFn,
244    ) -> bool
245    where
246        CallbackFn: FnOnce(),
247    {
248        let allowed: bool =
249            self.get_pages()
250                .get(&token.get_page_id())
251                .is_some_and(|entry: &PageLifecycleEntry| {
252                    entry.get_generation() == token.get_generation()
253                        && entry.get_phase() == LifecyclePhase::Active
254                });
255        if allowed {
256            callback();
257            true
258        } else {
259            let Self {
260                stale_callbacks_blocked,
261                ..
262            } = self;
263            *stale_callbacks_blocked = stale_callbacks_blocked.saturating_add(1);
264            false
265        }
266    }
267
268    /// Attaches or updates a versioned `PageSnapshot` (including persisted draft status) on `page_id`.
269    ///
270    /// # Arguments
271    ///
272    /// - `&Self` - Mutable page lifecycle controller.
273    /// - `u64` - Target page identifier.
274    /// - `PageSnapshot` - Versioned snapshot payload.
275    ///
276    /// # Returns
277    ///
278    /// - `bool` - `true` if `page_id` exists and is not `Destroyed`.
279    pub fn update_snapshot(&mut self, page_id: u64, snapshot: PageSnapshot) -> bool {
280        let max_bytes: usize = self.get_budget().get_max_snapshot_bytes();
281        let Some(entry) = self.get_mut_pages().get_mut(&page_id) else {
282            return false;
283        };
284        if entry.get_phase() == LifecyclePhase::Destroyed {
285            return false;
286        }
287        let mut bounded: PageSnapshot = snapshot;
288        if bounded.get_estimated_bytes() > max_bytes {
289            bounded.set_estimated_bytes(max_bytes);
290        }
291        entry.set_snapshot(bounded);
292        entry.set_has_snapshot(true);
293        true
294    }
295
296    /// Marks an unsaved draft on `page_id` durably persisted so cold eviction may proceed safely without data loss.
297    ///
298    /// # Arguments
299    ///
300    /// - `&Self` - Mutable page lifecycle controller.
301    /// - `u64` - Target page identifier.
302    /// - `String` - Persisted draft payload stored inside the page snapshot.
303    ///
304    /// # Returns
305    ///
306    /// - `bool` - `true` when the draft was persisted onto the page snapshot.
307    pub fn persist_page_draft(&mut self, page_id: u64, draft_payload: String) -> bool {
308        let Some(entry) = self.get_mut_pages().get_mut(&page_id) else {
309            return false;
310        };
311        if entry.get_phase() == LifecyclePhase::Destroyed {
312            return false;
313        }
314        let mut snap: PageSnapshot = if entry.get_has_snapshot() {
315            entry.get_snapshot().clone()
316        } else {
317            PageSnapshot::capture(
318                entry.get_route_key().clone(),
319                entry.get_generation(),
320                Point::default(),
321                None,
322                String::new(),
323                (true, true),
324                entry.get_host_synced_revision(),
325            )
326        };
327        snap.set_draft_payload(draft_payload);
328        snap.set_has_unsaved_draft(true);
329        snap.set_draft_persisted(true);
330        entry.set_snapshot(snap);
331        entry.set_has_snapshot(true);
332        true
333    }
334
335    /// Collects `root_id` followed by all descendant page IDs in deterministic breadth-first order.
336    ///
337    /// # Arguments
338    ///
339    /// - `&Self` - Page lifecycle controller reference.
340    /// - `u64` - Root page identifier.
341    ///
342    /// # Returns
343    ///
344    /// - `Vec<u64>` - Ordered list of `[root_id, ...descendants]`.
345    #[must_use]
346    fn collect_page_subtree(&self, root_id: u64) -> Vec<u64> {
347        if !self.get_pages().contains_key(&root_id) {
348            return Vec::new();
349        }
350        let mut ordered: Vec<u64> = vec![root_id];
351        let mut cursor: usize = 0;
352        while cursor < ordered.len() {
353            let parent_id: u64 = ordered[cursor];
354            cursor += 1;
355            let mut children: Vec<u64> = self
356                .get_pages()
357                .values()
358                .filter(|entry: &&PageLifecycleEntry| {
359                    entry.get_has_parent() && entry.get_parent_page_id() == parent_id
360                })
361                .map(PageLifecycleEntry::get_page_id)
362                .collect();
363            children.sort_unstable();
364            for cid in children.into_iter() {
365                if !ordered.contains(&cid) {
366                    ordered.push(cid);
367                }
368            }
369        }
370        ordered
371    }
372
373    /// Idempotently freezes `page_id` and its active descendants once without double-firing on already-frozen pages.
374    ///
375    /// # Arguments
376    ///
377    /// - `&Self` - Mutable page lifecycle controller.
378    /// - `u64` - Target page identifier to freeze.
379    /// - `Option<PageSnapshot>` - Optional fresh versioned snapshot captured before freezing.
380    ///
381    /// # Returns
382    ///
383    /// - `Vec<u64>` - Page identifiers newly transitioned from `Active` to `Frozen`.
384    pub fn freeze_page(&mut self, page_id: u64, snapshot: Option<PageSnapshot>) -> Vec<u64> {
385        if let Some(snap) = snapshot {
386            let _: bool = self.update_snapshot(page_id, snap);
387        }
388        let subtree: Vec<u64> = self.collect_page_subtree(page_id);
389        let mut newly_frozen: Vec<u64> = Vec::new();
390        for pid in subtree.into_iter() {
391            if let Some(entry) = self.get_mut_pages().get_mut(&pid)
392                && entry.get_phase() == LifecyclePhase::Active
393            {
394                entry.set_phase(LifecyclePhase::Frozen);
395                entry.set_freeze_count(entry.get_freeze_count().saturating_add(1));
396                newly_frozen.push(pid);
397            }
398        }
399        newly_frozen
400    }
401
402    /// Idempotently resumes `page_id` (and frozen descendants), restoring from `PageSnapshot` if previously `Evicted` and checking host-state synchronization.
403    ///
404    /// # Arguments
405    ///
406    /// - `&Self` - Mutable page lifecycle controller.
407    /// - `u64` - Target page identifier to resume.
408    /// - `u64` - Current authoritative host/shared-store revision.
409    ///
410    /// # Returns
411    ///
412    /// - `Option<(PageGenerationToken, Option<PageSnapshot>, bool)>` - Active token, restored snapshot (when reconstructed or present), and `host_sync_required` flag.
413    pub fn resume_page(
414        &mut self,
415        page_id: u64,
416        current_host_revision: u64,
417    ) -> Option<(PageGenerationToken, Option<PageSnapshot>, bool)> {
418        self.set_host_revision(current_host_revision.max(self.get_host_revision()));
419        let subtree: Vec<u64> = self.collect_page_subtree(page_id);
420        if subtree.is_empty() {
421            return None;
422        }
423        let root_phase: LifecyclePhase = self.get_pages().get(&page_id)?.get_phase();
424        if root_phase == LifecyclePhase::Destroyed {
425            return None;
426        }
427        let next_tick: u64 = self.get_active_clock().wrapping_add(1);
428        {
429            let Self { active_clock, .. } = self;
430            *active_clock = next_tick;
431        }
432        if root_phase == LifecyclePhase::Active {
433            let entry: &mut PageLifecycleEntry = self.get_mut_pages().get_mut(&page_id)?;
434            let host_dirty: bool = entry.get_host_synced_revision() != current_host_revision;
435            entry.set_host_synced_revision(current_host_revision);
436            entry.set_last_active_tick(next_tick);
437            let token: PageGenerationToken =
438                PageGenerationToken::new(entry.get_page_id(), entry.get_generation());
439            return Some((token, None, host_dirty));
440        }
441        let mut root_token: PageGenerationToken = PageGenerationToken::default();
442        let mut restored_snap: Option<PageSnapshot> = None;
443        let mut root_host_dirty: bool = false;
444        for pid in subtree.into_iter() {
445            if let Some(entry) = self.get_mut_pages().get_mut(&pid) {
446                match entry.get_phase() {
447                    LifecyclePhase::Frozen => {
448                        let dirty: bool = entry.get_host_synced_revision() != current_host_revision;
449                        entry.set_phase(LifecyclePhase::Active);
450                        entry.set_resume_count(entry.get_resume_count().saturating_add(1));
451                        entry.set_host_synced_revision(current_host_revision);
452                        entry.set_last_active_tick(next_tick);
453                        if pid == page_id {
454                            root_token = PageGenerationToken::new(pid, entry.get_generation());
455                            root_host_dirty = dirty;
456                            if entry.get_has_snapshot() {
457                                restored_snap = Some(entry.get_snapshot().clone());
458                            }
459                        }
460                    }
461                    LifecyclePhase::Evicted => {
462                        let next_gen: u64 = entry.get_generation().wrapping_add(1).max(1);
463                        entry.set_generation(next_gen);
464                        entry.set_phase(LifecyclePhase::Active);
465                        entry.set_resume_count(entry.get_resume_count().saturating_add(1));
466                        entry.set_host_synced_revision(current_host_revision);
467                        entry.set_last_active_tick(next_tick);
468                        if pid == page_id {
469                            root_token = PageGenerationToken::new(pid, next_gen);
470                            root_host_dirty = true;
471                            if entry.get_has_snapshot() {
472                                restored_snap = Some(entry.get_snapshot().clone());
473                            }
474                        }
475                    }
476                    LifecyclePhase::Active
477                    | LifecyclePhase::Created
478                    | LifecyclePhase::Mounted
479                    | LifecyclePhase::Unmounted
480                    | LifecyclePhase::Destroyed => {}
481                }
482            }
483        }
484        Some((root_token, restored_snap, root_host_dirty))
485    }
486
487    /// Enforces bounded cold-page budgets: FIRST drains reconstructible caches, THEN evicts oldest cold `Frozen` pages while protecting unpersisted unsaved drafts.
488    ///
489    /// # Arguments
490    ///
491    /// - `&Self` - Mutable page lifecycle controller.
492    ///
493    /// # Returns
494    ///
495    /// - `PageEvictionReport` - Freed reconstructible bytes, evicted page IDs, and protected unsaved draft count.
496    pub fn enforce_budget(&mut self) -> PageEvictionReport {
497        let policy: PageBudgetPolicy = self.get_budget();
498        let mut report: PageEvictionReport = PageEvictionReport::default();
499        let mut frozen_list: Vec<(u64, u64)> = self
500            .get_pages()
501            .values()
502            .filter(|event_ref: &&PageLifecycleEntry| {
503                event_ref.get_phase() == LifecyclePhase::Frozen
504            })
505            .map(|error_val: &PageLifecycleEntry| {
506                (error_val.get_last_active_tick(), error_val.get_page_id())
507            })
508            .collect();
509        frozen_list.sort_unstable_by_key(|pair: &(u64, u64)| pair.0);
510        let mut total_bytes: usize = self
511            .get_pages()
512            .values()
513            .filter(|entry_ref: &&PageLifecycleEntry| {
514                entry_ref.get_phase() == LifecyclePhase::Frozen
515            })
516            .fold(0_usize, |acc: usize, edge_vec: &PageLifecycleEntry| {
517                acc.saturating_add(edge_vec.get_retained_bytes())
518                    .saturating_add(edge_vec.get_reconstructible_cache_bytes())
519            });
520        for &(_, pid) in frozen_list.iter() {
521            if total_bytes <= policy.get_max_retained_bytes() {
522                break;
523            }
524            if let Some(entry) = self.get_mut_pages().get_mut(&pid) {
525                let cache_bytes: usize = entry.get_reconstructible_cache_bytes();
526                if cache_bytes > 0 {
527                    entry.set_reconstructible_cache_bytes(0);
528                    total_bytes = total_bytes.saturating_sub(cache_bytes);
529                    report.set_reconstructible_bytes_freed(
530                        report
531                            .get_reconstructible_bytes_freed()
532                            .saturating_add(cache_bytes),
533                    );
534                }
535            }
536        }
537        let mut frozen_count: usize = frozen_list.len();
538        for (_, pid) in frozen_list.into_iter() {
539            let over_count: bool = frozen_count > policy.get_max_frozen_pages();
540            let over_bytes: bool = total_bytes > policy.get_max_retained_bytes();
541            if !over_count && !over_bytes {
542                break;
543            }
544            let Some(entry) = self.get_mut_pages().get_mut(&pid) else {
545                continue;
546            };
547            if entry.get_phase() != LifecyclePhase::Frozen {
548                continue;
549            }
550            let has_unpersisted_draft: bool = entry.get_has_snapshot()
551                && entry.get_snapshot().get_has_unsaved_draft()
552                && !entry.get_snapshot().get_draft_persisted();
553            if has_unpersisted_draft {
554                report.set_protected_unsaved_pages(
555                    report.get_protected_unsaved_pages().saturating_add(1),
556                );
557                continue;
558            }
559            if !entry.get_has_snapshot() {
560                let fallback_snap: PageSnapshot = PageSnapshot::capture(
561                    entry.get_route_key().clone(),
562                    entry.get_generation(),
563                    Point::default(),
564                    None,
565                    String::new(),
566                    (false, false),
567                    entry.get_host_synced_revision(),
568                );
569                entry.set_snapshot(fallback_snap);
570                entry.set_has_snapshot(true);
571            }
572            let freed_now: usize = entry
573                .get_retained_bytes()
574                .saturating_add(entry.get_reconstructible_cache_bytes());
575            let snap_bytes: usize = entry
576                .get_snapshot()
577                .get_estimated_bytes()
578                .min(policy.get_max_snapshot_bytes());
579            let next_gen: u64 = entry.get_generation().wrapping_add(1).max(1);
580            entry.set_generation(next_gen);
581            entry.set_phase(LifecyclePhase::Evicted);
582            entry.set_retained_bytes(snap_bytes);
583            entry.set_reconstructible_cache_bytes(0);
584            entry.set_evict_count(entry.get_evict_count().saturating_add(1));
585            total_bytes = total_bytes.saturating_sub(freed_now);
586            frozen_count = frozen_count.saturating_sub(1);
587            report.get_mut_evicted_page_ids().push(pid);
588        }
589        report
590    }
591
592    /// Explicitly destroys `page_id` and all descendants, bumping generation, dropping `PageSnapshot`, and blocking all stale async writes.
593    ///
594    /// # Arguments
595    ///
596    /// - `&Self` - Mutable page lifecycle controller.
597    /// - `u64` - Target page identifier to destroy permanently.
598    ///
599    /// # Returns
600    ///
601    /// - `Vec<PageGenerationToken>` - Destroyed `(page_id, prior_generation)` tokens for resource ownership accounting.
602    pub fn destroy_page(&mut self, page_id: u64) -> Vec<PageGenerationToken> {
603        let subtree: Vec<u64> = self.collect_page_subtree(page_id);
604        let mut destroyed_tokens: Vec<PageGenerationToken> = Vec::new();
605        for pid in subtree.into_iter() {
606            if let Some(entry) = self.get_mut_pages().get_mut(&pid)
607                && entry.get_phase() != LifecyclePhase::Destroyed
608            {
609                let old_token: PageGenerationToken =
610                    PageGenerationToken::new(pid, entry.get_generation());
611                let next_gen: u64 = entry.get_generation().wrapping_add(1).max(1);
612                entry.set_generation(next_gen);
613                entry.set_phase(LifecyclePhase::Destroyed);
614                entry.set_retained_bytes(0);
615                entry.set_reconstructible_cache_bytes(0);
616                entry.set_snapshot(PageSnapshot::default());
617                entry.set_has_snapshot(false);
618                destroyed_tokens.push(old_token);
619            }
620        }
621        let Self {
622            total_destroyed_pages,
623            ..
624        } = self;
625        *total_destroyed_pages =
626            total_destroyed_pages.saturating_add(destroyed_tokens.len() as u64);
627        destroyed_tokens
628    }
629
630    /// Processes a distinct OS background, surface-loss, or route-freeze boundary event without conflating their state transitions.
631    ///
632    /// # Arguments
633    ///
634    /// - `&Self` - Mutable page lifecycle controller.
635    /// - `LifecycleBoundaryEvent` - Structured boundary event.
636    ///
637    /// # Returns
638    ///
639    /// - `usize` - Number of page entries updated by this boundary event.
640    pub fn apply_boundary_event(&mut self, event: LifecycleBoundaryEvent) -> usize {
641        match event {
642            LifecycleBoundaryEvent::OsBackground => {
643                let Self {
644                    pages,
645                    os_background_events,
646                    ..
647                } = self;
648                *os_background_events = os_background_events.saturating_add(1);
649                let mut touched: usize = 0;
650                for entry in pages.values_mut() {
651                    if matches!(
652                        entry.get_phase(),
653                        LifecyclePhase::Active | LifecyclePhase::Frozen
654                    ) && !entry.get_os_background_suspended()
655                    {
656                        entry.set_os_background_suspended(true);
657                        touched += 1;
658                    }
659                }
660                touched
661            }
662            LifecycleBoundaryEvent::OsForeground => {
663                let Self {
664                    pages,
665                    os_foreground_events,
666                    ..
667                } = self;
668                *os_foreground_events = os_foreground_events.saturating_add(1);
669                let mut touched: usize = 0;
670                for entry in pages.values_mut() {
671                    if entry.get_os_background_suspended() {
672                        entry.set_os_background_suspended(false);
673                        touched += 1;
674                    }
675                }
676                touched
677            }
678            LifecycleBoundaryEvent::SurfaceLost { surface_generation } => {
679                let Self {
680                    pages,
681                    surface_lost_events,
682                    ..
683                } = self;
684                *surface_lost_events = surface_lost_events.saturating_add(1);
685                let mut touched: usize = 0;
686                for entry in pages.values_mut() {
687                    if entry.get_phase() != LifecyclePhase::Destroyed {
688                        entry.set_has_surface_lost(true);
689                        entry.set_surface_lost_generation(surface_generation);
690                        touched += 1;
691                    }
692                }
693                touched
694            }
695            LifecycleBoundaryEvent::SurfaceRecreated { surface_generation } => {
696                let Self {
697                    pages,
698                    surface_recreated_events,
699                    ..
700                } = self;
701                *surface_recreated_events = surface_recreated_events.saturating_add(1);
702                let mut touched: usize = 0;
703                for entry in pages.values_mut() {
704                    if entry.get_has_surface_lost() {
705                        entry.set_has_surface_lost(false);
706                        entry.set_surface_lost_generation(surface_generation);
707                        touched += 1;
708                    }
709                }
710                touched
711            }
712            LifecycleBoundaryEvent::RouteFreeze { page_id } => {
713                self.freeze_page(page_id, None).len()
714            }
715            LifecycleBoundaryEvent::RouteResume { page_id } => {
716                let host_rev: u64 = self.get_host_revision();
717                usize::from(self.resume_page(page_id, host_rev).is_some())
718            }
719        }
720    }
721
722    /// Returns aggregate page counts `(active, frozen, evicted, destroyed)` for resource accounting snapshots.
723    ///
724    /// # Arguments
725    ///
726    /// - `&Self` - Page lifecycle controller reference.
727    ///
728    /// # Returns
729    ///
730    /// - `(usize, usize, usize, u64)` - Tuple `(active, frozen, evicted, total_destroyed)`.
731    #[must_use]
732    pub fn phase_counts(&self) -> (usize, usize, usize, u64) {
733        let mut active: usize = 0;
734        let mut frozen: usize = 0;
735        let mut evicted: usize = 0;
736        for entry in self.get_pages().values() {
737            match entry.get_phase() {
738                LifecyclePhase::Active | LifecyclePhase::Mounted | LifecyclePhase::Created => {
739                    active += 1;
740                }
741                LifecyclePhase::Frozen => {
742                    frozen += 1;
743                }
744                LifecyclePhase::Evicted => {
745                    evicted += 1;
746                }
747                LifecyclePhase::Unmounted | LifecyclePhase::Destroyed => {}
748            }
749        }
750        (active, frozen, evicted, self.get_total_destroyed_pages())
751    }
752}