1use crate::collections::map::HashMap;
2use crate::collections::map::HashSet;
3use crate::state::{MutationPolicy, NeverEqual};
4use crate::MutableStateInner;
5use std::any::Any;
6use std::cell::{Cell, RefCell};
7use std::collections::VecDeque;
8use std::future::Future;
9use std::pin::Pin;
10use std::rc::{Rc, Weak};
11use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
12use std::sync::{mpsc, Arc};
13use std::task::{Context, Poll, Waker};
14use std::thread::ThreadId;
15use std::thread_local;
16
17#[cfg(any(feature = "internal", test))]
18use crate::frame_clock::FrameClock;
19use crate::platform::RuntimeScheduler;
20use crate::{Applier, Command, FrameCallbackId, NodeError, RecomposeScopeInner, ScopeId};
21
22#[derive(Clone, Copy, PartialEq, Eq)]
23pub(crate) enum FrameCallbackKind {
24 Transient,
25 Perpetual,
26}
27
28enum UiMessage {
29 Task(Box<dyn FnOnce() + Send + 'static>),
30 Invoke { id: u64, value: Box<dyn Any + Send> },
31}
32
33type UiContinuation = Box<dyn Fn(Box<dyn Any>) -> bool + 'static>;
34type UiContinuationMap = HashMap<u64, UiContinuation>;
35
36struct TypedStateCell<T: Clone + 'static> {
37 inner: MutableStateInner<T>,
38}
39
40trait ScopeWatchCell {
41 fn unregister_scope(&self, scope_id: ScopeId);
42}
43
44impl<T: Clone + 'static> ScopeWatchCell for TypedStateCell<T> {
45 fn unregister_scope(&self, scope_id: ScopeId) {
46 self.inner.unregister_scope(scope_id);
47 }
48}
49
50struct StateArenaSlot {
51 generation: u32,
52 cell: Option<Rc<dyn Any>>,
53 watcher_cell: Option<Rc<dyn ScopeWatchCell>>,
54 lease: Option<Weak<StateHandleLease>>,
55}
56
57#[derive(Default)]
58struct StateArenaInner {
59 cells: Vec<StateArenaSlot>,
60 free: Vec<u32>,
61}
62
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
64pub struct StateArenaDebugStats {
65 pub cells_len: usize,
66 pub cells_cap: usize,
67 pub free_len: usize,
68 pub free_cap: usize,
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
72pub struct RuntimeDebugStats {
73 pub node_updates_len: usize,
74 pub node_updates_cap: usize,
75 pub invalid_scopes_len: usize,
76 pub invalid_scopes_cap: usize,
77 pub scope_queue_len: usize,
78 pub scope_queue_cap: usize,
79 pub frame_callbacks_len: usize,
80 pub frame_callbacks_cap: usize,
81 pub local_tasks_len: usize,
82 pub local_tasks_cap: usize,
83 pub ui_conts_len: usize,
84 pub ui_conts_cap: usize,
85 pub tasks_len: usize,
86 pub tasks_cap: usize,
87 pub external_state_owners_len: usize,
88 pub external_state_owners_cap: usize,
89 pub ui_dispatcher_pending: usize,
90}
91
92#[derive(Default)]
93pub(crate) struct StateArena {
94 inner: RefCell<StateArenaInner>,
95}
96
97impl StateArena {
98 pub(crate) fn alloc<T: Clone + 'static>(&self, value: T, runtime: RuntimeHandle) -> StateId {
99 self.alloc_with_policy(value, runtime, Arc::new(NeverEqual))
100 }
101
102 pub(crate) fn alloc_with_policy<T: Clone + 'static>(
103 &self,
104 value: T,
105 runtime: RuntimeHandle,
106 policy: Arc<dyn MutationPolicy<T>>,
107 ) -> StateId {
108 let (slot, generation) = {
109 let mut inner = self.inner.borrow_mut();
110 loop {
111 let Some(slot) = inner.free.pop() else {
112 let slot = inner.cells.len() as u32;
113 inner.cells.push(StateArenaSlot {
114 generation: 0,
115 cell: None,
116 watcher_cell: None,
117 lease: None,
118 });
119 break (slot, 0);
120 };
121
122 let Some(entry) = inner.cells.get_mut(slot as usize) else {
123 continue;
124 };
125 if entry.cell.is_some() {
126 continue;
127 }
128
129 entry.watcher_cell = None;
130 entry.lease = None;
131 entry.generation = entry.generation.wrapping_add(1);
132 break (slot, entry.generation);
133 }
134 };
135 let id = StateId::new(slot, generation);
136 let inner = MutableStateInner::new_with_policy(value, runtime.clone(), policy);
137 inner.install_snapshot_observer(id);
138 let typed_cell = Rc::new(TypedStateCell { inner });
139 let cell: Rc<dyn Any> = typed_cell.clone();
140 let watcher_cell: Rc<dyn ScopeWatchCell> = typed_cell;
141 let mut arena = self.inner.borrow_mut();
142 let slot_entry = &mut arena.cells[slot as usize];
143 slot_entry.cell = Some(cell);
144 slot_entry.watcher_cell = Some(watcher_cell);
145 id
146 }
147
148 fn get_cell_opt(&self, id: StateId) -> Option<Rc<dyn Any>> {
149 self.inner
150 .borrow()
151 .cells
152 .get(id.slot_index())
153 .filter(|cell| cell.generation == id.generation())
154 .and_then(|cell| cell.cell.as_ref())
155 .cloned()
156 }
157
158 fn get_typed<T: Clone + 'static>(&self, id: StateId) -> Rc<TypedStateCell<T>> {
159 match self.get_cell_opt(id) {
160 None => panic!(
161 "state cell missing: slot={}, gen={}, expected={}",
162 id.slot(),
163 id.generation(),
164 std::any::type_name::<T>(),
165 ),
166 Some(cell) => Rc::downcast::<TypedStateCell<T>>(cell).unwrap_or_else(|_| {
167 panic!(
168 "state cell type mismatch: slot={}, gen={}, expected={}",
169 id.slot(),
170 id.generation(),
171 std::any::type_name::<T>(),
172 )
173 }),
174 }
175 }
176
177 fn get_typed_opt<T: Clone + 'static>(&self, id: StateId) -> Option<Rc<TypedStateCell<T>>> {
178 Rc::downcast::<TypedStateCell<T>>(self.get_cell_opt(id)?).ok()
179 }
180
181 pub(crate) fn with_typed<T: Clone + 'static, R>(
182 &self,
183 id: StateId,
184 f: impl FnOnce(&MutableStateInner<T>) -> R,
185 ) -> R {
186 let cell = self.get_typed::<T>(id);
187 f(&cell.inner)
188 }
189
190 pub(crate) fn with_typed_opt<T: Clone + 'static, R>(
191 &self,
192 id: StateId,
193 f: impl FnOnce(&MutableStateInner<T>) -> R,
194 ) -> Option<R> {
195 let cell = self.get_typed_opt::<T>(id)?;
196 Some(f(&cell.inner))
197 }
198
199 pub(crate) fn release(&self, id: StateId) {
200 let cell = {
201 let mut inner = self.inner.borrow_mut();
202 let Some(slot) = inner.cells.get_mut(id.slot_index()) else {
203 return;
204 };
205 if slot.generation != id.generation() {
206 return;
207 }
208 slot.lease = None;
209 slot.watcher_cell = None;
210 let cell = slot.cell.take();
211 if cell.is_some() {
212 inner.free.push(id.slot());
213 }
214 cell
215 };
216 drop(cell);
217 }
218
219 pub(crate) fn stats(&self) -> (usize, usize) {
220 let inner = self.inner.borrow();
221 (inner.cells.len(), inner.free.len())
222 }
223
224 pub(crate) fn debug_stats(&self) -> StateArenaDebugStats {
225 let inner = self.inner.borrow();
226 StateArenaDebugStats {
227 cells_len: inner.cells.len(),
228 cells_cap: inner.cells.capacity(),
229 free_len: inner.free.len(),
230 free_cap: inner.free.capacity(),
231 }
232 }
233
234 pub(crate) fn unregister_scope(&self, id: StateId, scope_id: ScopeId) {
235 let watcher_cell = {
236 let inner = self.inner.borrow();
237 inner
238 .cells
239 .get(id.slot_index())
240 .filter(|slot| slot.generation == id.generation())
241 .and_then(|slot| slot.watcher_cell.as_ref())
242 .cloned()
243 };
244 if let Some(watcher_cell) = watcher_cell {
245 watcher_cell.unregister_scope(scope_id);
246 }
247 }
248
249 pub(crate) fn register_lease(&self, id: StateId, lease: &Rc<StateHandleLease>) {
250 let mut inner = self.inner.borrow_mut();
251 let Some(slot) = inner.cells.get_mut(id.slot_index()) else {
252 return;
253 };
254 if slot.generation != id.generation() {
255 return;
256 }
257 slot.lease = Some(Rc::downgrade(lease));
258 }
259
260 pub(crate) fn retain_lease(&self, id: StateId) -> Option<Rc<StateHandleLease>> {
261 let inner = self.inner.borrow();
262 let slot = inner.cells.get(id.slot_index())?;
263 if slot.generation != id.generation() {
264 return None;
265 }
266 slot.lease.as_ref()?.upgrade()
267 }
268}
269
270#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
271pub struct StateId {
272 slot: u32,
273 generation: u32,
274}
275
276impl StateId {
277 const fn new(slot: u32, generation: u32) -> Self {
278 Self { slot, generation }
279 }
280
281 pub(crate) const fn slot(self) -> u32 {
282 self.slot
283 }
284
285 pub(crate) const fn slot_index(self) -> usize {
286 self.slot as usize
287 }
288
289 pub(crate) const fn generation(self) -> u32 {
290 self.generation
291 }
292}
293
294#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
295pub struct RuntimeId(u32);
296
297impl RuntimeId {
298 fn next() -> Self {
299 NEXT_RUNTIME_ID.with(|next| {
300 let id = next.get();
301 next.set(id.wrapping_add(1));
302 Self(id)
303 })
304 }
305}
306
307struct UiDispatcherInner {
308 scheduler: Arc<dyn RuntimeScheduler>,
309 tx: mpsc::Sender<UiMessage>,
310 pending: AtomicUsize,
311}
312
313impl UiDispatcherInner {
314 fn new(scheduler: Arc<dyn RuntimeScheduler>, tx: mpsc::Sender<UiMessage>) -> Self {
315 Self {
316 scheduler,
317 tx,
318 pending: AtomicUsize::new(0),
319 }
320 }
321
322 fn post(&self, task: impl FnOnce() + Send + 'static) {
323 self.pending.fetch_add(1, Ordering::SeqCst);
324 if self.tx.send(UiMessage::Task(Box::new(task))).is_ok() {
325 self.scheduler.schedule_frame();
326 } else {
327 self.pending.fetch_sub(1, Ordering::SeqCst);
328 }
329 }
330
331 fn post_invoke(&self, id: u64, value: Box<dyn Any + Send>) {
332 self.pending.fetch_add(1, Ordering::SeqCst);
333 if self.tx.send(UiMessage::Invoke { id, value }).is_ok() {
334 self.scheduler.schedule_frame();
335 } else {
336 self.pending.fetch_sub(1, Ordering::SeqCst);
337 }
338 }
339
340 fn has_pending(&self) -> bool {
341 self.pending.load(Ordering::SeqCst) > 0
342 }
343}
344
345struct PendingGuard<'a> {
346 counter: &'a AtomicUsize,
347}
348
349impl<'a> PendingGuard<'a> {
350 fn new(counter: &'a AtomicUsize) -> Self {
351 Self { counter }
352 }
353}
354
355impl<'a> Drop for PendingGuard<'a> {
356 fn drop(&mut self) {
357 let mut current = self.counter.load(Ordering::SeqCst);
358 loop {
359 if current == 0 {
360 return;
361 }
362 match self.counter.compare_exchange(
363 current,
364 current - 1,
365 Ordering::SeqCst,
366 Ordering::SeqCst,
367 ) {
368 Ok(_) => return,
369 Err(next) => current = next,
370 }
371 }
372 }
373}
374
375#[derive(Clone)]
376pub struct UiDispatcher {
377 inner: Arc<UiDispatcherInner>,
378}
379
380impl UiDispatcher {
381 fn new(inner: Arc<UiDispatcherInner>) -> Self {
382 Self { inner }
383 }
384
385 pub fn post(&self, task: impl FnOnce() + Send + 'static) {
386 self.inner.post(task);
387 }
388
389 pub fn post_invoke<T>(&self, id: u64, value: T)
390 where
391 T: Send + 'static,
392 {
393 self.inner.post_invoke(id, Box::new(value));
394 }
395
396 pub fn has_pending(&self) -> bool {
397 self.inner.has_pending()
398 }
399}
400
401struct RuntimeInner {
402 scheduler: Arc<dyn RuntimeScheduler>,
403 needs_frame: RefCell<bool>,
404 node_updates: RefCell<Vec<Command>>,
405 invalid_scopes: RefCell<HashSet<ScopeId>>,
406 scope_queue: RefCell<Vec<(ScopeId, Weak<RecomposeScopeInner>)>>,
407 frame_callbacks: RefCell<VecDeque<FrameCallbackEntry>>,
408 next_frame_callback_id: Cell<u64>,
409 last_frame_time_nanos: Cell<Option<u64>>,
410 ui_dispatcher: Arc<UiDispatcherInner>,
411 ui_rx: RefCell<mpsc::Receiver<UiMessage>>,
412 local_tasks: RefCell<VecDeque<Box<dyn FnOnce() + 'static>>>,
413 ui_conts: RefCell<UiContinuationMap>,
414 next_cont_id: Cell<u64>,
415 ui_thread_id: ThreadId,
416 tasks: RefCell<Vec<TaskEntry>>,
417 next_task_id: Cell<u64>,
418 state_arena: StateArena,
419 external_state_owners: RefCell<HashMap<StateId, Rc<StateHandleLease>>>,
420 live_recompose_scope_count: Cell<usize>,
421 runtime_id: RuntimeId,
422}
423
424struct TaskEntry {
425 id: u64,
426 label: String,
427 future: Pin<Box<dyn Future<Output = ()> + 'static>>,
428 runnable: Arc<AtomicBool>,
439 waker: Waker,
442}
443
444thread_local! {
445 static NEXT_TASK_LABEL: RefCell<Option<String>> = const { RefCell::new(None) };
446}
447
448pub fn label_next_ui_task(label: impl Into<String>) {
449 NEXT_TASK_LABEL.with(|held| *held.borrow_mut() = Some(label.into()));
450}
451
452impl RuntimeInner {
453 fn new(scheduler: Arc<dyn RuntimeScheduler>) -> Self {
454 let (tx, rx) = mpsc::channel();
455 let dispatcher = Arc::new(UiDispatcherInner::new(scheduler.clone(), tx));
456 Self {
457 scheduler,
458 needs_frame: RefCell::new(false),
459 node_updates: RefCell::new(Vec::new()),
460 invalid_scopes: RefCell::new(HashSet::default()),
461 scope_queue: RefCell::new(Vec::new()),
462 frame_callbacks: RefCell::new(VecDeque::new()),
463 next_frame_callback_id: Cell::new(1),
464 last_frame_time_nanos: Cell::new(None),
465 ui_dispatcher: dispatcher,
466 ui_rx: RefCell::new(rx),
467 local_tasks: RefCell::new(VecDeque::new()),
468 ui_conts: RefCell::new(UiContinuationMap::default()),
469 next_cont_id: Cell::new(1),
470 ui_thread_id: std::thread::current().id(),
471 tasks: RefCell::new(Vec::new()),
472 next_task_id: Cell::new(1),
473 state_arena: StateArena::default(),
474 external_state_owners: RefCell::new(HashMap::default()),
475 live_recompose_scope_count: Cell::new(0),
476 runtime_id: RuntimeId::next(),
477 }
478 }
479
480 fn schedule(&self) {
481 *self.needs_frame.borrow_mut() = true;
482 self.scheduler.schedule_frame();
483 }
484
485 fn enqueue_update(&self, command: Command) {
486 self.node_updates.borrow_mut().push(command);
487 self.schedule(); }
489
490 fn take_updates(&self) -> Vec<Command> {
491 let updates = self.node_updates.borrow_mut().drain(..).collect::<Vec<_>>();
492 updates
493 }
494
495 fn has_updates(&self) -> bool {
496 !self.node_updates.borrow().is_empty() || self.has_invalid_scopes()
497 }
498
499 fn register_invalid_scope(&self, id: ScopeId, scope: Weak<RecomposeScopeInner>) {
500 let mut invalid = self.invalid_scopes.borrow_mut();
501 if invalid.insert(id) {
502 self.scope_queue.borrow_mut().push((id, scope));
503 self.schedule();
504 }
505 }
506
507 fn requeue_invalid_scope(&self, id: ScopeId, scope: Weak<RecomposeScopeInner>) {
508 if self.invalid_scopes.borrow().contains(&id) {
509 self.scope_queue.borrow_mut().push((id, scope));
510 self.schedule();
511 }
512 }
513
514 fn mark_scope_recomposed(&self, id: ScopeId) {
515 self.invalid_scopes.borrow_mut().remove(&id);
516 }
517
518 fn take_invalidated_scopes(&self) -> Vec<(ScopeId, Weak<RecomposeScopeInner>)> {
519 let mut queue = self.scope_queue.borrow_mut();
520 if queue.is_empty() {
521 return Vec::new();
522 }
523 let pending: Vec<_> = queue.drain(..).collect();
524 drop(queue);
525 let invalid = self.invalid_scopes.borrow();
526 pending
527 .into_iter()
528 .filter(|(id, _)| invalid.contains(id))
529 .collect()
530 }
531
532 fn has_invalid_scopes(&self) -> bool {
533 !self.invalid_scopes.borrow().is_empty()
534 }
535
536 fn increment_live_recompose_scope_count(&self) {
537 self.live_recompose_scope_count
538 .set(self.live_recompose_scope_count.get().saturating_add(1));
539 }
540
541 fn decrement_live_recompose_scope_count(&self) {
542 self.live_recompose_scope_count
543 .set(self.live_recompose_scope_count.get().saturating_sub(1));
544 }
545
546 fn live_recompose_scope_count(&self) -> usize {
547 self.live_recompose_scope_count.get()
548 }
549
550 fn has_frame_callbacks(&self) -> bool {
551 !self.frame_callbacks.borrow().is_empty()
552 }
553
554 fn has_transient_frame_callbacks(&self) -> bool {
555 self.frame_callbacks
556 .borrow()
557 .iter()
558 .any(|entry| entry.kind == FrameCallbackKind::Transient)
559 }
560
561 fn enqueue_ui_task(&self, task: Box<dyn FnOnce() + 'static>) {
566 self.local_tasks.borrow_mut().push_back(task);
567 self.schedule();
568 }
569
570 fn spawn_ui_task(&self, future: Pin<Box<dyn Future<Output = ()> + 'static>>) -> u64 {
571 let id = self.next_task_id.get();
572 self.next_task_id.set(id + 1);
573 let label = NEXT_TASK_LABEL
574 .with(|held| held.borrow_mut().take())
575 .unwrap_or_else(|| "unnamed".to_string());
576 let runnable = Arc::new(AtomicBool::new(true));
577 let waker = RuntimeTaskWaker::new(self, Arc::clone(&runnable)).into_waker();
578 self.tasks.borrow_mut().push(TaskEntry {
579 id,
580 label,
581 future,
582 runnable,
583 waker,
584 });
585 self.schedule();
586 id
587 }
588
589 fn cancel_task(&self, id: u64) {
590 let mut tasks = self.tasks.borrow_mut();
591 if tasks.iter().any(|entry| entry.id == id) {
592 tasks.retain(|entry| entry.id != id);
593 }
594 }
595
596 fn poll_async_tasks(&self) -> bool {
597 let mut tasks_ref = self.tasks.borrow_mut();
598 let tasks = std::mem::take(&mut *tasks_ref);
599 drop(tasks_ref);
600 let mut pending = Vec::with_capacity(tasks.len());
601 let mut made_progress = false;
602 for mut entry in tasks.into_iter() {
603 if !entry.runnable.swap(false, Ordering::AcqRel) {
607 pending.push(entry);
608 continue;
609 }
610 let mut cx = Context::from_waker(&entry.waker);
611 match entry.future.as_mut().poll(&mut cx) {
612 Poll::Ready(()) => {
613 made_progress = true;
614 }
615 Poll::Pending => {
616 pending.push(entry);
617 }
618 }
619 }
620 if !pending.is_empty() {
621 self.tasks.borrow_mut().extend(pending);
622 }
623 made_progress
624 }
625
626 fn drain_ui(&self) {
627 loop {
628 let mut executed = false;
629
630 {
631 let rx = &mut *self.ui_rx.borrow_mut();
632 for message in rx.try_iter() {
633 executed = true;
634 let _guard = PendingGuard::new(&self.ui_dispatcher.pending);
635 match message {
636 UiMessage::Task(task) => {
637 task();
638 }
639 UiMessage::Invoke { id, value } => {
640 self.invoke_ui_cont(id, value);
641 }
642 }
643 }
644 }
645
646 loop {
647 let task = {
648 let mut local = self.local_tasks.borrow_mut();
649 local.pop_front()
650 };
651
652 match task {
653 Some(task) => {
654 executed = true;
655 task();
656 }
657 None => break,
658 }
659 }
660
661 if self.poll_async_tasks() {
662 executed = true;
663 }
664
665 if !executed {
666 break;
667 }
668 }
669
670 self.clear_needs_frame_if_idle();
675 }
676
677 fn has_pending_ui(&self) -> bool {
678 let local_pending = self
679 .local_tasks
680 .try_borrow()
681 .map(|tasks| !tasks.is_empty())
682 .unwrap_or(true);
683
684 local_pending || self.ui_dispatcher.has_pending() || self.has_runnable_tasks()
685 }
686
687 fn has_runnable_tasks(&self) -> bool {
699 self.tasks
700 .try_borrow()
701 .map(|tasks| {
702 tasks
703 .iter()
704 .any(|task| task.runnable.load(Ordering::Acquire))
705 })
706 .unwrap_or(true)
707 }
708
709 fn register_ui_cont<T: 'static>(&self, f: impl FnOnce(T) + 'static) -> u64 {
710 debug_assert_eq!(
711 std::thread::current().id(),
712 self.ui_thread_id,
713 "UI continuation registered off the runtime thread",
714 );
715 let id = self.next_cont_id.get();
716 self.next_cont_id.set(id + 1);
717 let callback = RefCell::new(Some(f));
718 self.ui_conts.borrow_mut().insert(
719 id,
720 Box::new(move |value: Box<dyn Any>| {
721 let Ok(value) = value.downcast::<T>() else {
722 return false;
723 };
724 let Some(slot) = callback.borrow_mut().take() else {
725 return true;
726 };
727 slot(*value);
728 true
729 }),
730 );
731 id
732 }
733
734 fn invoke_ui_cont(&self, id: u64, value: Box<dyn Any + Send>) {
735 debug_assert_eq!(
736 std::thread::current().id(),
737 self.ui_thread_id,
738 "UI continuation invoked off the runtime thread",
739 );
740 let callback = { self.ui_conts.borrow_mut().remove(&id) };
741 if let Some(callback) = callback {
742 let value: Box<dyn Any> = value;
743 if !callback(value) {
744 self.ui_conts.borrow_mut().insert(id, callback);
745 }
746 }
747 }
748
749 fn cancel_ui_cont(&self, id: u64) {
750 self.ui_conts.borrow_mut().remove(&id);
751 }
752
753 fn register_frame_callback(
754 &self,
755 kind: FrameCallbackKind,
756 callback: Box<dyn FnOnce(u64) + 'static>,
757 ) -> FrameCallbackId {
758 let id = self.next_frame_callback_id.get();
759 self.next_frame_callback_id.set(id + 1);
760 self.frame_callbacks
761 .borrow_mut()
762 .push_back(FrameCallbackEntry {
763 id,
764 kind,
765 callback: Some(callback),
766 });
767 self.schedule();
768 id
769 }
770
771 fn cancel_frame_callback(&self, id: FrameCallbackId) {
772 let mut callbacks = self.frame_callbacks.borrow_mut();
773 if let Some(index) = callbacks.iter().position(|entry| entry.id == id) {
774 callbacks.remove(index);
775 }
776 drop(callbacks);
777 self.clear_needs_frame_if_idle();
778 }
779
780 fn clear_needs_frame_if_idle(&self) {
787 if !self.has_invalid_scopes()
788 && !self.has_updates()
789 && !self.has_frame_callbacks()
790 && !self.has_pending_ui()
791 {
792 *self.needs_frame.borrow_mut() = false;
793 }
794 }
795
796 fn drain_frame_callbacks(&self, frame_time_nanos: u64) {
797 self.last_frame_time_nanos.set(Some(frame_time_nanos));
798 let mut callbacks = self.frame_callbacks.borrow_mut();
799 let mut pending: Vec<Box<dyn FnOnce(u64) + 'static>> = Vec::with_capacity(callbacks.len());
800 while let Some(mut entry) = callbacks.pop_front() {
801 if let Some(callback) = entry.callback.take() {
802 pending.push(callback);
803 }
804 }
805 drop(callbacks);
806
807 if !pending.is_empty() {
812 let _ = crate::run_in_mutable_snapshot(|| {
813 for callback in pending {
814 callback(frame_time_nanos);
815 }
816 });
817 }
818
819 self.clear_needs_frame_if_idle();
820 }
821
822 fn debug_stats(&self) -> RuntimeDebugStats {
823 let node_updates = self.node_updates.borrow();
824 let invalid_scopes = self.invalid_scopes.borrow();
825 let scope_queue = self.scope_queue.borrow();
826 let frame_callbacks = self.frame_callbacks.borrow();
827 let local_tasks = self.local_tasks.borrow();
828 let ui_conts = self.ui_conts.borrow();
829 let tasks = self.tasks.borrow();
830 let external_state_owners = self.external_state_owners.borrow();
831
832 RuntimeDebugStats {
833 node_updates_len: node_updates.len(),
834 node_updates_cap: node_updates.capacity(),
835 invalid_scopes_len: invalid_scopes.len(),
836 invalid_scopes_cap: invalid_scopes.capacity(),
837 scope_queue_len: scope_queue.len(),
838 scope_queue_cap: scope_queue.capacity(),
839 frame_callbacks_len: frame_callbacks.len(),
840 frame_callbacks_cap: frame_callbacks.capacity(),
841 local_tasks_len: local_tasks.len(),
842 local_tasks_cap: local_tasks.capacity(),
843 ui_conts_len: ui_conts.len(),
844 ui_conts_cap: ui_conts.capacity(),
845 tasks_len: tasks.len(),
846 tasks_cap: tasks.capacity(),
847 external_state_owners_len: external_state_owners.len(),
848 external_state_owners_cap: external_state_owners.capacity(),
849 ui_dispatcher_pending: self.ui_dispatcher.pending.load(Ordering::SeqCst),
850 }
851 }
852}
853
854#[derive(Clone)]
855pub struct Runtime {
856 inner: Rc<RuntimeInner>,
857}
858
859impl Runtime {
860 pub fn new(scheduler: Arc<dyn RuntimeScheduler>) -> Self {
861 let inner = Rc::new(RuntimeInner::new(scheduler));
862 let runtime = Self { inner };
863 let handle = runtime.handle();
864 register_runtime_handle(&handle);
865 LAST_RUNTIME.with(|slot| *slot.borrow_mut() = Some(handle));
866 runtime
867 }
868
869 pub fn handle(&self) -> RuntimeHandle {
870 RuntimeHandle {
871 inner: Rc::downgrade(&self.inner),
872 dispatcher: UiDispatcher::new(self.inner.ui_dispatcher.clone()),
873 ui_thread_id: self.inner.ui_thread_id,
874 id: self.inner.runtime_id,
875 }
876 }
877
878 pub fn has_updates(&self) -> bool {
879 self.inner.has_updates()
880 }
881
882 pub fn needs_frame(&self) -> bool {
883 *self.inner.needs_frame.borrow() || self.inner.has_runnable_tasks()
892 }
893
894 pub fn set_needs_frame(&self, value: bool) {
895 *self.inner.needs_frame.borrow_mut() = value;
896 }
897
898 pub fn last_frame_time_nanos(&self) -> Option<u64> {
903 self.inner.last_frame_time_nanos.get()
904 }
905
906 #[cfg(any(feature = "internal", test))]
907 pub fn frame_clock(&self) -> FrameClock {
908 FrameClock::new(self.handle())
909 }
910}
911
912impl Drop for Runtime {
913 fn drop(&mut self) {
914 if Rc::strong_count(&self.inner) != 1 {
915 return;
916 }
917 unregister_runtime_handle(self.inner.runtime_id);
918 LAST_RUNTIME.with(|slot| {
919 let should_clear = slot
920 .borrow()
921 .as_ref()
922 .is_some_and(|handle| handle.id() == self.inner.runtime_id);
923 if should_clear {
924 *slot.borrow_mut() = None;
925 }
926 });
927 }
928}
929
930#[derive(Default)]
931pub struct DefaultScheduler;
932
933impl RuntimeScheduler for DefaultScheduler {
934 fn schedule_frame(&self) {}
935}
936
937#[cfg(test)]
938#[derive(Default)]
939pub struct TestScheduler;
940
941#[cfg(test)]
942impl RuntimeScheduler for TestScheduler {
943 fn schedule_frame(&self) {}
944}
945
946#[cfg(test)]
947pub struct TestRuntime {
948 runtime: Runtime,
949}
950
951#[cfg(test)]
952impl Default for TestRuntime {
953 fn default() -> Self {
954 Self::new()
955 }
956}
957
958#[cfg(test)]
959impl TestRuntime {
960 pub fn new() -> Self {
961 Self {
962 runtime: Runtime::new(Arc::new(TestScheduler)),
963 }
964 }
965
966 pub fn handle(&self) -> RuntimeHandle {
967 self.runtime.handle()
968 }
969}
970
971#[derive(Clone)]
972pub struct RuntimeHandle {
973 inner: Weak<RuntimeInner>,
974 dispatcher: UiDispatcher,
975 ui_thread_id: ThreadId,
976 id: RuntimeId,
977}
978
979pub struct TaskHandle {
980 id: u64,
981 runtime: RuntimeHandle,
982}
983
984struct DeferredStateRelease {
985 runtime: RuntimeHandle,
986 id: StateId,
987}
988
989pub(crate) struct StateHandleLease {
990 id: StateId,
991 runtime: RuntimeHandle,
992}
993
994impl StateHandleLease {
995 pub(crate) fn id(&self) -> StateId {
996 self.id
997 }
998
999 pub(crate) fn runtime(&self) -> RuntimeHandle {
1000 self.runtime.clone()
1001 }
1002}
1003
1004impl Drop for StateHandleLease {
1005 fn drop(&mut self) {
1006 defer_state_release(self.runtime.clone(), self.id);
1007 }
1008}
1009
1010impl RuntimeHandle {
1011 pub fn id(&self) -> RuntimeId {
1012 self.id
1013 }
1014
1015 pub(crate) fn alloc_state<T: Clone + 'static>(&self, value: T) -> Rc<StateHandleLease> {
1016 let id = self.with_state_arena(|arena| arena.alloc(value, self.clone()));
1017 let lease = Rc::new(StateHandleLease {
1018 id,
1019 runtime: self.clone(),
1020 });
1021 self.with_state_arena(|arena| arena.register_lease(id, &lease));
1022 lease
1023 }
1024
1025 pub(crate) fn alloc_state_with_policy<T: Clone + 'static>(
1026 &self,
1027 value: T,
1028 policy: Arc<dyn MutationPolicy<T>>,
1029 ) -> Rc<StateHandleLease> {
1030 let id =
1031 self.with_state_arena(|arena| arena.alloc_with_policy(value, self.clone(), policy));
1032 let lease = Rc::new(StateHandleLease {
1033 id,
1034 runtime: self.clone(),
1035 });
1036 self.with_state_arena(|arena| arena.register_lease(id, &lease));
1037 lease
1038 }
1039
1040 pub(crate) fn alloc_persistent_state<T: Clone + 'static>(
1041 &self,
1042 value: T,
1043 ) -> crate::MutableState<T> {
1044 let lease = self.alloc_state(value);
1045 if let Some(inner) = self.inner.upgrade() {
1046 inner
1047 .external_state_owners
1048 .borrow_mut()
1049 .insert(lease.id(), Rc::clone(&lease));
1050 }
1051 crate::MutableState::from_lease(&lease)
1052 }
1053
1054 pub(crate) fn retain_state_lease(&self, id: StateId) -> Option<Rc<StateHandleLease>> {
1055 self.with_state_arena(|arena| arena.retain_lease(id))
1056 }
1057
1058 pub(crate) fn with_state_arena<R>(&self, f: impl FnOnce(&StateArena) -> R) -> R {
1059 self.try_with_state_arena(f)
1060 .unwrap_or_else(|| panic!("runtime dropped"))
1061 }
1062
1063 pub(crate) fn try_with_state_arena<R>(&self, f: impl FnOnce(&StateArena) -> R) -> Option<R> {
1064 self.inner.upgrade().map(|inner| f(&inner.state_arena))
1065 }
1066
1067 fn release_state_immediate(&self, id: StateId) {
1068 if let Some(inner) = self.inner.upgrade() {
1069 inner.state_arena.release(id);
1070 }
1071 }
1072
1073 pub fn state_arena_stats(&self) -> (usize, usize) {
1074 self.try_with_state_arena(StateArena::stats)
1075 .unwrap_or_default()
1076 }
1077
1078 pub fn state_arena_debug_stats(&self) -> StateArenaDebugStats {
1079 self.try_with_state_arena(StateArena::debug_stats)
1080 .unwrap_or_default()
1081 }
1082
1083 pub fn debug_stats(&self) -> RuntimeDebugStats {
1084 self.inner
1085 .upgrade()
1086 .map(|inner| inner.debug_stats())
1087 .unwrap_or_default()
1088 }
1089
1090 pub fn live_ui_task_labels(&self) -> Vec<(u64, String)> {
1091 self.inner
1092 .upgrade()
1093 .map(|inner| {
1094 inner
1095 .tasks
1096 .borrow()
1097 .iter()
1098 .map(|entry| (entry.id, entry.label.clone()))
1099 .collect()
1100 })
1101 .unwrap_or_default()
1102 }
1103
1104 pub(crate) fn unregister_state_scope(&self, id: StateId, scope_id: ScopeId) {
1105 if let Some(inner) = self.inner.upgrade() {
1106 inner.state_arena.unregister_scope(id, scope_id);
1107 }
1108 }
1109
1110 pub fn schedule(&self) {
1111 if let Some(inner) = self.inner.upgrade() {
1112 inner.schedule();
1113 }
1114 }
1115
1116 pub(crate) fn enqueue_node_update(&self, command: Command) {
1117 if let Some(inner) = self.inner.upgrade() {
1118 inner.enqueue_update(command);
1119 }
1120 }
1121
1122 pub fn enqueue_ui_task(&self, task: Box<dyn FnOnce() + 'static>) {
1129 if let Some(inner) = self.inner.upgrade() {
1130 inner.enqueue_ui_task(task);
1131 } else {
1132 task();
1133 }
1134 }
1135
1136 pub fn spawn_ui<F>(&self, fut: F) -> Option<TaskHandle>
1137 where
1138 F: Future<Output = ()> + 'static,
1139 {
1140 self.inner.upgrade().map(|inner| {
1141 let id = inner.spawn_ui_task(Box::pin(fut));
1142 TaskHandle {
1143 id,
1144 runtime: self.clone(),
1145 }
1146 })
1147 }
1148
1149 pub fn cancel_task(&self, id: u64) {
1150 if let Some(inner) = self.inner.upgrade() {
1151 inner.cancel_task(id);
1152 }
1153 }
1154
1155 pub fn post_ui(&self, task: impl FnOnce() + Send + 'static) {
1160 self.dispatcher.post(task);
1161 }
1162
1163 pub fn register_ui_cont<T: 'static>(&self, f: impl FnOnce(T) + 'static) -> Option<u64> {
1164 self.inner.upgrade().map(|inner| inner.register_ui_cont(f))
1165 }
1166
1167 pub fn cancel_ui_cont(&self, id: u64) {
1168 if let Some(inner) = self.inner.upgrade() {
1169 inner.cancel_ui_cont(id);
1170 }
1171 }
1172
1173 pub fn drain_ui(&self) {
1174 if let Some(inner) = self.inner.upgrade() {
1175 inner.drain_ui();
1176 }
1177 }
1178
1179 pub fn has_pending_ui(&self) -> bool {
1180 self.inner
1181 .upgrade()
1182 .map(|inner| inner.has_pending_ui())
1183 .unwrap_or_else(|| self.dispatcher.has_pending())
1184 }
1185
1186 pub fn register_frame_callback(
1187 &self,
1188 callback: impl FnOnce(u64) + 'static,
1189 ) -> Option<FrameCallbackId> {
1190 self.inner.upgrade().map(|inner| {
1191 inner.register_frame_callback(FrameCallbackKind::Transient, Box::new(callback))
1192 })
1193 }
1194
1195 pub fn register_perpetual_frame_callback(
1196 &self,
1197 callback: impl FnOnce(u64) + 'static,
1198 ) -> Option<FrameCallbackId> {
1199 self.inner.upgrade().map(|inner| {
1200 inner.register_frame_callback(FrameCallbackKind::Perpetual, Box::new(callback))
1201 })
1202 }
1203
1204 pub fn cancel_frame_callback(&self, id: FrameCallbackId) {
1205 if let Some(inner) = self.inner.upgrade() {
1206 inner.cancel_frame_callback(id);
1207 }
1208 }
1209
1210 pub fn drain_frame_callbacks(&self, frame_time_nanos: u64) {
1211 if let Some(inner) = self.inner.upgrade() {
1212 inner.drain_frame_callbacks(frame_time_nanos);
1213 }
1214 }
1215
1216 pub fn last_frame_time_nanos(&self) -> Option<u64> {
1219 self.inner
1220 .upgrade()
1221 .and_then(|inner| inner.last_frame_time_nanos.get())
1222 }
1223
1224 #[cfg(any(feature = "internal", test))]
1225 pub fn frame_clock(&self) -> FrameClock {
1226 FrameClock::new(self.clone())
1227 }
1228
1229 pub fn set_needs_frame(&self, value: bool) {
1230 if let Some(inner) = self.inner.upgrade() {
1231 *inner.needs_frame.borrow_mut() = value;
1232 }
1233 }
1234
1235 pub(crate) fn take_updates(&self) -> Vec<Command> {
1236 self.inner
1237 .upgrade()
1238 .map(|inner| inner.take_updates())
1239 .unwrap_or_default()
1240 }
1241
1242 pub fn has_updates(&self) -> bool {
1243 self.inner
1244 .upgrade()
1245 .map(|inner| inner.has_updates())
1246 .unwrap_or(false)
1247 }
1248
1249 pub(crate) fn mark_scope_recomposed(&self, id: ScopeId) {
1250 if let Some(inner) = self.inner.upgrade() {
1251 inner.mark_scope_recomposed(id);
1252 }
1253 }
1254
1255 pub(crate) fn register_invalid_scope(&self, id: ScopeId, scope: Weak<RecomposeScopeInner>) {
1256 if let Some(inner) = self.inner.upgrade() {
1257 inner.register_invalid_scope(id, scope);
1258 }
1259 }
1260
1261 pub(crate) fn requeue_invalid_scope(&self, id: ScopeId, scope: Weak<RecomposeScopeInner>) {
1262 if let Some(inner) = self.inner.upgrade() {
1263 inner.requeue_invalid_scope(id, scope);
1264 }
1265 }
1266
1267 pub(crate) fn take_invalidated_scopes(&self) -> Vec<(ScopeId, Weak<RecomposeScopeInner>)> {
1268 self.inner
1269 .upgrade()
1270 .map(|inner| inner.take_invalidated_scopes())
1271 .unwrap_or_default()
1272 }
1273
1274 pub fn has_invalid_scopes(&self) -> bool {
1275 self.inner
1276 .upgrade()
1277 .map(|inner| inner.has_invalid_scopes())
1278 .unwrap_or(false)
1279 }
1280
1281 pub(crate) fn increment_live_recompose_scope_count(&self) {
1282 if let Some(inner) = self.inner.upgrade() {
1283 inner.increment_live_recompose_scope_count();
1284 }
1285 }
1286
1287 pub(crate) fn decrement_live_recompose_scope_count(&self) {
1288 if let Some(inner) = self.inner.upgrade() {
1289 inner.decrement_live_recompose_scope_count();
1290 }
1291 }
1292
1293 fn live_recompose_scope_count(&self) -> usize {
1294 self.inner
1295 .upgrade()
1296 .map(|inner| inner.live_recompose_scope_count())
1297 .unwrap_or_default()
1298 }
1299
1300 #[doc(hidden)]
1301 pub fn debug_invalid_scope_ids(&self) -> Vec<usize> {
1302 self.inner
1303 .upgrade()
1304 .map(|inner| inner.invalid_scopes.borrow().iter().copied().collect())
1305 .unwrap_or_default()
1306 }
1307
1308 pub fn has_frame_callbacks(&self) -> bool {
1309 self.inner
1310 .upgrade()
1311 .map(|inner| inner.has_frame_callbacks())
1312 .unwrap_or(false)
1313 }
1314
1315 pub fn has_transient_frame_callbacks(&self) -> bool {
1316 self.inner
1317 .upgrade()
1318 .map(|inner| inner.has_transient_frame_callbacks())
1319 .unwrap_or(false)
1320 }
1321
1322 pub fn assert_ui_thread(&self) {
1323 debug_assert_eq!(
1324 std::thread::current().id(),
1325 self.ui_thread_id,
1326 "state mutated off the runtime's UI thread"
1327 );
1328 }
1329
1330 pub fn dispatcher(&self) -> UiDispatcher {
1331 self.dispatcher.clone()
1332 }
1333
1334 #[doc(hidden)]
1335 pub fn with_deferred_state_releases<R>(&self, f: impl FnOnce() -> R) -> R {
1336 let _scope = enter_state_teardown_scope();
1337 f()
1338 }
1339}
1340
1341impl TaskHandle {
1342 pub fn cancel(self) {
1343 self.runtime.cancel_task(self.id);
1344 }
1345}
1346
1347pub(crate) struct FrameCallbackEntry {
1348 id: FrameCallbackId,
1349 kind: FrameCallbackKind,
1350 callback: Option<Box<dyn FnOnce(u64) + 'static>>,
1351}
1352
1353#[cfg(not(target_arch = "wasm32"))]
1365struct RuntimeTaskWaker {
1366 scheduler: Arc<dyn RuntimeScheduler>,
1367 runnable: Arc<AtomicBool>,
1368}
1369
1370#[cfg(target_arch = "wasm32")]
1371struct RuntimeTaskWaker {
1372 runtime_id: RuntimeId,
1373 runnable: Arc<AtomicBool>,
1374}
1375
1376impl RuntimeTaskWaker {
1377 #[cfg(not(target_arch = "wasm32"))]
1378 fn new(inner: &RuntimeInner, runnable: Arc<AtomicBool>) -> Self {
1379 let scheduler = inner.scheduler.clone();
1380 Self {
1381 scheduler,
1382 runnable,
1383 }
1384 }
1385
1386 #[cfg(target_arch = "wasm32")]
1387 fn new(inner: &RuntimeInner, runnable: Arc<AtomicBool>) -> Self {
1388 let runtime_id = inner.runtime_id;
1389 Self {
1390 runtime_id,
1391 runnable,
1392 }
1393 }
1394
1395 fn into_waker(self) -> Waker {
1396 futures_task::waker(Arc::new(self))
1397 }
1398}
1399
1400impl futures_task::ArcWake for RuntimeTaskWaker {
1401 #[cfg(not(target_arch = "wasm32"))]
1402 fn wake_by_ref(arc_self: &Arc<Self>) {
1403 arc_self.runnable.store(true, Ordering::Release);
1404 arc_self.scheduler.schedule_frame();
1405 }
1406
1407 #[cfg(target_arch = "wasm32")]
1408 fn wake_by_ref(arc_self: &Arc<Self>) {
1409 arc_self.runnable.store(true, Ordering::Release);
1410 REGISTERED_RUNTIMES.with(|registry| {
1411 if let Some(handle) = registry.borrow().get(&arc_self.runtime_id).cloned() {
1412 handle.schedule();
1413 }
1414 });
1415 }
1416}
1417
1418thread_local! {
1419 static NEXT_RUNTIME_ID: Cell<u32> = const { Cell::new(1) };
1420 static ACTIVE_RUNTIMES: RefCell<Vec<RuntimeHandle>> = const { RefCell::new(Vec::new()) };
1421 static LAST_RUNTIME: RefCell<Option<RuntimeHandle>> = const { RefCell::new(None) };
1422 static REGISTERED_RUNTIMES: RefCell<HashMap<RuntimeId, RuntimeHandle>> = RefCell::new(HashMap::default());
1423 static STATE_TEARDOWN_DEPTH: Cell<usize> = const { Cell::new(0) };
1424 static DEFERRED_STATE_RELEASES: RefCell<Vec<DeferredStateRelease>> = const { RefCell::new(Vec::new()) };
1425}
1426
1427#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1428pub struct RuntimeThreadLocalDebugStats {
1429 pub active_runtimes_len: usize,
1430 pub active_runtimes_cap: usize,
1431 pub registered_runtimes_len: usize,
1432 pub registered_runtimes_cap: usize,
1433 pub deferred_state_releases_len: usize,
1434 pub deferred_state_releases_cap: usize,
1435}
1436
1437pub fn current_runtime_handle() -> Option<RuntimeHandle> {
1442 if let Some(handle) = ACTIVE_RUNTIMES.with(|stack| stack.borrow().last().cloned()) {
1443 return Some(handle);
1444 }
1445 LAST_RUNTIME.with(|slot| slot.borrow().clone())
1446}
1447
1448pub(crate) fn runtime_handle_by_id(id: RuntimeId) -> Option<RuntimeHandle> {
1449 REGISTERED_RUNTIMES.with(|registry| registry.borrow().get(&id).cloned())
1450}
1451
1452pub(crate) fn live_recompose_scope_count() -> usize {
1453 REGISTERED_RUNTIMES.with(|registry| {
1454 registry
1455 .borrow()
1456 .values()
1457 .map(RuntimeHandle::live_recompose_scope_count)
1458 .sum()
1459 })
1460}
1461
1462pub fn debug_runtime_thread_local_stats() -> RuntimeThreadLocalDebugStats {
1463 let (active_runtimes_len, active_runtimes_cap) = ACTIVE_RUNTIMES.with(|stack| {
1464 let stack = stack.borrow();
1465 (stack.len(), stack.capacity())
1466 });
1467 let (registered_runtimes_len, registered_runtimes_cap) = REGISTERED_RUNTIMES.with(|registry| {
1468 let registry = registry.borrow();
1469 (registry.len(), registry.capacity())
1470 });
1471 let (deferred_state_releases_len, deferred_state_releases_cap) =
1472 DEFERRED_STATE_RELEASES.with(|releases| {
1473 let releases = releases.borrow();
1474 (releases.len(), releases.capacity())
1475 });
1476
1477 RuntimeThreadLocalDebugStats {
1478 active_runtimes_len,
1479 active_runtimes_cap,
1480 registered_runtimes_len,
1481 registered_runtimes_cap,
1482 deferred_state_releases_len,
1483 deferred_state_releases_cap,
1484 }
1485}
1486
1487fn register_runtime_handle(handle: &RuntimeHandle) {
1488 REGISTERED_RUNTIMES.with(|registry| {
1489 registry.borrow_mut().insert(handle.id(), handle.clone());
1490 });
1491}
1492
1493fn unregister_runtime_handle(id: RuntimeId) {
1494 REGISTERED_RUNTIMES.with(|registry| {
1495 registry.borrow_mut().remove(&id);
1496 });
1497}
1498
1499fn defer_state_release(runtime: RuntimeHandle, id: StateId) {
1500 let teardown_active = STATE_TEARDOWN_DEPTH.with(|depth| depth.get() > 0);
1501 if teardown_active {
1502 DEFERRED_STATE_RELEASES.with(|releases| {
1503 releases
1504 .borrow_mut()
1505 .push(DeferredStateRelease { runtime, id });
1506 });
1507 } else {
1508 runtime.release_state_immediate(id);
1509 }
1510}
1511
1512fn flush_deferred_state_releases() {
1513 DEFERRED_STATE_RELEASES.with(|releases| {
1514 let mut releases = releases.borrow_mut();
1515 while let Some(deferred) = releases.pop() {
1516 deferred.runtime.release_state_immediate(deferred.id);
1517 }
1518 });
1519}
1520
1521pub(crate) struct StateTeardownScope;
1522
1523pub(crate) fn enter_state_teardown_scope() -> StateTeardownScope {
1524 STATE_TEARDOWN_DEPTH.with(|depth| depth.set(depth.get() + 1));
1525 StateTeardownScope
1526}
1527
1528impl Drop for StateTeardownScope {
1529 fn drop(&mut self) {
1530 STATE_TEARDOWN_DEPTH.with(|depth| {
1531 let next = depth.get().saturating_sub(1);
1532 depth.set(next);
1533 if next == 0 {
1534 flush_deferred_state_releases();
1535 }
1536 });
1537 }
1538}
1539
1540pub(crate) fn push_active_runtime(handle: &RuntimeHandle) {
1541 register_runtime_handle(handle);
1542 ACTIVE_RUNTIMES.with(|stack| stack.borrow_mut().push(handle.clone()));
1543 LAST_RUNTIME.with(|slot| *slot.borrow_mut() = Some(handle.clone()));
1544}
1545
1546pub(crate) fn pop_active_runtime() {
1547 ACTIVE_RUNTIMES.with(|stack| {
1548 stack.borrow_mut().pop();
1549 });
1550}
1551
1552pub fn schedule_frame() {
1554 if let Some(handle) = current_runtime_handle() {
1555 handle.schedule();
1556 return;
1557 }
1558 log::debug!(
1559 target: "cranpose::runtime",
1560 "ignoring frame request without an active runtime",
1561 );
1562}
1563
1564pub fn schedule_node_update(
1566 update: impl FnOnce(&mut dyn Applier) -> Result<(), NodeError> + 'static,
1567) {
1568 if let Some(handle) = current_runtime_handle() {
1569 handle.enqueue_node_update(Command::callback(update));
1570 } else {
1571 drop(update);
1572 log::debug!(
1573 target: "cranpose::runtime",
1574 "ignoring node update request without an active runtime",
1575 );
1576 }
1577}
1578
1579#[cfg(test)]
1580mod tests {
1581 use super::*;
1582
1583 #[test]
1584 fn state_arena_alloc_skips_free_slot_outside_cell_storage() {
1585 let runtime = TestRuntime::new();
1586 let arena = StateArena::default();
1587 let first = arena.alloc(1_i32, runtime.handle());
1588 arena.inner.borrow_mut().free.push(u32::MAX);
1589
1590 let second = arena.alloc(2_i32, runtime.handle());
1591
1592 assert_eq!(first.slot(), 0);
1593 assert_eq!(second.slot(), 1);
1594 assert!(arena.get_typed_opt::<i32>(first).is_some());
1595 assert!(arena.get_typed_opt::<i32>(second).is_some());
1596 }
1597
1598 #[test]
1599 fn state_arena_alloc_skips_occupied_free_slot() {
1600 let runtime = TestRuntime::new();
1601 let arena = StateArena::default();
1602 let first = arena.alloc(1_i32, runtime.handle());
1603 arena.inner.borrow_mut().free.push(first.slot());
1604
1605 let second = arena.alloc(2_i32, runtime.handle());
1606
1607 assert_ne!(first.slot(), second.slot());
1608 assert_eq!(second.slot(), 1);
1609 assert!(arena.get_typed_opt::<i32>(first).is_some());
1610 assert!(arena.get_typed_opt::<i32>(second).is_some());
1611 }
1612
1613 #[test]
1614 fn state_arena_register_lease_ignores_stale_id() {
1615 let runtime = TestRuntime::new();
1616 let arena = StateArena::default();
1617 let stale_id = StateId::new(99, 0);
1618 let lease = Rc::new(StateHandleLease {
1619 id: stale_id,
1620 runtime: runtime.handle(),
1621 });
1622
1623 arena.register_lease(stale_id, &lease);
1624
1625 assert!(arena.retain_lease(stale_id).is_none());
1626 }
1627
1628 #[test]
1629 fn ui_continuation_type_mismatch_is_ignored_until_matching_payload() {
1630 let runtime = TestRuntime::new();
1631 let handle = runtime.handle();
1632 let received = Rc::new(Cell::new(None));
1633 let received_for_continuation = Rc::clone(&received);
1634 let cont_id = handle
1635 .register_ui_cont(move |value: u32| {
1636 received_for_continuation.set(Some(value));
1637 })
1638 .expect("test runtime is alive");
1639
1640 handle.dispatcher().post_invoke(cont_id, "wrong payload");
1641 handle.drain_ui();
1642
1643 assert_eq!(received.get(), None);
1644 assert_eq!(handle.debug_stats().ui_conts_len, 1);
1645
1646 handle.dispatcher().post_invoke(cont_id, 42_u32);
1647 handle.drain_ui();
1648
1649 assert_eq!(received.get(), Some(42));
1650 assert_eq!(handle.debug_stats().ui_conts_len, 0);
1651 }
1652
1653 #[test]
1654 fn ui_dispatcher_failed_send_does_not_leave_pending_work() {
1655 let runtime = Runtime::new(Arc::new(TestScheduler));
1656 let dispatcher = runtime.handle().dispatcher();
1657
1658 drop(runtime);
1659
1660 assert!(!dispatcher.has_pending());
1661 dispatcher.post(|| {});
1662 assert!(!dispatcher.has_pending());
1663 dispatcher.post_invoke(404, 12_u32);
1664 assert!(!dispatcher.has_pending());
1665 }
1666
1667 #[test]
1668 fn pending_guard_does_not_wrap_on_underflow() {
1669 let counter = AtomicUsize::new(0);
1670
1671 {
1672 let _guard = PendingGuard::new(&counter);
1673 }
1674
1675 assert_eq!(counter.load(Ordering::SeqCst), 0);
1676 }
1677
1678 #[test]
1679 fn pending_guard_decrements_pending_count() {
1680 let counter = AtomicUsize::new(2);
1681
1682 {
1683 let _guard = PendingGuard::new(&counter);
1684 }
1685
1686 assert_eq!(counter.load(Ordering::SeqCst), 1);
1687 }
1688
1689 #[test]
1690 fn schedule_frame_without_runtime_is_ignored() {
1691 let ok = std::thread::spawn(|| std::panic::catch_unwind(super::schedule_frame).is_ok())
1692 .join()
1693 .expect("test thread should join");
1694
1695 assert!(ok);
1696 }
1697
1698 #[test]
1699 fn schedule_node_update_without_runtime_is_ignored() {
1700 let ok = std::thread::spawn(|| {
1701 std::panic::catch_unwind(|| {
1702 super::schedule_node_update(|_| Ok(()));
1703 })
1704 .is_ok()
1705 })
1706 .join()
1707 .expect("test thread should join");
1708
1709 assert!(ok);
1710 }
1711}