euv_core/scene/lifecycle/
impl.rs1use super::*;
2
3impl Lifecycle for NodeId {}
5
6impl Component for NodeId {
8 fn render(&self) -> NodeId {
18 *self
19 }
20
21 fn mount(self) -> NodeId {
31 self
32 }
33}
34
35impl Default for PageBudgetPolicy {
37 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
51impl PageSnapshot {
53 #[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(k) if !k.is_empty() => (true, k),
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
103impl Default for PageLifecycleController {
105 fn default() -> Self {
111 Self::with_budget(PageBudgetPolicy::default())
112 }
113}
114
115impl PageLifecycleController {
117 #[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 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(p) => (true, p),
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 #[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 pub fn try_commit_async_callback<F>(&mut self, token: PageGenerationToken, callback: F) -> bool
241 where
242 F: FnOnce(),
243 {
244 let allowed: bool =
245 self.get_pages()
246 .get(&token.get_page_id())
247 .is_some_and(|entry: &PageLifecycleEntry| {
248 entry.get_generation() == token.get_generation()
249 && entry.get_phase() == LifecyclePhase::Active
250 });
251 if allowed {
252 callback();
253 true
254 } else {
255 let Self {
256 stale_callbacks_blocked,
257 ..
258 } = self;
259 *stale_callbacks_blocked = stale_callbacks_blocked.saturating_add(1);
260 false
261 }
262 }
263
264 pub fn update_snapshot(&mut self, page_id: u64, snapshot: PageSnapshot) -> bool {
276 let max_bytes: usize = self.get_budget().get_max_snapshot_bytes();
277 let Some(entry) = self.get_mut_pages().get_mut(&page_id) else {
278 return false;
279 };
280 if entry.get_phase() == LifecyclePhase::Destroyed {
281 return false;
282 }
283 let mut bounded: PageSnapshot = snapshot;
284 if bounded.get_estimated_bytes() > max_bytes {
285 bounded.set_estimated_bytes(max_bytes);
286 }
287 entry.set_snapshot(bounded);
288 entry.set_has_snapshot(true);
289 true
290 }
291
292 pub fn persist_page_draft(&mut self, page_id: u64, draft_payload: String) -> bool {
304 let Some(entry) = self.get_mut_pages().get_mut(&page_id) else {
305 return false;
306 };
307 if entry.get_phase() == LifecyclePhase::Destroyed {
308 return false;
309 }
310 let mut snap: PageSnapshot = if entry.get_has_snapshot() {
311 entry.get_snapshot().clone()
312 } else {
313 PageSnapshot::capture(
314 entry.get_route_key().clone(),
315 entry.get_generation(),
316 Point::default(),
317 None,
318 String::new(),
319 (true, true),
320 entry.get_host_synced_revision(),
321 )
322 };
323 snap.set_draft_payload(draft_payload);
324 snap.set_has_unsaved_draft(true);
325 snap.set_draft_persisted(true);
326 entry.set_snapshot(snap);
327 entry.set_has_snapshot(true);
328 true
329 }
330
331 #[must_use]
342 fn collect_page_subtree(&self, root_id: u64) -> Vec<u64> {
343 if !self.get_pages().contains_key(&root_id) {
344 return Vec::new();
345 }
346 let mut ordered: Vec<u64> = vec![root_id];
347 let mut cursor: usize = 0;
348 while cursor < ordered.len() {
349 let parent_id: u64 = ordered[cursor];
350 cursor += 1;
351 let mut children: Vec<u64> = self
352 .get_pages()
353 .values()
354 .filter(|entry: &&PageLifecycleEntry| {
355 entry.get_has_parent() && entry.get_parent_page_id() == parent_id
356 })
357 .map(PageLifecycleEntry::get_page_id)
358 .collect();
359 children.sort_unstable();
360 for cid in children.into_iter() {
361 if !ordered.contains(&cid) {
362 ordered.push(cid);
363 }
364 }
365 }
366 ordered
367 }
368
369 pub fn freeze_page(&mut self, page_id: u64, snapshot: Option<PageSnapshot>) -> Vec<u64> {
381 if let Some(snap) = snapshot {
382 let _: bool = self.update_snapshot(page_id, snap);
383 }
384 let subtree: Vec<u64> = self.collect_page_subtree(page_id);
385 let mut newly_frozen: Vec<u64> = Vec::new();
386 for pid in subtree.into_iter() {
387 if let Some(entry) = self.get_mut_pages().get_mut(&pid)
388 && entry.get_phase() == LifecyclePhase::Active
389 {
390 entry.set_phase(LifecyclePhase::Frozen);
391 entry.set_freeze_count(entry.get_freeze_count().saturating_add(1));
392 newly_frozen.push(pid);
393 }
394 }
395 newly_frozen
396 }
397
398 pub fn resume_page(
410 &mut self,
411 page_id: u64,
412 current_host_revision: u64,
413 ) -> Option<(PageGenerationToken, Option<PageSnapshot>, bool)> {
414 self.set_host_revision(current_host_revision.max(self.get_host_revision()));
415 let subtree: Vec<u64> = self.collect_page_subtree(page_id);
416 if subtree.is_empty() {
417 return None;
418 }
419 let root_phase: LifecyclePhase = self.get_pages().get(&page_id)?.get_phase();
420 if root_phase == LifecyclePhase::Destroyed {
421 return None;
422 }
423 let next_tick: u64 = self.get_active_clock().wrapping_add(1);
424 {
425 let Self { active_clock, .. } = self;
426 *active_clock = next_tick;
427 }
428 if root_phase == LifecyclePhase::Active {
429 let entry: &mut PageLifecycleEntry = self.get_mut_pages().get_mut(&page_id)?;
430 let host_dirty: bool = entry.get_host_synced_revision() != current_host_revision;
431 entry.set_host_synced_revision(current_host_revision);
432 entry.set_last_active_tick(next_tick);
433 let token: PageGenerationToken =
434 PageGenerationToken::new(entry.get_page_id(), entry.get_generation());
435 return Some((token, None, host_dirty));
436 }
437 let mut root_token: PageGenerationToken = PageGenerationToken::default();
438 let mut restored_snap: Option<PageSnapshot> = None;
439 let mut root_host_dirty: bool = false;
440 for pid in subtree.into_iter() {
441 if let Some(entry) = self.get_mut_pages().get_mut(&pid) {
442 match entry.get_phase() {
443 LifecyclePhase::Frozen => {
444 let dirty: bool = entry.get_host_synced_revision() != current_host_revision;
445 entry.set_phase(LifecyclePhase::Active);
446 entry.set_resume_count(entry.get_resume_count().saturating_add(1));
447 entry.set_host_synced_revision(current_host_revision);
448 entry.set_last_active_tick(next_tick);
449 if pid == page_id {
450 root_token = PageGenerationToken::new(pid, entry.get_generation());
451 root_host_dirty = dirty;
452 if entry.get_has_snapshot() {
453 restored_snap = Some(entry.get_snapshot().clone());
454 }
455 }
456 }
457 LifecyclePhase::Evicted => {
458 let next_gen: u64 = entry.get_generation().wrapping_add(1).max(1);
459 entry.set_generation(next_gen);
460 entry.set_phase(LifecyclePhase::Active);
461 entry.set_resume_count(entry.get_resume_count().saturating_add(1));
462 entry.set_host_synced_revision(current_host_revision);
463 entry.set_last_active_tick(next_tick);
464 if pid == page_id {
465 root_token = PageGenerationToken::new(pid, next_gen);
466 root_host_dirty = true;
467 if entry.get_has_snapshot() {
468 restored_snap = Some(entry.get_snapshot().clone());
469 }
470 }
471 }
472 LifecyclePhase::Active
473 | LifecyclePhase::Created
474 | LifecyclePhase::Mounted
475 | LifecyclePhase::Unmounted
476 | LifecyclePhase::Destroyed => {}
477 }
478 }
479 }
480 Some((root_token, restored_snap, root_host_dirty))
481 }
482
483 pub fn enforce_budget(&mut self) -> PageEvictionReport {
493 let policy: PageBudgetPolicy = self.get_budget();
494 let mut report: PageEvictionReport = PageEvictionReport::default();
495 let mut frozen_list: Vec<(u64, u64)> = self
496 .get_pages()
497 .values()
498 .filter(|e: &&PageLifecycleEntry| e.get_phase() == LifecyclePhase::Frozen)
499 .map(|e: &PageLifecycleEntry| (e.get_last_active_tick(), e.get_page_id()))
500 .collect();
501 frozen_list.sort_unstable_by_key(|pair: &(u64, u64)| pair.0);
502 let mut total_bytes: usize = self
503 .get_pages()
504 .values()
505 .filter(|e: &&PageLifecycleEntry| e.get_phase() == LifecyclePhase::Frozen)
506 .fold(0_usize, |acc: usize, e: &PageLifecycleEntry| {
507 acc.saturating_add(e.get_retained_bytes())
508 .saturating_add(e.get_reconstructible_cache_bytes())
509 });
510 for &(_, pid) in frozen_list.iter() {
511 if total_bytes <= policy.get_max_retained_bytes() {
512 break;
513 }
514 if let Some(entry) = self.get_mut_pages().get_mut(&pid) {
515 let cache_bytes: usize = entry.get_reconstructible_cache_bytes();
516 if cache_bytes > 0 {
517 entry.set_reconstructible_cache_bytes(0);
518 total_bytes = total_bytes.saturating_sub(cache_bytes);
519 report.set_reconstructible_bytes_freed(
520 report
521 .get_reconstructible_bytes_freed()
522 .saturating_add(cache_bytes),
523 );
524 }
525 }
526 }
527 let mut frozen_count: usize = frozen_list.len();
528 for (_, pid) in frozen_list.into_iter() {
529 let over_count: bool = frozen_count > policy.get_max_frozen_pages();
530 let over_bytes: bool = total_bytes > policy.get_max_retained_bytes();
531 if !over_count && !over_bytes {
532 break;
533 }
534 let Some(entry) = self.get_mut_pages().get_mut(&pid) else {
535 continue;
536 };
537 if entry.get_phase() != LifecyclePhase::Frozen {
538 continue;
539 }
540 let has_unpersisted_draft: bool = entry.get_has_snapshot()
541 && entry.get_snapshot().get_has_unsaved_draft()
542 && !entry.get_snapshot().get_draft_persisted();
543 if has_unpersisted_draft {
544 report.set_protected_unsaved_pages(
545 report.get_protected_unsaved_pages().saturating_add(1),
546 );
547 continue;
548 }
549 if !entry.get_has_snapshot() {
550 let fallback_snap: PageSnapshot = PageSnapshot::capture(
551 entry.get_route_key().clone(),
552 entry.get_generation(),
553 Point::default(),
554 None,
555 String::new(),
556 (false, false),
557 entry.get_host_synced_revision(),
558 );
559 entry.set_snapshot(fallback_snap);
560 entry.set_has_snapshot(true);
561 }
562 let freed_now: usize = entry
563 .get_retained_bytes()
564 .saturating_add(entry.get_reconstructible_cache_bytes());
565 let snap_bytes: usize = entry
566 .get_snapshot()
567 .get_estimated_bytes()
568 .min(policy.get_max_snapshot_bytes());
569 let next_gen: u64 = entry.get_generation().wrapping_add(1).max(1);
570 entry.set_generation(next_gen);
571 entry.set_phase(LifecyclePhase::Evicted);
572 entry.set_retained_bytes(snap_bytes);
573 entry.set_reconstructible_cache_bytes(0);
574 entry.set_evict_count(entry.get_evict_count().saturating_add(1));
575 total_bytes = total_bytes.saturating_sub(freed_now);
576 frozen_count = frozen_count.saturating_sub(1);
577 report.get_mut_evicted_page_ids().push(pid);
578 }
579 report
580 }
581
582 pub fn destroy_page(&mut self, page_id: u64) -> Vec<PageGenerationToken> {
593 let subtree: Vec<u64> = self.collect_page_subtree(page_id);
594 let mut destroyed_tokens: Vec<PageGenerationToken> = Vec::new();
595 for pid in subtree.into_iter() {
596 if let Some(entry) = self.get_mut_pages().get_mut(&pid)
597 && entry.get_phase() != LifecyclePhase::Destroyed
598 {
599 let old_token: PageGenerationToken =
600 PageGenerationToken::new(pid, entry.get_generation());
601 let next_gen: u64 = entry.get_generation().wrapping_add(1).max(1);
602 entry.set_generation(next_gen);
603 entry.set_phase(LifecyclePhase::Destroyed);
604 entry.set_retained_bytes(0);
605 entry.set_reconstructible_cache_bytes(0);
606 entry.set_snapshot(PageSnapshot::default());
607 entry.set_has_snapshot(false);
608 destroyed_tokens.push(old_token);
609 }
610 }
611 let Self {
612 total_destroyed_pages,
613 ..
614 } = self;
615 *total_destroyed_pages =
616 total_destroyed_pages.saturating_add(destroyed_tokens.len() as u64);
617 destroyed_tokens
618 }
619
620 pub fn apply_boundary_event(&mut self, event: LifecycleBoundaryEvent) -> usize {
631 match event {
632 LifecycleBoundaryEvent::OsBackground => {
633 let Self {
634 pages,
635 os_background_events,
636 ..
637 } = self;
638 *os_background_events = os_background_events.saturating_add(1);
639 let mut touched: usize = 0;
640 for entry in pages.values_mut() {
641 if matches!(
642 entry.get_phase(),
643 LifecyclePhase::Active | LifecyclePhase::Frozen
644 ) && !entry.get_os_background_suspended()
645 {
646 entry.set_os_background_suspended(true);
647 touched += 1;
648 }
649 }
650 touched
651 }
652 LifecycleBoundaryEvent::OsForeground => {
653 let Self {
654 pages,
655 os_foreground_events,
656 ..
657 } = self;
658 *os_foreground_events = os_foreground_events.saturating_add(1);
659 let mut touched: usize = 0;
660 for entry in pages.values_mut() {
661 if entry.get_os_background_suspended() {
662 entry.set_os_background_suspended(false);
663 touched += 1;
664 }
665 }
666 touched
667 }
668 LifecycleBoundaryEvent::SurfaceLost { surface_generation } => {
669 let Self {
670 pages,
671 surface_lost_events,
672 ..
673 } = self;
674 *surface_lost_events = surface_lost_events.saturating_add(1);
675 let mut touched: usize = 0;
676 for entry in pages.values_mut() {
677 if entry.get_phase() != LifecyclePhase::Destroyed {
678 entry.set_has_surface_lost(true);
679 entry.set_surface_lost_generation(surface_generation);
680 touched += 1;
681 }
682 }
683 touched
684 }
685 LifecycleBoundaryEvent::SurfaceRecreated { surface_generation } => {
686 let Self {
687 pages,
688 surface_recreated_events,
689 ..
690 } = self;
691 *surface_recreated_events = surface_recreated_events.saturating_add(1);
692 let mut touched: usize = 0;
693 for entry in pages.values_mut() {
694 if entry.get_has_surface_lost() {
695 entry.set_has_surface_lost(false);
696 entry.set_surface_lost_generation(surface_generation);
697 touched += 1;
698 }
699 }
700 touched
701 }
702 LifecycleBoundaryEvent::RouteFreeze { page_id } => {
703 self.freeze_page(page_id, None).len()
704 }
705 LifecycleBoundaryEvent::RouteResume { page_id } => {
706 let host_rev: u64 = self.get_host_revision();
707 usize::from(self.resume_page(page_id, host_rev).is_some())
708 }
709 }
710 }
711
712 #[must_use]
722 pub fn phase_counts(&self) -> (usize, usize, usize, u64) {
723 let mut active: usize = 0;
724 let mut frozen: usize = 0;
725 let mut evicted: usize = 0;
726 for entry in self.get_pages().values() {
727 match entry.get_phase() {
728 LifecyclePhase::Active | LifecyclePhase::Mounted | LifecyclePhase::Created => {
729 active += 1;
730 }
731 LifecyclePhase::Frozen => {
732 frozen += 1;
733 }
734 LifecyclePhase::Evicted => {
735 evicted += 1;
736 }
737 LifecyclePhase::Unmounted | LifecyclePhase::Destroyed => {}
738 }
739 }
740 (active, frozen, evicted, self.get_total_destroyed_pages())
741 }
742}