1use std::rc::Rc;
2
3use web_time::Instant;
4
5use crate::{
6 Applier, ApplierGuard, ApplierHost, Composer, ConcreteApplierHost, DIAGNOSTICS,
7 DefaultScheduler, Key, NodeError, NodeId, PausableContent, RecomposeScope, RetentionPolicy,
8 Runtime, RuntimeHandle, ScopeId, SlotDebugSnapshot, SlotTable, SlotTableDebugStats, SlotsHost,
9 debug_scope_invalidation_sources, debug_scope_label, runtime, scheduler_ref,
10};
11
12mod scope_groups;
13
14use scope_groups::ScopeGroups;
15
16pub struct Composition<A: Applier + 'static> {
19 parked_composer: Option<Composer>,
23 pub(crate) composer_state: Rc<crate::composer::ComposerRuntimeState>,
24 pub(crate) slots: Rc<SlotsHost>,
25 pub(crate) applier: Rc<ConcreteApplierHost<A>>,
26 pub(crate) runtime: Runtime,
27 pub(crate) root: Option<NodeId>,
28 pub(crate) root_key: Option<Key>,
29 pub(crate) root_render_requested: bool,
30 scope_groups: Option<Box<ScopeGroups>>,
33 #[cfg(any(test, feature = "leak-debug"))]
34 last_pass_stats: CompositionPassDebugStats,
35 teardown: Option<runtime::StateTeardownScope>,
36}
37
38#[doc(hidden)]
41pub struct LayoutBudget {
42 state: Rc<crate::composer::ComposerRuntimeState>,
43 runtime: RuntimeHandle,
44}
45
46impl Drop for LayoutBudget {
47 fn drop(&mut self) {
48 self.state.pausing.close_layout(&self.runtime);
49 }
50}
51
52pub const ROOT_RENDER_REPLAY_LIMIT: usize = 100;
68
69impl<A: Applier + 'static> Composition<A> {
70 pub fn new(applier: A) -> Self {
73 Self::with_runtime(applier, Runtime::new(scheduler_ref(DefaultScheduler)))
74 }
75
76 pub fn with_runtime(applier: A, runtime: Runtime) -> Self {
79 let composer_state = Rc::new(crate::composer::ComposerRuntimeState::default());
80 let slots = Rc::new(SlotsHost::new(SlotTable::new()));
81 let applier = Rc::new(ConcreteApplierHost::new(applier));
82 Self {
83 parked_composer: None,
84 composer_state,
85 slots,
86 applier,
87 runtime,
88 root: None,
89 root_key: None,
90 root_render_requested: false,
91 scope_groups: None,
92 #[cfg(any(test, feature = "leak-debug"))]
93 last_pass_stats: CompositionPassDebugStats::default(),
94 teardown: None,
95 }
96 }
97
98 pub fn root_key(&self) -> Option<Key> {
101 self.root_key
102 }
103
104 pub fn set_retention_policy(&self, policy: RetentionPolicy) {
107 self.composer_state.set_retention_policy(policy);
108 }
109
110 fn slots_host(&self) -> Rc<SlotsHost> {
111 Rc::clone(&self.slots)
112 }
113
114 fn applier_host(&self) -> Rc<dyn ApplierHost> {
115 Rc::<ConcreteApplierHost<A>>::clone(&self.applier)
116 }
117
118 #[expect(clippy::print_stderr, reason = "COMPOSE_DEBUG_SLOT_TABLE asks for it")]
119 fn maybe_dump_slot_table(&self, label: &str) {
120 if !DIAGNOSTICS.compose_debug_slot_table.is_set() {
121 return;
122 }
123 eprintln!(
124 "[COMPOSE_DEBUG_SLOT_TABLE] {label}\n{:#?}",
125 self.debug_slot_snapshot()
126 );
127 }
128
129 pub fn take_root_render_request(&mut self) -> bool {
131 std::mem::take(&mut self.root_render_requested)
132 }
133
134 pub fn request_root_render(&mut self) {
136 self.root_render_requested = true;
137 self.runtime.handle().schedule();
138 }
139
140 fn finalize_runtime_state(&mut self) {
141 if !self.runtime.has_updates()
142 && !self.runtime.has_invalid_scopes()
143 && !self.runtime.has_frame_callbacks()
144 && !self.runtime.has_pending_ui()
145 {
146 self.runtime.set_needs_frame(false);
147 }
148 }
149
150 fn abandon_host_after_apply_failure(&mut self, host: &Rc<SlotsHost>) {
151 host.abandon_after_apply_failure();
152 if Rc::ptr_eq(host, &self.slots) {
153 self.root = None;
154 }
155 self.root_render_requested = true;
156 self.finalize_runtime_state();
157 }
158
159 fn apply_commands_and_updates_for_host(
162 &mut self,
163 host: &Rc<SlotsHost>,
164 runtime_handle: &RuntimeHandle,
165 composer: &Composer,
166 ) -> Result<(), NodeError> {
167 let result = composer.with_commands(|commands| {
168 let mut applier = self.applier.borrow_dyn();
169 let mut result = commands.apply(&mut *applier);
170 if result.is_ok() {
171 for update in runtime_handle.take_updates() {
172 if let Err(err) = update.apply(&mut *applier) {
173 result = Err(err);
174 break;
175 }
176 }
177 }
178 result
179 });
180 if result.is_err() {
181 self.abandon_host_after_apply_failure(host);
182 }
183 result
184 }
185
186 fn render_root_pass(&mut self, key: Key, content: &mut dyn FnMut()) -> Result<(), NodeError> {
187 self.root_key = Some(key);
188 self.root_render_requested = false;
189 let runtime_handle = self.runtime_handle();
190 runtime_handle.drain_ui();
191 let side_effects = {
192 let _teardown = runtime::enter_state_teardown_scope();
193 let composer = Composer::new_with_shared_state(
194 Rc::clone(&self.composer_state),
195 Rc::clone(&self.slots),
196 Rc::<ConcreteApplierHost<A>>::clone(&self.applier),
197 runtime_handle.clone(),
198 self.root,
199 );
200 let (root, side_effects, compact_applier) = composer.install(|composer| {
201 let ((), outcome) = composer.try_with_slot_host_pass(
202 Rc::clone(&self.slots),
203 crate::slot::SlotPassMode::Compose,
204 |composer| composer.with_group(key, |_| content()),
205 )?;
206 let root = composer.root();
207 let side_effects = composer.take_side_effects();
208 Ok((root, side_effects, outcome.compacted))
209 })?;
210 #[cfg(any(test, feature = "leak-debug"))]
211 composer.with_commands(|commands| self.last_pass_stats.record(commands, &side_effects));
212 self.apply_commands_and_updates_for_host(
213 &Rc::clone(&self.slots),
214 &runtime_handle,
215 &composer,
216 )?;
217 if compact_applier {
218 self.applier.compact();
219 self.applier.borrow_dyn().clear_recycled_nodes();
220 }
221
222 self.root = root;
223 side_effects
224 };
225 runtime_handle.drain_ui();
226 for effect in side_effects {
227 effect();
228 }
229 runtime_handle.drain_ui();
230 self.maybe_dump_slot_table("root_render_pass");
231 Ok(())
232 }
233
234 fn reconcile_with_content(
235 &mut self,
236 key: Key,
237 content: &mut dyn FnMut(),
238 ) -> Result<bool, NodeError> {
239 self.root_key = Some(key);
240 let mut did_work = false;
241 let mut root_render_replays = 0usize;
242 loop {
243 did_work |= self.process_invalid_scopes_within_budget()?;
244 if !self.take_root_render_request() {
245 return Ok(did_work);
246 }
247
248 root_render_replays += 1;
249 if root_render_replays > ROOT_RENDER_REPLAY_LIMIT {
250 log::error!(
251 "root render replay looped past {ROOT_RENDER_REPLAY_LIMIT} iterations; breaking to keep UI responsive"
252 );
253 return Err(NodeError::RecompositionLimitExceeded {
254 operation: "root render replay",
255 limit: ROOT_RENDER_REPLAY_LIMIT,
256 });
257 }
258
259 self.render_root_pass(key, content)?;
260 did_work = true;
261 }
262 }
263
264 pub fn render(&mut self, key: Key, mut content: impl FnMut()) -> Result<(), NodeError> {
267 #[cfg(any(test, feature = "leak-debug"))]
268 {
269 self.last_pass_stats = CompositionPassDebugStats::default();
270 }
271 self.render_root_pass(key, &mut content)?;
272 let _ = self.process_invalid_scopes()?;
273 Ok(())
274 }
275
276 pub fn render_stable(&mut self, key: Key, mut content: impl FnMut()) -> Result<(), NodeError> {
279 #[cfg(any(test, feature = "leak-debug"))]
280 {
281 self.last_pass_stats = CompositionPassDebugStats::default();
282 }
283 self.render_root_pass(key, &mut content)?;
284 let _ = self.reconcile_with_content(key, &mut content)?;
285 Ok(())
286 }
287
288 pub fn reconcile(&mut self, key: Key, mut content: impl FnMut()) -> Result<bool, NodeError> {
291 self.reconcile_with_content(key, &mut content)
292 }
293
294 pub fn should_render(&self) -> bool {
303 self.root_render_requested || self.runtime.needs_frame() || self.runtime.has_updates()
304 }
305
306 pub fn should_recompose(&self) -> bool {
322 self.root_render_requested || self.runtime.has_updates()
323 }
324
325 pub fn set_pausable_budget(&self, budget: Option<std::time::Duration>) {
330 self.composer_state.pausing.set_budget(budget);
331 }
332
333 #[doc(hidden)]
338 pub fn open_layout_budget(&self) -> LayoutBudget {
339 self.composer_state.pausing.open_layout();
340 LayoutBudget {
341 state: Rc::clone(&self.composer_state),
342 runtime: self.runtime.handle(),
343 }
344 }
345
346 pub fn runtime_handle(&self) -> RuntimeHandle {
348 self.runtime.handle()
349 }
350
351 pub fn runtime(&self) -> &Runtime {
353 &self.runtime
354 }
355
356 pub fn applier_mut(&mut self) -> ApplierGuard<'_, A> {
358 self.applier.borrow_typed()
359 }
360
361 pub fn root(&self) -> Option<NodeId> {
363 self.root
364 }
365
366 pub fn debug_dump_slot_table_groups(&self) -> Vec<(usize, Key, Option<ScopeId>, usize)> {
369 self.slots.borrow().debug_dump_groups()
370 }
371
372 pub fn debug_dump_slot_entries(&self) -> Vec<crate::SlotDebugEntry> {
374 self.slots.borrow().debug_dump_slot_entries()
375 }
376
377 pub fn slot_table_heap_bytes(&self) -> usize {
379 self.slots.borrow().heap_bytes()
380 }
381
382 pub fn debug_slot_table_stats(&self) -> SlotTableDebugStats {
384 self.slots.debug_stats()
385 }
386
387 pub fn debug_slot_snapshot(&self) -> SlotDebugSnapshot {
389 self.slots.debug_snapshot()
390 }
391
392 #[cfg(any(test, feature = "leak-debug"))]
394 pub fn debug_last_pass_stats(&self) -> CompositionPassDebugStats {
395 self.last_pass_stats
396 }
397
398 #[cfg(test)]
399 pub(crate) fn debug_validate_slots(&self) -> Result<(), crate::slot::SlotInvariantError> {
400 let table = self.slots.borrow();
401 table.validate()?;
402 self.composer_state
403 .validate_host_retention(self.slots.as_ref(), &table)
404 }
405
406 fn host_for_scope(&self, scope: &RecomposeScope, root_host: &Rc<SlotsHost>) -> Rc<SlotsHost> {
408 scope
409 .slots_runtime_state()
410 .and_then(|state| {
411 scope
412 .slots_storage_key()
413 .and_then(|storage_key| state.host_for_storage_key(storage_key))
414 })
415 .or_else(|| {
416 scope
417 .slots_storage_key()
418 .and_then(|storage_key| self.composer_state.host_for_storage_key(storage_key))
419 })
420 .unwrap_or_else(|| Rc::clone(root_host))
421 }
422
423 fn process_invalid_scopes_within_budget(&mut self) -> Result<bool, NodeError> {
426 self.composer_state.pausing.start_budget();
427 let result = self.process_invalid_scopes_until_root_request();
428 self.composer_state.pausing.end_budget(&self.runtime);
429 result
430 }
431
432 fn process_invalid_scopes_until_root_request(&mut self) -> Result<bool, NodeError> {
433 let runtime_handle = self.runtime_handle();
434 let mut did_recompose = false;
435 let mut loop_count = 0;
436 loop {
437 loop_count += 1;
438 if loop_count > ROOT_RENDER_REPLAY_LIMIT {
439 log::error!(
440 "process_invalid_scopes looped past {ROOT_RENDER_REPLAY_LIMIT} iterations; breaking to keep UI responsive"
441 );
442 return Err(NodeError::RecompositionLimitExceeded {
443 operation: "process_invalid_scopes",
444 limit: ROOT_RENDER_REPLAY_LIMIT,
445 });
446 }
447 runtime_handle.drain_ui();
448 self.dispose_forgotten_movables()?;
449 let (scopes, batch) = match runtime_handle.take_invalidated_scopes() {
450 Some(scopes) => (scopes, Batch::Invalid),
451 None => match self.composer_state.pausing.take_resumable() {
452 Some((content, scopes)) => (scopes, Batch::Waiting(content)),
453 None => break,
454 },
455 };
456 let Some(mut scopes) = self.rerun_derivations(&runtime_handle, scopes) else {
457 continue;
458 };
459 did_recompose = true;
460 let mut groups = self.scope_groups.take().unwrap_or_default();
461 groups.group(&mut scopes, |scope| self.host_for_scope(scope, &self.slots));
462 for (host, range) in groups.iter() {
463 let side_effects = self.recompose_host_scopes(
464 host,
465 &scopes[range.clone()],
466 &batch,
467 &runtime_handle,
468 )?;
469 runtime_handle.drain_ui();
470 for effect in side_effects {
471 effect();
472 }
473 runtime_handle.drain_ui();
474 self.maybe_dump_slot_table("recompose_pass");
475 if self.root_render_requested {
476 requeue_scopes(&runtime_handle, &batch, &scopes[range.end..]);
477 break;
478 }
479 }
480 groups.clear();
481 self.scope_groups = Some(groups);
482 runtime_handle.recycle_scopes(scopes);
483 if let Batch::Waiting(content) = batch {
484 self.composer_state.pausing.finish_resumed(content);
485 }
486 if self.root_render_requested {
487 break;
488 }
489 }
490 self.finalize_runtime_state();
491 Ok(did_recompose)
492 }
493
494 fn recompose_host_scopes(
497 &mut self,
498 host: &Rc<SlotsHost>,
499 scopes: &[RecomposeScope],
500 batch: &Batch,
501 runtime_handle: &RuntimeHandle,
502 ) -> Result<Vec<Box<dyn FnOnce()>>, NodeError> {
503 let shared_state = host
504 .runtime_state()
505 .or_else(|| scopes.first().and_then(RecomposeScope::slots_runtime_state))
506 .unwrap_or_else(|| Rc::clone(&self.composer_state));
507 let threshold_ms = DIAGNOSTICS.recompose_scope_telemetry_ms.threshold_ms();
508 let _teardown = runtime::enter_state_teardown_scope();
509 let composer = Composer::for_pass(
510 self.parked_composer.take(),
511 shared_state,
512 Rc::clone(host),
513 self.applier_host(),
514 runtime_handle.clone(),
515 self.root,
516 );
517 composer.parent_stack().clear();
518 let (root, side_effects, requested_root_render, compact_applier) =
519 composer.install(|composer| {
520 let ((), outcome) = composer.try_with_slot_host_pass(
521 Rc::clone(host),
522 crate::slot::SlotPassMode::Recompose,
523 |composer| match (batch, threshold_ms) {
524 (Batch::Invalid, None) => {
525 for scope in scopes {
526 composer.recompose_group(scope);
527 }
528 }
529 (Batch::Invalid, Some(threshold_ms)) => {
530 recompose_timed(composer, scopes, threshold_ms);
531 }
532 (Batch::Waiting(content), _) => {
533 composer.resume_waiting_bodies(content, scopes);
534 }
535 },
536 )?;
537 let root = composer.root();
538 let side_effects = composer.take_side_effects();
539 let requested_root_render = composer.take_root_render_request();
540 Ok((root, side_effects, requested_root_render, outcome.compacted))
541 })?;
542 #[cfg(any(test, feature = "leak-debug"))]
543 composer.with_commands(|commands| self.last_pass_stats.record(commands, &side_effects));
544 self.apply_commands_and_updates_for_host(host, runtime_handle, &composer)?;
545 if compact_applier {
546 self.applier.compact();
547 self.applier.borrow_dyn().clear_recycled_nodes();
548 }
549 if root.is_some() {
550 self.root = root;
551 }
552 if requested_root_render {
553 self.root_render_requested = true;
554 }
555 self.park_composer(host, composer);
556 Ok(side_effects)
557 }
558
559 pub fn process_invalid_scopes(&mut self) -> Result<bool, NodeError> {
562 self.process_invalid_scopes_within_budget()
563 }
564
565 fn rerun_derivations(
571 &mut self,
572 runtime: &RuntimeHandle,
573 mut scopes: Vec<RecomposeScope>,
574 ) -> Option<Vec<RecomposeScope>> {
575 if scopes.iter().any(RecomposeScope::is_derivation) {
576 self.rerun_derivations_of(runtime, &mut scopes);
577 }
578 if scopes.is_empty() {
579 runtime.recycle_scopes(scopes);
580 return None;
581 }
582 Some(scopes)
583 }
584
585 fn rerun_derivations_of(&mut self, runtime: &RuntimeHandle, scopes: &mut Vec<RecomposeScope>) {
586 let _teardown = runtime::enter_state_teardown_scope();
587 let host = self.slots_host();
588 let composer = Composer::for_pass(
589 self.parked_composer.take(),
590 Rc::clone(&self.composer_state),
591 Rc::clone(&host),
592 self.applier_host(),
593 runtime.clone(),
594 self.root,
595 );
596 composer.install(|composer| {
597 for scope in scopes.iter().filter(|scope| scope.is_derivation()) {
598 composer.recompose_group(scope);
599 }
600 });
601 self.park_composer(&host, composer);
602 scopes.retain(|scope| !scope.is_derivation());
603 }
604
605 fn park_composer(&mut self, host: &Rc<SlotsHost>, composer: Composer) {
609 let Some(parked) = composer.park() else {
610 return;
611 };
612 self.parked_composer = if Rc::ptr_eq(host, &self.slots) {
613 Some(parked)
614 } else {
615 Composer::for_pass(
616 Some(parked),
617 Rc::clone(&self.composer_state),
618 self.slots_host(),
619 self.applier_host(),
620 self.runtime_handle(),
621 self.root,
622 )
623 .park()
624 };
625 }
626
627 fn dispose_forgotten_movables(&mut self) -> Result<(), NodeError> {
628 let ids = self.runtime.take_forgotten_movables();
629 if ids.is_empty() {
630 return Ok(());
631 }
632 self.forget_movables(&ids)
633 }
634
635 #[inline(never)]
638 fn forget_movables(&mut self, ids: &[Key]) -> Result<(), NodeError> {
639 let runtime_handle = self.runtime_handle();
640 let _teardown = runtime::enter_state_teardown_scope();
641 let host = self.slots_host();
642 let composer = Composer::new_with_shared_state(
643 Rc::clone(&self.composer_state),
644 Rc::clone(&host),
645 self.applier_host(),
646 runtime_handle.clone(),
647 self.root,
648 );
649 composer.install(|composer| composer.forget_movables(ids))?;
650 self.apply_commands_and_updates_for_host(&host, &runtime_handle, &composer)
651 }
652
653 pub fn flush_pending_node_updates(&mut self) -> Result<(), NodeError> {
655 let updates = self.runtime.take_updates();
656 let mut applier = self.applier.borrow_dyn();
657 for update in updates {
658 update.apply(&mut *applier)?;
659 }
660 Ok(())
661 }
662}
663
664#[expect(clippy::print_stderr, reason = "a scope telemetry threshold asks")]
667fn recompose_timed(composer: &Composer, scopes: &[RecomposeScope], threshold_ms: f64) {
668 for scope in scopes {
669 let start = Instant::now();
670 composer.recompose_group(scope);
671 let elapsed_ms = start.elapsed().as_secs_f64() * 1000.0;
672 if elapsed_ms >= threshold_ms {
673 eprintln!(
674 "[recompose-scope-telemetry] scope_id={} label={:?} elapsed_ms={elapsed_ms:.3} invalidation_sources={:?}",
675 scope.id(),
676 debug_scope_label(scope.id()),
677 debug_scope_invalidation_sources(scope.id())
678 );
679 }
680 }
681}
682
683enum Batch {
685 Invalid,
687 Waiting(PausableContent),
689}
690
691fn requeue_scopes(runtime_handle: &RuntimeHandle, batch: &Batch, scopes: &[RecomposeScope]) {
694 for scope in scopes {
695 match batch {
696 Batch::Invalid => runtime_handle.requeue_invalid_scope(scope),
697 Batch::Waiting(content) => content.keep_waiting(scope),
698 }
699 }
700}
701
702impl<A: Applier + 'static> Drop for Composition<A> {
703 fn drop(&mut self) {
704 #[cfg(target_os = "android")]
705 self.runtime.restore_thread_state();
706 self.teardown = Some(runtime::enter_state_teardown_scope());
707 }
708}
709
710#[cfg(any(test, feature = "leak-debug"))]
713#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
714pub struct CompositionPassDebugStats {
715 pub commands_len: usize,
717 pub commands_cap: usize,
719 pub command_payload_len_bytes: usize,
721 pub command_payload_cap_bytes: usize,
723 pub sync_children_len: usize,
725 pub sync_children_cap: usize,
727 pub sync_child_ids_len: usize,
729 pub sync_child_ids_cap: usize,
731 pub side_effects_len: usize,
733 pub side_effects_cap: usize,
735}
736
737#[cfg(any(test, feature = "leak-debug"))]
738impl CompositionPassDebugStats {
739 fn record(&mut self, commands: &crate::CommandQueue, side_effects: &Vec<Box<dyn FnOnce()>>) {
740 self.commands_len = self.commands_len.max(commands.len());
741 self.commands_cap = self.commands_cap.max(commands.capacity());
742 self.command_payload_len_bytes = self
743 .command_payload_len_bytes
744 .max(commands.payload_len_bytes());
745 self.command_payload_cap_bytes = self
746 .command_payload_cap_bytes
747 .max(commands.payload_capacity_bytes());
748 self.sync_children_len = self.sync_children_len.max(commands.sync_children.len());
749 self.sync_children_cap = self
750 .sync_children_cap
751 .max(commands.sync_children.capacity());
752 self.sync_child_ids_len = self.sync_child_ids_len.max(commands.sync_child_ids.len());
753 self.sync_child_ids_cap = self
754 .sync_child_ids_cap
755 .max(commands.sync_child_ids.capacity());
756 self.side_effects_len = self.side_effects_len.max(side_effects.len());
757 self.side_effects_cap = self.side_effects_cap.max(side_effects.capacity());
758 }
759}