1#[macro_export]
35macro_rules! tls_group {
36 ($( $(#[$attr:meta])* $vis:vis static $name:ident : $ty:ty = $init:expr ; )+) => {
37 #[allow(non_snake_case)]
38 struct TlsGroupSlots { $( $name: $ty, )+ }
39 ::std::thread_local! {
40 static TLS_GROUP: TlsGroupSlots = TlsGroupSlots { $( $name: $init, )+ };
41 }
42 $(
43 $(#[$attr])*
44 #[allow(non_camel_case_types, dead_code)]
45 #[derive(Clone, Copy)]
46 $vis struct $name;
47 impl $name {
48 #[inline]
49 #[allow(dead_code)]
50 $vis fn with<R>(self, f: impl ::core::ops::FnOnce(&$ty) -> R) -> R {
51 TLS_GROUP.with(|g| f(&g.$name))
52 }
53 #[inline]
54 #[allow(dead_code)]
55 $vis fn try_with<R>(
56 self,
57 f: impl ::core::ops::FnOnce(&$ty) -> R,
58 ) -> ::core::result::Result<R, ::std::thread::AccessError> {
59 TLS_GROUP.try_with(|g| f(&g.$name))
60 }
61 }
62 )+
63 };
64}
65
66#[macro_export]
78macro_rules! tls_root {
79 ($( $(#[$attr:meta])* $field:ident : $ty:ty ),+ $(,)?) => {
80 #[allow(non_snake_case)]
81 pub(crate) struct TlsRoot { $( $(#[$attr])* pub(crate) $field: $ty, )+ }
82 ::std::thread_local! {
83 static TLS_ROOT: TlsRoot =
84 TlsRoot { $( $(#[$attr])* $field: ::core::default::Default::default(), )+ };
85 }
86 #[inline]
89 pub(crate) fn tls_root<R>(f: impl ::core::ops::FnOnce(&TlsRoot) -> R) -> R {
90 TLS_ROOT.with(f)
91 }
92 #[inline]
94 #[allow(dead_code)]
95 pub(crate) fn try_tls_root<R>(
96 f: impl ::core::ops::FnOnce(&TlsRoot) -> R,
97 ) -> ::core::result::Result<R, ::std::thread::AccessError> {
98 TLS_ROOT.try_with(f)
99 }
100 };
101}
102
103#[allow(clippy::crate_in_macro_def)]
108#[macro_export]
109macro_rules! tls_slots {
110 ($field:ident; $( $(#[$attr:meta])* $vis:vis static $name:ident : $ty:ty = $init:expr ; )+) => {
111 #[allow(non_snake_case)]
112 pub(crate) struct TlsGroupSlots { $( $name: $ty, )+ }
113 impl ::core::default::Default for TlsGroupSlots {
114 fn default() -> Self { Self { $( $name: $init, )+ } }
115 }
116 $(
117 $(#[$attr])*
118 #[allow(non_camel_case_types, dead_code)]
119 #[derive(Clone, Copy)]
120 $vis struct $name;
121 impl $name {
122 #[inline]
123 #[allow(dead_code)]
124 $vis fn with<R>(self, f: impl ::core::ops::FnOnce(&$ty) -> R) -> R {
125 crate::tls_root(|r| f(&r.$field.$name))
126 }
127 #[inline]
128 #[allow(dead_code)]
129 $vis fn try_with<R>(
130 self,
131 f: impl ::core::ops::FnOnce(&$ty) -> R,
132 ) -> ::core::result::Result<R, ::std::thread::AccessError> {
133 crate::try_tls_root(|r| f(&r.$field.$name))
134 }
135 }
136 )+
137 };
138}
139
140use std::any::{Any, TypeId};
141use std::cell::{Cell, RefCell};
142use std::collections::{HashMap, HashSet};
143use std::future::Future;
144use std::marker::PhantomData;
145use std::panic::Location;
146use std::pin::Pin;
147use std::rc::Rc;
148use std::sync::Arc;
149
150use slotmap::{Key, SlotMap, new_key_type};
151
152new_key_type! {
153 pub struct NodeKey;
154 pub struct ScopeKey;
155}
156
157#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
162enum NodeState {
163 Clean,
164 Check,
165 Dirty,
166}
167
168#[derive(Clone, Copy, PartialEq, Eq)]
169enum NodeKind {
170 Signal,
171 Memo,
172 Reaction,
174}
175
176type MemoEq = fn(&dyn Any, &dyn Any) -> bool;
178
179type NodeValue = Rc<RefCell<Box<dyn Any>>>;
188
189struct Node {
190 kind: NodeKind,
191 state: NodeState,
192 value: Option<NodeValue>,
193 memo_compute: Option<Rc<dyn Fn() -> Box<dyn Any>>>,
195 memo_eq: Option<MemoEq>,
196 reaction: Option<Rc<dyn Fn()>>,
198 sources: Vec<NodeKey>,
199 run_cleanups: Vec<Box<dyn FnOnce()>>,
203 observers: Vec<NodeKey>,
204 scope: ScopeKey,
206 priority: u8,
208 depth: u32,
209 seq: u64,
210 last_changed: u64,
211 last_run: u64,
212 queued: bool,
213 created_at: &'static Location<'static>,
214}
215
216struct ScopeData {
217 parent: ScopeKey,
218 children: Vec<ScopeKey>,
219 nodes: Vec<NodeKey>,
220 cleanups: Vec<Box<dyn FnOnce()>>,
221 context: HashMap<TypeId, Box<dyn Any>>,
222 depth: u32,
223}
224
225struct Runtime {
226 nodes: SlotMap<NodeKey, Node>,
227 scopes: SlotMap<ScopeKey, ScopeData>,
228 root_scope: ScopeKey,
229 current_scope: ScopeKey,
230 observers: Vec<Option<NodeKey>>,
232 pending: Vec<NodeKey>,
233 batch_depth: u32,
234 draining: bool,
235 tick: u64,
236 next_seq: u64,
237 scheduler: Option<Rc<dyn Fn()>>,
238 schedule_posted: bool,
239 spawner: Option<Spawner>,
242 turn_end: Vec<Rc<dyn Fn()>>,
243 turn_end_once: Vec<Box<dyn FnOnce()>>,
245 warned_writes: HashSet<*const Location<'static>>,
246}
247
248impl Runtime {
249 fn new() -> Self {
250 let mut scopes = SlotMap::with_key();
251 let root_scope = scopes.insert(ScopeData {
252 parent: ScopeKey::null(),
253 children: Vec::new(),
254 nodes: Vec::new(),
255 cleanups: Vec::new(),
256 context: HashMap::new(),
257 depth: 0,
258 });
259 Runtime {
260 nodes: SlotMap::with_key(),
261 scopes,
262 root_scope,
263 current_scope: root_scope,
264 observers: Vec::new(),
265 pending: Vec::new(),
266 batch_depth: 0,
267 draining: false,
268 tick: 1,
269 next_seq: 0,
270 scheduler: None,
271 schedule_posted: false,
272 turn_end_once: Vec::new(),
273 spawner: None,
274 turn_end: Vec::new(),
275 warned_writes: HashSet::new(),
276 }
277 }
278}
279
280crate::tls_group! {
281 static RT: RefCell<Runtime> = RefCell::new(Runtime::new());
282
283}
284
285const RERUN_CAP: u32 = 100;
287
288const TURN_ROUND_CAP: u32 = 8;
293
294fn with_rt<R>(f: impl FnOnce(&mut Runtime) -> R) -> R {
295 RT.with(|rt| f(&mut rt.borrow_mut()))
296}
297
298#[track_caller]
303fn create_node(rt: &mut Runtime, kind: NodeKind, scope: ScopeKey) -> NodeKey {
304 let depth = rt.scopes.get(scope).map_or(0, |s| s.depth);
305 let seq = rt.next_seq;
306 rt.next_seq += 1;
307 let key = rt.nodes.insert(Node {
308 kind,
309 state: NodeState::Clean,
310 value: None,
311 memo_compute: None,
312 memo_eq: None,
313 reaction: None,
314 sources: Vec::new(),
315 run_cleanups: Vec::new(),
316 observers: Vec::new(),
317 scope,
318 priority: 1,
319 depth,
320 seq,
321 last_changed: 0,
322 last_run: 0,
323 queued: false,
324 created_at: Location::caller(),
325 });
326 if let Some(s) = rt.scopes.get_mut(scope) {
327 s.nodes.push(key);
328 }
329 key
330}
331
332fn track_read(rt: &mut Runtime, source: NodeKey) {
334 if let Some(Some(obs)) = rt.observers.last().copied() {
335 if obs == source {
336 return;
337 }
338 let already = rt.nodes[obs].sources.contains(&source);
339 if !already {
340 rt.nodes[obs].sources.push(source);
341 rt.nodes[source].observers.push(obs);
342 }
343 }
344}
345
346#[must_use]
350fn clear_sources(rt: &mut Runtime, key: NodeKey) -> Vec<Box<dyn FnOnce()>> {
351 let sources = std::mem::take(&mut rt.nodes[key].sources);
352 for s in sources {
353 if let Some(n) = rt.nodes.get_mut(s)
354 && let Some(pos) = n.observers.iter().position(|&o| o == key)
355 {
356 n.observers.swap_remove(pos);
357 }
358 }
359 std::mem::take(&mut rt.nodes[key].run_cleanups)
360}
361
362fn mark_observers(rt: &mut Runtime, source: NodeKey, level: NodeState) {
365 let mut stack: Vec<(NodeKey, NodeState)> = rt.nodes[source]
367 .observers
368 .iter()
369 .map(|&o| (o, level))
370 .collect();
371 while let Some((key, level)) = stack.pop() {
372 let Some(node) = rt.nodes.get_mut(key) else {
373 continue;
374 };
375 if node.state >= level {
376 continue; }
378 node.state = level;
379 match node.kind {
380 NodeKind::Reaction => {
381 if !node.queued {
382 node.queued = true;
383 rt.pending.push(key);
384 }
385 }
386 NodeKind::Memo => {
387 for &o in &rt.nodes[key].observers {
388 stack.push((o, NodeState::Check));
389 }
390 }
391 NodeKind::Signal => {}
392 }
393 }
394}
395
396fn compute_in_owner<T>(key: NodeKey, f: impl FnOnce() -> T) -> Option<T> {
400 let owner = with_rt(|rt| {
401 let owner = rt.nodes.get(key)?.scope;
402 rt.scopes.contains_key(owner).then_some(owner)
403 })?;
404 let scope = Scope {
405 key: owner,
406 _not_send: PhantomData,
407 };
408 Some(scope.enter(|| {
409 with_rt(|rt| rt.observers.push(Some(key)));
410 let _guard = rt_guard(|rt: &mut Runtime| {
411 rt.observers.pop();
412 });
413 f()
414 }))
415}
416
417fn refresh_memo(key: NodeKey) {
419 let Some((state, kind)) = with_rt(|rt| rt.nodes.get(key).map(|n| (n.state, n.kind))) else {
420 return;
421 };
422 if kind != NodeKind::Memo || state == NodeState::Clean {
423 return;
424 }
425 if state == NodeState::Check {
426 let (sources, last_run) =
428 with_rt(|rt| (rt.nodes[key].sources.clone(), rt.nodes[key].last_run));
429 let mut any_changed = false;
430 for s in sources {
431 refresh_memo(s);
432 if with_rt(|rt| rt.nodes.get(s).is_some_and(|n| n.last_changed > last_run)) {
433 any_changed = true;
434 }
435 }
436 if !any_changed {
437 with_rt(|rt| {
438 if let Some(n) = rt.nodes.get_mut(key) {
439 n.state = NodeState::Clean;
440 }
441 });
442 return;
443 }
444 }
445 let compute = with_rt(|rt| rt.nodes[key].memo_compute.clone());
447 let Some(compute) = compute else { return };
448 let cleanups = with_rt(|rt| clear_sources(rt, key));
449 for f in cleanups {
450 f();
451 }
452 let Some(new_value) = compute_in_owner(key, || compute()) else {
453 return;
454 };
455 with_rt(|rt| {
456 let tick = rt.tick;
457 let Some(node) = rt.nodes.get_mut(key) else {
458 return;
459 };
460 let changed = match (node.value.as_ref(), node.memo_eq) {
461 (Some(old), Some(eq)) => {
462 let old = old.borrow();
464 !eq(old.as_ref(), new_value.as_ref())
465 }
466 _ => true,
467 };
468 node.last_run = tick;
469 node.state = NodeState::Clean;
470 if changed {
471 node.value = Some(Rc::new(RefCell::new(new_value)));
474 node.last_changed = tick;
475 rt.tick += 1;
476 }
477 });
480}
481
482fn run_reaction(key: NodeKey) {
484 let info = with_rt(|rt| {
485 rt.nodes.get_mut(key).map(|n| {
486 n.queued = false;
487 (n.state, n.sources.clone(), n.last_run)
488 })
489 });
490 let Some((state, sources, last_run)) = info else {
491 return;
492 };
493 if state == NodeState::Clean {
494 return;
495 }
496 if state == NodeState::Check {
497 let mut any_changed = false;
498 for s in &sources {
499 refresh_memo(*s);
500 if with_rt(|rt| rt.nodes.get(*s).is_some_and(|n| n.last_changed > last_run)) {
501 any_changed = true;
502 break;
503 }
504 }
505 if !any_changed {
506 with_rt(|rt| {
507 if let Some(n) = rt.nodes.get_mut(key) {
508 n.state = NodeState::Clean;
509 }
510 });
511 return;
512 }
513 }
514 let reaction = with_rt(|rt| rt.nodes.get(key).and_then(|n| n.reaction.clone()));
515 let Some(reaction) = reaction else { return };
516 let cleanups = with_rt(|rt| {
517 let cleanups = clear_sources(rt, key);
518 if let Some(n) = rt.nodes.get_mut(key) {
519 n.state = NodeState::Clean;
520 }
521 cleanups
522 });
523 for f in cleanups {
525 f();
526 }
527 compute_in_owner(key, || reaction());
528 with_rt(|rt| {
529 let tick = rt.tick;
530 rt.tick += 1;
531 if let Some(n) = rt.nodes.get_mut(key) {
532 n.last_run = tick;
533 }
534 });
535}
536
537pub fn flush_sync() {
553 let already = with_rt(|rt| {
554 if rt.draining {
555 return true;
556 }
557 rt.draining = true;
558 false
559 });
560 if already {
561 return; }
563 let mut round = 0u32;
564 loop {
565 round += 1;
566 let mut run_counts: HashMap<NodeKey, u32> = HashMap::new();
568 loop {
569 let mut batch = with_rt(|rt| std::mem::take(&mut rt.pending));
570 if batch.is_empty() {
571 break;
572 }
573 with_rt(|rt| {
575 batch.sort_by_key(|&k| {
576 rt.nodes.get(k).map_or((u8::MAX, u32::MAX, u64::MAX), |n| {
577 (n.priority, n.depth, n.seq)
578 })
579 });
580 });
581 for key in batch {
582 let count = run_counts.entry(key).or_insert(0);
583 *count += 1;
584 if *count > RERUN_CAP {
585 if *count == RERUN_CAP + 1 {
586 let loc = with_rt(|rt| rt.nodes.get(key).map(|n| n.created_at));
587 if let Some(loc) = loc {
588 debug_assert!(
589 false,
590 "day-reactive: effect created at {loc} re-ran more than {RERUN_CAP} times in one drain (reactive cycle?)"
591 );
592 log::warn!(
593 "day-reactive: effect created at {loc} exceeded the re-run cap; skipping it for the rest of this drain (the next source write re-arms it)"
594 );
595 }
596 }
597 with_rt(|rt| {
603 if let Some(n) = rt.nodes.get_mut(key) {
604 n.queued = false;
605 n.state = NodeState::Clean;
606 }
607 });
608 continue;
609 }
610 run_reaction(key);
611 }
612 }
613 let (once, turn_end) = with_rt(|rt| {
614 rt.draining = false;
615 rt.schedule_posted = false;
616 (std::mem::take(&mut rt.turn_end_once), rt.turn_end.clone())
617 });
618 for cb in once {
621 cb();
622 }
623 for cb in turn_end {
624 cb();
625 }
626 let more = with_rt(|rt| {
628 if rt.pending.is_empty() {
629 return false;
630 }
631 rt.draining = true;
632 true
633 });
634 if !more {
635 return;
636 }
637 if round >= TURN_ROUND_CAP {
638 with_rt(|rt| rt.draining = false);
642 debug_assert!(
643 false,
644 "day-reactive: turn-end callbacks scheduled new reactive work for {TURN_ROUND_CAP} straight rounds in one turn (hooks feeding each other?)"
645 );
646 log::warn!(
647 "day-reactive: turn-end callbacks still scheduling work after {TURN_ROUND_CAP} rounds; deferring the rest to the next turn"
648 );
649 return;
650 }
651 }
652}
653
654pub fn recover_from_panic() {
661 with_rt(|rt| {
662 rt.draining = false;
663 rt.schedule_posted = false;
664 rt.batch_depth = 0;
665 rt.turn_end_once.clear();
666 rt.pending.clear();
667 rt.observers.clear();
668 rt.current_scope = rt.root_scope;
672 });
673}
674
675fn schedule_after_write(rt: &mut Runtime) -> Option<Rc<dyn Fn()>> {
678 if rt.batch_depth > 0 || rt.draining {
679 return None;
680 }
681 if rt.schedule_posted {
682 return None;
683 }
684 rt.schedule_posted = true;
685 rt.scheduler.clone()
686}
687
688fn signal_write_boxed(key: NodeKey, apply: impl FnOnce(&mut Box<dyn Any>) -> bool) {
689 let poster = with_rt(|rt| {
690 let node = rt.nodes.get_mut(key)?;
691 let cell = node.value.as_ref()?.clone();
692 let Ok(mut value) = cell.try_borrow_mut() else {
696 panic!(
697 "day-reactive: wrote to a Signal while a with()/try_with() read of it is still \
698 in flight — the write would be lost. Finish the read closure first (copy the \
699 value out with get()) and write after it returns."
700 )
701 };
702 let changed = apply(&mut value);
703 drop(value);
704 let node = rt.nodes.get_mut(key)?;
705 if !changed {
706 return None;
707 }
708 node.last_changed = rt.tick;
709 rt.tick += 1;
710 mark_observers(rt, key, NodeState::Dirty);
711 schedule_after_write(rt)
712 });
713 if let Some(post) = poster {
714 post();
715 }
716}
717
718fn rt_guard(f: impl FnOnce(&mut Runtime)) -> impl Drop {
729 std::mem::DropGuard::new((), |()| with_rt(f))
730}
731
732pub fn batch<R>(f: impl FnOnce() -> R) -> R {
733 with_rt(|rt| rt.batch_depth += 1);
734 let r = {
735 let _g = rt_guard(|rt: &mut Runtime| rt.batch_depth = rt.batch_depth.saturating_sub(1));
740 f()
741 };
742 let should_drain = with_rt(|rt| {
743 rt.batch_depth == 0
744 && !rt.draining
745 && (!rt.pending.is_empty() || !rt.turn_end_once.is_empty())
746 });
747 if should_drain {
748 flush_sync();
749 }
750 r
751}
752
753pub fn flush_now() {
760 let saved = with_rt(|rt| std::mem::replace(&mut rt.batch_depth, 0));
761 let _g = rt_guard(move |rt: &mut Runtime| rt.batch_depth = saved);
764 flush_sync();
765}
766
767pub fn untrack<R>(f: impl FnOnce() -> R) -> R {
769 with_rt(|rt| rt.observers.push(None));
770 let _g = rt_guard(|rt: &mut Runtime| {
773 rt.observers.pop();
774 });
775 f()
776}
777
778#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
782pub struct RunId(NodeKey);
783
784pub fn active_run() -> Option<RunId> {
786 with_rt(|rt| rt.observers.last().copied().flatten()).map(RunId)
787}
788
789pub fn on_run_retrack(f: impl FnOnce() + 'static) -> bool {
794 with_rt(|rt| {
795 let Some(Some(key)) = rt.observers.last().copied() else {
796 return false;
797 };
798 match rt.nodes.get_mut(key) {
799 Some(n) => {
800 n.run_cleanups.push(Box::new(f));
801 true
802 }
803 None => false,
804 }
805 })
806}
807
808pub fn install_scheduler(post: impl Fn() + 'static) {
810 with_rt(|rt| rt.scheduler = Some(Rc::new(post)));
811}
812
813pub type LocalBoxFuture = Pin<Box<dyn Future<Output = ()> + 'static>>;
815
816type Spawner = Rc<dyn Fn(LocalBoxFuture) -> Box<dyn FnOnce()>>;
818
819pub fn install_spawner(spawn: impl Fn(LocalBoxFuture) -> Box<dyn FnOnce()> + 'static) {
825 with_rt(|rt| rt.spawner = Some(Rc::new(spawn)));
826}
827
828fn spawn_local(fut: LocalBoxFuture) -> Box<dyn FnOnce()> {
830 let spawner = with_rt(|rt| rt.spawner.clone());
831 match spawner {
832 Some(s) => s(fut),
833 None => panic!("day-reactive: no spawner installed (backend not started)"),
834 }
835}
836
837pub fn on_turn_end(cb: impl Fn() + 'static) {
839 with_rt(|rt| rt.turn_end.push(Rc::new(cb)));
840}
841
842pub fn at_turn_end(cb: impl FnOnce() + 'static) {
849 let now = with_rt(|rt| {
850 if rt.draining || rt.batch_depth > 0 {
851 rt.turn_end_once.push(Box::new(cb));
852 None
853 } else {
854 Some(cb)
855 }
856 });
857 if let Some(cb) = now {
858 cb();
859 }
860}
861
862type MainPoster = Box<dyn Fn(Box<dyn FnOnce() + Send>) + Send + Sync>;
867static MAIN_POSTER: std::sync::OnceLock<MainPoster> = std::sync::OnceLock::new();
868
869pub fn install_main_poster(post: impl Fn(Box<dyn FnOnce() + Send>) + Send + Sync + 'static) {
871 let _ = MAIN_POSTER.set(Box::new(post));
872}
873
874pub fn has_main_poster() -> bool {
880 MAIN_POSTER.get().is_some()
881}
882
883pub fn on_main(f: impl FnOnce() + Send + 'static) {
889 match MAIN_POSTER.get() {
890 Some(post) => post(Box::new(f)),
891 None => panic!("day-reactive: no main poster installed (backend not started)"),
892 }
893}
894
895type DelayedPoster = Box<dyn Fn(u32, Box<dyn FnOnce() + Send>) + Send + Sync>;
896static DELAYED_POSTER: std::sync::OnceLock<DelayedPoster> = std::sync::OnceLock::new();
897
898pub fn install_delayed_poster(
900 post: impl Fn(u32, Box<dyn FnOnce() + Send>) + Send + Sync + 'static,
901) {
902 let _ = DELAYED_POSTER.set(Box::new(post));
903}
904
905pub fn on_main_delayed(ms: u32, f: impl FnOnce() + Send + 'static) {
912 let Some(post) = DELAYED_POSTER.get() else {
913 panic!("day-reactive: no delayed poster installed (backend not started)")
914 };
915 #[cfg(not(target_arch = "wasm32"))]
916 post(ms, delayed::arm(ms, Box::new(f)));
917 #[cfg(target_arch = "wasm32")]
920 post(ms, Box::new(f));
921}
922
923#[cfg(not(target_arch = "wasm32"))]
934mod delayed {
935 use std::cmp::Reverse;
936 use std::collections::BinaryHeap;
937 use std::sync::{Mutex, PoisonError};
938 use std::time::{Duration, Instant};
939
940 type Job = Box<dyn FnOnce() + Send>;
941
942 struct Entry {
943 due: Instant,
944 seq: u64,
946 job: Job,
947 }
948
949 impl PartialEq for Entry {
950 fn eq(&self, other: &Self) -> bool {
951 (self.due, self.seq) == (other.due, other.seq)
952 }
953 }
954 impl Eq for Entry {}
955 impl PartialOrd for Entry {
956 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
957 Some(self.cmp(other))
958 }
959 }
960 impl Ord for Entry {
961 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
962 (self.due, self.seq).cmp(&(other.due, other.seq))
963 }
964 }
965
966 struct Queue {
967 waiting: BinaryHeap<Reverse<Entry>>,
968 next_seq: u64,
969 }
970
971 static QUEUE: Mutex<Queue> = Mutex::new(Queue {
972 waiting: BinaryHeap::new(),
973 next_seq: 0,
974 });
975
976 pub(super) fn arm(ms: u32, job: Job) -> Job {
978 let due = Instant::now() + Duration::from_millis(u64::from(ms));
979 {
980 let mut queue = QUEUE.lock().unwrap_or_else(PoisonError::into_inner);
981 let seq = queue.next_seq;
982 queue.next_seq += 1;
983 queue.waiting.push(Reverse(Entry { due, seq, job }));
984 }
985 Box::new(move || run_due(due))
986 }
987
988 fn run_due(own: Instant) {
991 let until = own.max(Instant::now());
992 loop {
993 let job = {
995 let mut queue = QUEUE.lock().unwrap_or_else(PoisonError::into_inner);
996 match queue.waiting.peek() {
997 Some(Reverse(entry)) if entry.due <= until => {
998 queue.waiting.pop().map(|Reverse(entry)| entry.job)
999 }
1000 _ => None,
1001 }
1002 };
1003 let Some(job) = job else { break };
1004 job();
1005 }
1006 }
1007
1008 #[cfg(test)]
1009 mod tests {
1010 use super::*;
1011 use std::sync::Arc;
1012
1013 #[test]
1016 fn overdue_timers_run_in_deadline_order_whatever_order_they_fire_in() {
1017 let ran = Arc::new(Mutex::new(Vec::new()));
1018 let mut timers = Vec::new();
1019 for ms in [200u32, 10, 100, 50] {
1020 let ran = ran.clone();
1021 timers.push(arm(ms, Box::new(move || ran.lock().unwrap().push(ms))));
1022 }
1023 std::thread::sleep(Duration::from_millis(230));
1025 for timer in timers {
1026 timer();
1027 }
1028 assert_eq!(*ran.lock().unwrap(), [10, 50, 100, 200]);
1029 }
1030
1031 #[test]
1033 fn a_timer_runs_its_own_closure_and_nothing_due_later() {
1034 let ran = Arc::new(Mutex::new(Vec::new()));
1035 let note = |tag: &'static str| {
1036 let ran = ran.clone();
1037 Box::new(move || ran.lock().unwrap().push(tag)) as Job
1038 };
1039 let soon = arm(0, note("soon"));
1040 let later = arm(60_000, note("later"));
1041 soon();
1042 assert_eq!(*ran.lock().unwrap(), ["soon"]);
1043 later();
1045 assert_eq!(*ran.lock().unwrap(), ["soon", "later"]);
1046 }
1047 }
1048}
1049
1050#[derive(Clone, Copy, PartialEq, Eq)]
1056pub struct Scope {
1057 key: ScopeKey,
1058 _not_send: PhantomData<*const ()>,
1059}
1060
1061impl Scope {
1062 pub fn current() -> Scope {
1063 Scope {
1064 key: with_rt(|rt| rt.current_scope),
1065 _not_send: PhantomData,
1066 }
1067 }
1068
1069 pub fn root() -> Scope {
1070 Scope {
1071 key: with_rt(|rt| rt.root_scope),
1072 _not_send: PhantomData,
1073 }
1074 }
1075
1076 pub fn child() -> Scope {
1078 Scope::current().create_child()
1079 }
1080
1081 #[must_use]
1082 pub fn create_child(self) -> Scope {
1083 let key = with_rt(|rt| {
1084 let depth = rt.scopes.get(self.key).map_or(1, |s| s.depth + 1);
1085 let child = rt.scopes.insert(ScopeData {
1086 parent: self.key,
1087 children: Vec::new(),
1088 nodes: Vec::new(),
1089 cleanups: Vec::new(),
1090 context: HashMap::new(),
1091 depth,
1092 });
1093 if let Some(p) = rt.scopes.get_mut(self.key) {
1094 p.children.push(child);
1095 }
1096 child
1097 });
1098 Scope {
1099 key,
1100 _not_send: PhantomData,
1101 }
1102 }
1103
1104 pub fn detached() -> Scope {
1106 let key = with_rt(|rt| {
1107 rt.scopes.insert(ScopeData {
1108 parent: ScopeKey::null(),
1109 children: Vec::new(),
1110 nodes: Vec::new(),
1111 cleanups: Vec::new(),
1112 context: HashMap::new(),
1113 depth: 0,
1114 })
1115 });
1116 Scope {
1117 key,
1118 _not_send: PhantomData,
1119 }
1120 }
1121
1122 pub fn enter<R>(self, f: impl FnOnce() -> R) -> R {
1124 let prev = with_rt(|rt| std::mem::replace(&mut rt.current_scope, self.key));
1125 let _g = rt_guard(move |rt: &mut Runtime| rt.current_scope = prev);
1129 f()
1130 }
1131
1132 pub fn on_cleanup(self, f: impl FnOnce() + 'static) {
1133 with_rt(|rt| {
1134 if let Some(s) = rt.scopes.get_mut(self.key) {
1135 s.cleanups.push(Box::new(f));
1136 }
1137 });
1138 }
1139
1140 #[must_use]
1141 pub fn is_alive(self) -> bool {
1142 with_rt(|rt| rt.scopes.contains_key(self.key))
1143 }
1144
1145 pub fn dispose(self) {
1147 let Some(children) = with_rt(|rt| rt.scopes.get(self.key).map(|s| s.children.clone()))
1148 else {
1149 return;
1150 };
1151 for c in children {
1152 (Scope {
1153 key: c,
1154 _not_send: PhantomData,
1155 })
1156 .dispose();
1157 }
1158 let Some((nodes, cleanups, parent)) = with_rt(|rt| {
1159 rt.scopes
1160 .remove(self.key)
1161 .map(|s| (s.nodes, s.cleanups, s.parent))
1162 }) else {
1163 return;
1164 };
1165 let mut run_cleanups: Vec<Box<dyn FnOnce()>> = Vec::new();
1166 with_rt(|rt| {
1167 if let Some(p) = rt.scopes.get_mut(parent)
1168 && let Some(pos) = p.children.iter().position(|&c| c == self.key)
1169 {
1170 p.children.swap_remove(pos);
1171 }
1172 for key in nodes {
1173 run_cleanups.extend(clear_sources(rt, key));
1174 if let Some(node) = rt.nodes.get_mut(key) {
1176 let observers = std::mem::take(&mut node.observers);
1177 for o in observers {
1178 if let Some(on) = rt.nodes.get_mut(o)
1179 && let Some(pos) = on.sources.iter().position(|&s| s == key)
1180 {
1181 on.sources.swap_remove(pos);
1182 }
1183 }
1184 }
1185 rt.nodes.remove(key);
1186 }
1188 });
1189 for f in run_cleanups {
1192 f();
1193 }
1194 for c in cleanups {
1195 c();
1196 }
1197 }
1198
1199 pub fn provide<T: 'static>(self, value: T) {
1201 with_rt(|rt| {
1202 if let Some(s) = rt.scopes.get_mut(self.key) {
1203 s.context.insert(TypeId::of::<T>(), Box::new(value));
1204 }
1205 });
1206 }
1207
1208 #[must_use]
1210 pub fn use_context<T: Clone + 'static>(self) -> Option<T> {
1211 with_rt(|rt| {
1212 let mut cur = self.key;
1213 while let Some(s) = rt.scopes.get(cur) {
1214 if let Some(v) = s.context.get(&TypeId::of::<T>()) {
1215 return v.downcast_ref::<T>().cloned();
1216 }
1217 cur = s.parent;
1218 }
1219 None
1220 })
1221 }
1222}
1223
1224pub struct Signal<T: 'static> {
1230 key: NodeKey,
1231 created_at: &'static Location<'static>,
1232 _m: PhantomData<*const T>,
1233}
1234
1235impl<T: 'static> Clone for Signal<T> {
1236 fn clone(&self) -> Self {
1237 *self
1238 }
1239}
1240impl<T: 'static> Copy for Signal<T> {}
1241
1242impl<T: 'static> std::fmt::Debug for Signal<T> {
1243 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1244 write!(f, "Signal({:?})", self.key)
1245 }
1246}
1247
1248impl<T: 'static> Signal<T> {
1249 #[track_caller]
1250 pub fn new(value: T) -> Self {
1251 Self::new_in(Scope::current(), value)
1252 }
1253
1254 #[track_caller]
1261 pub fn global(value: T) -> Self {
1262 Self::new_in(Scope::root(), value)
1263 }
1264
1265 #[track_caller]
1266 pub fn new_in(scope: Scope, value: T) -> Self {
1267 let created_at = Location::caller();
1268 let key = with_rt(|rt| {
1269 let k = create_node(rt, NodeKind::Signal, scope.key);
1270 rt.nodes[k].value = Some(Rc::new(RefCell::new(Box::new(value) as Box<dyn Any>)));
1271 rt.nodes[k].created_at = created_at;
1272 k
1273 });
1274 Signal {
1275 key,
1276 created_at,
1277 _m: PhantomData,
1278 }
1279 }
1280
1281 #[track_caller]
1288 pub fn with<R>(self, f: impl FnOnce(&T) -> R) -> R {
1289 match self.try_with(f) {
1290 Some(r) => r,
1291 None => panic!(
1292 "day-reactive: read of disposed Signal created at {} (use try_with in closures that can outlive their scope)",
1293 self.created_at
1294 ),
1295 }
1296 }
1297
1298 pub fn try_with<R>(self, f: impl FnOnce(&T) -> R) -> Option<R> {
1299 let cell = with_rt(|rt| {
1304 track_read(rt, self.key);
1305 rt.nodes.get(self.key).and_then(|n| n.value.clone())
1306 })?;
1307 let value = cell.borrow();
1308 value.downcast_ref::<T>().map(f)
1309 }
1310
1311 pub fn with_untracked<R>(self, f: impl FnOnce(&T) -> R) -> R {
1312 untrack(|| self.with(f))
1313 }
1314
1315 #[track_caller]
1316 #[must_use]
1317 pub fn get(self) -> T
1318 where
1319 T: Clone,
1320 {
1321 self.with(std::clone::Clone::clone)
1322 }
1323
1324 #[must_use]
1325 pub fn try_get(self) -> Option<T>
1326 where
1327 T: Clone,
1328 {
1329 self.try_with(std::clone::Clone::clone)
1330 }
1331
1332 #[must_use]
1333 pub fn get_untracked(self) -> T
1334 where
1335 T: Clone,
1336 {
1337 untrack(|| self.get())
1338 }
1339
1340 pub fn track(self) {
1342 with_rt(|rt| track_read(rt, self.key));
1343 }
1344
1345 #[track_caller]
1346 pub fn set(self, value: T) {
1347 self.write_check(move |slot| {
1348 *slot = value;
1349 true
1350 });
1351 }
1352
1353 #[track_caller]
1354 pub fn set_if_changed(self, value: T)
1355 where
1356 T: PartialEq,
1357 {
1358 self.write_check(move |slot| {
1359 if *slot == value {
1360 false
1361 } else {
1362 *slot = value;
1363 true
1364 }
1365 });
1366 }
1367
1368 #[track_caller]
1369 pub fn update(self, f: impl FnOnce(&mut T)) {
1370 self.write_check(move |slot| {
1371 f(slot);
1372 true
1373 });
1374 }
1375
1376 #[track_caller]
1377 fn write_check(self, apply: impl FnOnce(&mut T) -> bool) {
1378 let alive = with_rt(|rt| rt.nodes.contains_key(self.key));
1379 if !alive {
1380 let loc = Location::caller();
1382 let first = with_rt(|rt| rt.warned_writes.insert(std::ptr::from_ref(loc)));
1383 if first && cfg!(debug_assertions) {
1384 log::warn!(
1385 "day-reactive: write at {loc} to a disposed signal (created at {}) ignored",
1386 self.created_at
1387 );
1388 }
1389 return;
1390 }
1391 signal_write_boxed(self.key, |boxed| match boxed.downcast_mut::<T>() {
1392 Some(slot) => apply(slot),
1393 None => false,
1394 });
1395 }
1396
1397 #[must_use]
1399 pub fn setter(self) -> Setter<T>
1400 where
1401 T: Send,
1402 {
1403 Setter {
1404 key: self.key,
1405 _m: PhantomData,
1406 }
1407 }
1408}
1409
1410pub struct Setter<T: Send + 'static> {
1413 key: NodeKey,
1414 _m: PhantomData<fn(T)>,
1415}
1416
1417impl<T: Send + 'static> Clone for Setter<T> {
1418 fn clone(&self) -> Self {
1419 *self
1420 }
1421}
1422impl<T: Send + 'static> Copy for Setter<T> {}
1423
1424impl<T: Send + 'static> Setter<T> {
1425 pub fn set(self, value: T) {
1426 let key = self.key;
1427 on_main(move || {
1428 let poster = with_rt(|rt| {
1429 let cell = rt.nodes.get(key)?.value.clone()?;
1430 {
1431 let mut boxed = cell.try_borrow_mut().ok()?;
1432 let slot = boxed.downcast_mut::<T>()?;
1433 *slot = value;
1434 }
1435 let node = rt.nodes.get_mut(key)?;
1436 node.last_changed = rt.tick;
1437 rt.tick += 1;
1438 mark_observers(rt, key, NodeState::Dirty);
1439 schedule_after_write(rt)
1440 });
1441 if let Some(post) = poster {
1442 post();
1443 }
1444 });
1445 }
1446}
1447
1448pub struct Memo<T: 'static> {
1454 key: NodeKey,
1455 created_at: &'static Location<'static>,
1456 _m: PhantomData<*const T>,
1457}
1458
1459impl<T: 'static> Clone for Memo<T> {
1460 fn clone(&self) -> Self {
1461 *self
1462 }
1463}
1464impl<T: 'static> Copy for Memo<T> {}
1465
1466impl<T: 'static> Memo<T> {
1467 #[track_caller]
1468 pub fn new(f: impl Fn() -> T + 'static) -> Self
1469 where
1470 T: PartialEq,
1471 {
1472 Self::new_with_eq(f, |a, b| a == b)
1473 }
1474
1475 #[track_caller]
1476 pub fn new_with_eq(f: impl Fn() -> T + 'static, eq: fn(&T, &T) -> bool) -> Self {
1477 let created_at = Location::caller();
1478 let key = with_rt(|rt| {
1481 let scope = rt.current_scope;
1482 create_node(rt, NodeKind::Memo, scope)
1483 });
1484 let compute: Rc<dyn Fn() -> Box<dyn Any>> =
1485 Rc::new(move || Box::new(EqBox { value: f(), eq }) as Box<dyn Any>);
1486 with_rt(|rt| {
1487 let node = &mut rt.nodes[key];
1488 node.memo_compute = Some(compute);
1489 node.memo_eq = Some(eqbox_eq::<T>);
1490 node.state = NodeState::Dirty; node.created_at = created_at;
1492 });
1493 Memo {
1494 key,
1495 created_at,
1496 _m: PhantomData,
1497 }
1498 }
1499
1500 #[track_caller]
1506 pub fn with<R>(self, f: impl FnOnce(&T) -> R) -> R {
1507 refresh_memo(self.key);
1508 let value = with_rt(|rt| {
1509 track_read(rt, self.key);
1510 rt.nodes.get(self.key).and_then(|n| n.value.clone())
1511 });
1512 match value {
1513 Some(cell) => {
1515 let boxed = cell.borrow();
1516 boxed.downcast_ref::<EqBox<T>>().map_or_else(
1517 || panic!("day-reactive: memo type mismatch"),
1518 |e| f(&e.value),
1519 )
1520 }
1521 None => panic!(
1522 "day-reactive: read of disposed Memo created at {}",
1523 self.created_at
1524 ),
1525 }
1526 }
1527
1528 #[track_caller]
1529 #[must_use]
1530 pub fn get(self) -> T
1531 where
1532 T: Clone,
1533 {
1534 self.with(std::clone::Clone::clone)
1535 }
1536}
1537
1538struct EqBox<T> {
1540 value: T,
1541 eq: fn(&T, &T) -> bool,
1542}
1543
1544fn eqbox_eq<T: 'static>(a: &dyn Any, b: &dyn Any) -> bool {
1545 match (a.downcast_ref::<EqBox<T>>(), b.downcast_ref::<EqBox<T>>()) {
1546 (Some(a), Some(b)) => (a.eq)(&a.value, &b.value),
1547 _ => false,
1548 }
1549}
1550
1551pub struct Effect;
1559
1560impl Effect {
1561 #[allow(clippy::new_ret_no_self)]
1564 #[track_caller]
1565 pub fn new(f: impl Fn() + 'static) {
1566 create_reaction(Rc::new(f), 1);
1567 }
1568}
1569
1570#[track_caller]
1571fn create_reaction(f: Rc<dyn Fn()>, priority: u8) -> NodeKey {
1572 let created_at = Location::caller();
1573 let key = with_rt(|rt| {
1574 let scope = rt.current_scope;
1575 let k = create_node(rt, NodeKind::Reaction, scope);
1576 rt.nodes[k].reaction = Some(f);
1577 rt.nodes[k].priority = priority;
1578 rt.nodes[k].created_at = created_at;
1579 k
1580 });
1581 let reaction = with_rt(|rt| rt.nodes[key].reaction.clone());
1582 if let Some(reaction) = reaction {
1583 compute_in_owner(key, || reaction());
1584 }
1585 with_rt(|rt| {
1586 let tick = rt.tick;
1587 rt.tick += 1;
1588 if let Some(n) = rt.nodes.get_mut(key) {
1589 n.last_run = tick;
1590 }
1591 });
1592 key
1593}
1594
1595#[track_caller]
1599pub fn bind<V: PartialEq + 'static>(
1600 compute: impl Fn() -> V + 'static,
1601 apply: impl Fn(&V) + 'static,
1602) {
1603 let last: RefCell<Option<V>> = RefCell::new(None);
1604 create_reaction(
1605 Rc::new(move || {
1606 let v = compute();
1607 if last.borrow().as_ref() != Some(&v) {
1608 untrack(|| apply(&v));
1609 *last.borrow_mut() = Some(v);
1610 }
1611 }),
1612 0,
1613 );
1614}
1615
1616#[track_caller]
1619pub fn bind_seeded<V: PartialEq + 'static>(
1620 seed: V,
1621 compute: impl Fn() -> V + 'static,
1622 apply: impl Fn(&V) + 'static,
1623) {
1624 let last: RefCell<Option<V>> = RefCell::new(Some(seed));
1625 create_reaction(
1626 Rc::new(move || {
1627 let v = compute();
1628 if last.borrow().as_ref() != Some(&v) {
1629 untrack(|| apply(&v));
1630 *last.borrow_mut() = Some(v);
1631 }
1632 }),
1633 0,
1634 );
1635}
1636
1637#[track_caller]
1639pub fn bind_always<V: 'static>(compute: impl Fn() -> V + 'static, apply: impl Fn(V) + 'static) {
1640 create_reaction(
1641 Rc::new(move || {
1642 let v = compute();
1643 untrack(|| apply(v));
1644 }),
1645 0,
1646 );
1647}
1648
1649#[track_caller]
1654pub fn watch<S: Clone + 'static>(
1655 source: impl Fn() -> S + 'static,
1656 cb: impl Fn(&S, Option<&S>) + 'static,
1657) {
1658 let prev: RefCell<Option<S>> = RefCell::new(None);
1659 create_reaction(
1660 Rc::new(move || {
1661 let new = source();
1662 let old = prev.borrow_mut().replace(new.clone());
1663 if old.is_some() {
1664 untrack(|| cb(&new, old.as_ref()));
1665 }
1666 }),
1667 1,
1668 );
1669}
1670
1671#[derive(Clone, Copy)]
1673pub struct Trigger {
1674 signal: Signal<u64>,
1675}
1676
1677impl Trigger {
1678 #[track_caller]
1679 #[must_use]
1680 pub fn new() -> Self {
1681 Trigger {
1682 signal: Signal::new(0),
1683 }
1684 }
1685 pub fn track(self) {
1686 self.signal.track();
1687 }
1688 pub fn notify(self) {
1689 self.signal.update(|v| *v = v.wrapping_add(1));
1690 }
1691}
1692
1693impl Default for Trigger {
1694 fn default() -> Self {
1695 Self::new()
1696 }
1697}
1698
1699pub trait Binding<T: 'static>: Clone + 'static {
1709 fn read(&self) -> T;
1711 fn peek(&self) -> T;
1713 fn write(&self, v: T);
1715 fn write_preview(&self, v: T) {
1719 self.write(v);
1720 }
1721 fn write_commit(&self, v: T) {
1725 self.write(v);
1726 }
1727 fn write_teardown(&self, v: T) {
1730 self.write_commit(v);
1731 }
1732 fn end_preview(&self) {}
1737}
1738
1739impl<T: Clone + 'static> Binding<T> for Signal<T> {
1740 fn read(&self) -> T {
1741 self.get()
1742 }
1743 fn peek(&self) -> T {
1744 self.get_untracked()
1745 }
1746 fn write(&self, v: T) {
1747 self.set(v);
1748 }
1749 fn write_teardown(&self, _v: T) {}
1750}
1751
1752trait ErasedBinding<T: 'static> {
1755 fn erased_read(&self) -> T;
1756 fn erased_peek(&self) -> T;
1757 fn erased_write(&self, v: T);
1758 fn erased_write_preview(&self, v: T);
1759 fn erased_write_commit(&self, v: T);
1760 fn erased_write_teardown(&self, v: T);
1761 fn erased_end_preview(&self);
1762}
1763
1764impl<T: 'static, B: Binding<T>> ErasedBinding<T> for B {
1765 fn erased_read(&self) -> T {
1766 Binding::read(self)
1767 }
1768 fn erased_peek(&self) -> T {
1769 Binding::peek(self)
1770 }
1771 fn erased_write(&self, v: T) {
1772 Binding::write(self, v);
1773 }
1774 fn erased_write_preview(&self, v: T) {
1775 Binding::write_preview(self, v);
1776 }
1777 fn erased_write_commit(&self, v: T) {
1778 Binding::write_commit(self, v);
1779 }
1780 fn erased_write_teardown(&self, v: T) {
1781 Binding::write_teardown(self, v);
1782 }
1783 fn erased_end_preview(&self) {
1784 Binding::end_preview(self);
1785 }
1786}
1787
1788pub struct AnyBinding<T: 'static> {
1796 slot: Signal<Rc<dyn ErasedBinding<T>>>,
1797}
1798
1799impl<T: 'static> Clone for AnyBinding<T> {
1800 fn clone(&self) -> Self {
1801 *self
1802 }
1803}
1804impl<T: 'static> Copy for AnyBinding<T> {}
1805
1806impl<T: 'static> AnyBinding<T> {
1807 pub fn new(binding: impl Binding<T>) -> Self {
1809 let erased: Rc<dyn ErasedBinding<T>> = Rc::new(binding);
1810 AnyBinding {
1811 slot: Signal::new(erased),
1812 }
1813 }
1814 fn inner(self) -> Rc<dyn ErasedBinding<T>> {
1815 self.slot.get_untracked()
1816 }
1817 #[must_use]
1819 pub fn get(self) -> T {
1820 self.inner().erased_read()
1821 }
1822 #[must_use]
1824 pub fn try_get(self) -> Option<T> {
1825 self.slot.try_get().map(|b| b.erased_read())
1826 }
1827 #[must_use]
1829 pub fn get_untracked(self) -> T {
1830 self.inner().erased_peek()
1831 }
1832 pub fn with<R>(self, f: impl FnOnce(&T) -> R) -> R {
1834 let v = self.inner().erased_read();
1835 f(&v)
1836 }
1837 pub fn set(self, v: T) {
1839 self.inner().erased_write(v);
1840 }
1841 pub fn set_if_changed(self, v: T)
1843 where
1844 T: PartialEq,
1845 {
1846 let b = self.inner();
1847 if b.erased_peek() != v {
1848 b.erased_write(v);
1849 }
1850 }
1851 pub fn update(self, f: impl FnOnce(&mut T)) {
1853 let b = self.inner();
1854 let mut v = b.erased_peek();
1855 f(&mut v);
1856 b.erased_write(v);
1857 }
1858}
1859
1860impl<T: 'static> Binding<T> for AnyBinding<T> {
1861 fn read(&self) -> T {
1862 self.inner().erased_read()
1863 }
1864 fn peek(&self) -> T {
1865 self.inner().erased_peek()
1866 }
1867 fn write(&self, v: T) {
1868 self.inner().erased_write(v);
1869 }
1870 fn write_preview(&self, v: T) {
1871 self.inner().erased_write_preview(v);
1872 }
1873 fn write_commit(&self, v: T) {
1874 self.inner().erased_write_commit(v);
1875 }
1876 fn write_teardown(&self, v: T) {
1877 self.inner().erased_write_teardown(v);
1878 }
1879 fn end_preview(&self) {
1880 self.inner().erased_end_preview();
1881 }
1882}
1883
1884#[derive(Clone)]
1891pub enum Load<T> {
1892 Loading,
1893 Ready(T),
1894 Failed(Arc<dyn std::error::Error + Send + Sync>),
1895}
1896
1897impl<T> Load<T> {
1898 pub fn ready(&self) -> Option<&T> {
1900 match self {
1901 Load::Ready(v) => Some(v),
1902 _ => None,
1903 }
1904 }
1905 pub fn is_loading(&self) -> bool {
1906 matches!(self, Load::Loading)
1907 }
1908 pub fn is_ready(&self) -> bool {
1909 matches!(self, Load::Ready(_))
1910 }
1911 pub fn error(&self) -> Option<&(dyn std::error::Error + Send + Sync + 'static)> {
1913 match self {
1914 Load::Failed(e) => Some(e.as_ref()),
1915 _ => None,
1916 }
1917 }
1918}
1919
1920impl<T: std::fmt::Debug> std::fmt::Debug for Load<T> {
1921 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1922 match self {
1923 Load::Loading => write!(f, "Loading"),
1924 Load::Ready(v) => f.debug_tuple("Ready").field(v).finish(),
1925 Load::Failed(e) => f.debug_tuple("Failed").field(&e.to_string()).finish(),
1926 }
1927 }
1928}
1929
1930struct FetchState {
1932 generation: Cell<u64>,
1933 abort: RefCell<Option<Box<dyn FnOnce()>>>,
1934}
1935
1936impl FetchState {
1937 fn supersede(&self) -> u64 {
1941 let next = self.generation.get() + 1;
1942 self.generation.set(next);
1943 let old = self.abort.borrow_mut().take();
1944 if let Some(abort) = old {
1945 abort();
1946 }
1947 next
1948 }
1949}
1950
1951pub struct Resource<T: 'static> {
1966 state: Signal<Load<T>>,
1967 refetch_count: Signal<u64>,
1968 _not_send: PhantomData<*const T>,
1969}
1970
1971impl<T> Clone for Resource<T> {
1972 fn clone(&self) -> Self {
1973 *self
1974 }
1975}
1976impl<T> Copy for Resource<T> {}
1977
1978impl<T: 'static> Resource<T> {
1979 #[track_caller]
1984 pub fn new<S, Fut, E>(
1985 source: impl Fn() -> S + 'static,
1986 fetcher: impl Fn(S) -> Fut + 'static,
1987 ) -> Resource<T>
1988 where
1989 S: Clone + PartialEq + 'static,
1990 Fut: Future<Output = Result<T, E>> + 'static,
1991 E: std::error::Error + Send + Sync + 'static,
1992 {
1993 let state: Signal<Load<T>> = Signal::new(Load::Loading);
1994 let refetch_count: Signal<u64> = Signal::new(0);
1995 let fs = Rc::new(FetchState {
1996 generation: Cell::new(0),
1997 abort: RefCell::new(None),
1998 });
1999 let reaction_fs = fs.clone();
2000 let prev: RefCell<Option<(S, u64)>> = RefCell::new(None);
2001 create_reaction(
2002 Rc::new(move || {
2003 let count = refetch_count.get();
2006 let s = source();
2007 let fs = reaction_fs.clone();
2008 untrack(|| {
2009 let same = prev
2013 .borrow()
2014 .as_ref()
2015 .is_some_and(|(ps, pc)| ps == &s && *pc == count);
2016 if same {
2017 return;
2018 }
2019 *prev.borrow_mut() = Some((s.clone(), count));
2020 let my_generation = fs.supersede();
2021 state.set(Load::Loading);
2022 let fut = fetcher(s);
2023 let done = fs.clone();
2024 let abort = spawn_local(Box::pin(async move {
2025 let result = fut.await;
2026 if done.generation.get() != my_generation {
2027 return; }
2029 done.abort.borrow_mut().take(); match result {
2031 Ok(v) => state.set(Load::Ready(v)),
2032 Err(e) => state.set(Load::Failed(Arc::new(e))),
2033 }
2034 }));
2035 *fs.abort.borrow_mut() = Some(abort);
2040 });
2041 }),
2042 1,
2043 );
2044 let cleanup_fs = fs;
2048 Scope::current().on_cleanup(move || {
2049 cleanup_fs.supersede();
2050 });
2051 Resource {
2052 state,
2053 refetch_count,
2054 _not_send: PhantomData,
2055 }
2056 }
2057
2058 #[must_use]
2060 pub fn signal(self) -> Signal<Load<T>> {
2061 self.state
2062 }
2063
2064 #[must_use]
2066 pub fn get(self) -> Load<T>
2067 where
2068 T: Clone,
2069 {
2070 self.state.get()
2071 }
2072
2073 pub fn with<R>(self, f: impl FnOnce(&Load<T>) -> R) -> R {
2075 self.state.with(f)
2076 }
2077
2078 pub fn loading(self) -> bool {
2080 self.with(Load::is_loading)
2081 }
2082
2083 pub fn ready(self) -> bool {
2085 self.with(Load::is_ready)
2086 }
2087
2088 pub fn refetch(self) {
2090 self.refetch_count.update(|c| *c = c.wrapping_add(1));
2091 }
2092}
2093
2094#[cfg(test)]
2099mod tests {
2100 use super::*;
2101 use std::cell::Cell as StdCell;
2102 use std::rc::Rc;
2103
2104 fn counter() -> (Rc<StdCell<u32>>, impl Fn()) {
2105 let c = Rc::new(StdCell::new(0));
2106 let c2 = c.clone();
2107 (c, move || c2.set(c2.get() + 1))
2108 }
2109
2110 #[test]
2111 fn signal_get_set() {
2112 let s = Signal::new(1);
2113 assert_eq!(s.get(), 1);
2114 s.set(5);
2115 assert_eq!(s.get(), 5);
2116 s.update(|v| *v += 1);
2117 assert_eq!(s.get(), 6);
2118 }
2119
2120 #[test]
2121 fn signal_teardown_does_not_write_after_scope_disposal() {
2122 let scope = Scope::child();
2123 let warned = with_rt(|rt| rt.warned_writes.len());
2124 scope.enter(|| {
2125 let signal = Signal::new(String::new());
2126 signal.write_preview("Fixture final edit".into());
2127 assert_eq!(signal.peek(), "Fixture final edit");
2128 Scope::current().on_cleanup(move || {
2129 signal.write_teardown("Fixture final edit".into());
2130 });
2131 });
2132 scope.dispose();
2133 assert_eq!(with_rt(|rt| rt.warned_writes.len()), warned);
2134 }
2135
2136 #[test]
2137 fn persistent_binding_teardown_seals_preview() {
2138 #[derive(Clone)]
2139 struct FixtureBinding(Rc<RefCell<Vec<String>>>);
2140 impl Binding<String> for FixtureBinding {
2141 fn read(&self) -> String {
2142 String::new()
2143 }
2144 fn peek(&self) -> String {
2145 self.read()
2146 }
2147 fn write(&self, value: String) {
2148 self.0.borrow_mut().push(value);
2149 }
2150 fn write_preview(&self, _value: String) {}
2151 }
2152 let committed = Rc::new(RefCell::new(Vec::new()));
2153 let binding = FixtureBinding(committed.clone());
2154 let scope = Scope::child();
2155 scope.enter(|| {
2156 binding.write_preview("Fixture edit".into());
2157 Scope::current().on_cleanup(move || binding.write_teardown("Fixture edit".into()));
2158 });
2159 assert!(committed.borrow().is_empty());
2160 scope.dispose();
2161 assert_eq!(*committed.borrow(), ["Fixture edit"]);
2162 }
2163
2164 #[test]
2165 fn effect_reruns_on_change() {
2166 let s = Signal::new(1);
2167 let (count, bump) = counter();
2168 Effect::new(move || {
2169 s.track();
2170 bump();
2171 });
2172 assert_eq!(count.get(), 1); batch(|| s.set(2));
2174 assert_eq!(count.get(), 2);
2175 batch(|| s.set(3));
2176 assert_eq!(count.get(), 3);
2177 }
2178
2179 #[test]
2180 fn batch_coalesces() {
2181 let s = Signal::new(0);
2182 let (count, bump) = counter();
2183 Effect::new(move || {
2184 s.track();
2185 bump();
2186 });
2187 batch(|| {
2188 s.set(1);
2189 s.set(2);
2190 s.set(3);
2191 });
2192 assert_eq!(count.get(), 2); assert_eq!(s.get(), 3);
2194 }
2195
2196 #[test]
2197 fn set_if_changed_no_op() {
2198 let s = Signal::new(7);
2199 let (count, bump) = counter();
2200 Effect::new(move || {
2201 s.track();
2202 bump();
2203 });
2204 batch(|| s.set_if_changed(7));
2205 assert_eq!(count.get(), 1); }
2207
2208 #[test]
2209 fn memo_caches_and_diffs() {
2210 let s = Signal::new(1);
2211 let computes = Rc::new(StdCell::new(0));
2212 let c2 = computes.clone();
2213 let doubled = Memo::new(move || {
2214 c2.set(c2.get() + 1);
2215 s.get() * 2
2216 });
2217 assert_eq!(doubled.get(), 2);
2218 assert_eq!(doubled.get(), 2);
2219 assert_eq!(computes.get(), 1); let (effect_runs, bump) = counter();
2221 Effect::new(move || {
2222 let _ = doubled.get();
2223 bump();
2224 });
2225 assert_eq!(effect_runs.get(), 1);
2226 batch(|| s.set(1)); assert_eq!(effect_runs.get(), 1); batch(|| s.set(5));
2230 assert_eq!(doubled.get(), 10);
2231 assert_eq!(effect_runs.get(), 2);
2232 }
2233
2234 #[test]
2235 fn bind_applies_on_change_only() {
2236 let s = Signal::new(1);
2237 let applied: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
2238 let a2 = applied.clone();
2239 bind(
2240 move || s.get().to_string(),
2241 move |v| a2.borrow_mut().push(v.clone()),
2242 );
2243 assert_eq!(*applied.borrow(), vec!["1"]);
2244 batch(|| s.set(2));
2245 assert_eq!(*applied.borrow(), vec!["1", "2"]);
2246 batch(|| s.update(|v| *v = 2)); assert_eq!(*applied.borrow(), vec!["1", "2"]);
2248 }
2249
2250 #[test]
2251 fn watch_skips_initial_and_passes_old() {
2252 type Log = Rc<RefCell<Vec<(i32, Option<i32>)>>>;
2253 let s = Signal::new(10);
2254 let log: Log = Rc::new(RefCell::new(Vec::new()));
2255 let l2 = log.clone();
2256 watch(
2257 move || s.get(),
2258 move |new, old| l2.borrow_mut().push((*new, old.copied())),
2259 );
2260 assert!(log.borrow().is_empty());
2261 batch(|| s.set(11));
2262 assert_eq!(*log.borrow(), vec![(11, Some(10))]);
2263 }
2264
2265 #[test]
2266 fn scope_dispose_stops_effects_and_write_is_noop() {
2267 let s = Signal::new(0);
2268 let (count, bump) = counter();
2269 let scope = Scope::child();
2270 let inner = scope.enter(|| {
2271 let inner = Signal::new(1);
2272 Effect::new(move || {
2273 s.track();
2274 bump();
2275 });
2276 inner
2277 });
2278 assert_eq!(count.get(), 1);
2279 batch(|| s.set(1));
2280 assert_eq!(count.get(), 2);
2281 scope.dispose();
2282 batch(|| s.set(2));
2283 assert_eq!(count.get(), 2); inner.set(9); assert_eq!(inner.try_get(), None);
2286 }
2287
2288 #[test]
2289 fn dispose_during_drain_skips_pending() {
2290 let s = Signal::new(0);
2291 let scope = Scope::child();
2292 let (count, bump) = counter();
2293 let scope_cell = Rc::new(StdCell::new(Some(scope)));
2295 let sc = scope_cell.clone();
2296 Effect::new(move || {
2297 if s.get() == 1
2298 && let Some(scope) = sc.take()
2299 {
2300 scope.dispose();
2301 }
2302 });
2303 scope.enter(|| {
2304 Effect::new(move || {
2305 s.track();
2306 bump();
2307 });
2308 });
2309 assert_eq!(count.get(), 1);
2310 batch(|| s.set(1));
2311 assert_eq!(count.get(), 1);
2314 }
2315
2316 #[test]
2317 fn fixpoint_extends_drain() {
2318 let a = Signal::new(0);
2319 let b = Signal::new(0);
2320 let (count, bump) = counter();
2321 Effect::new(move || {
2322 if a.get() == 1 {
2323 b.set(1); }
2325 });
2326 Effect::new(move || {
2327 b.track();
2328 bump();
2329 });
2330 assert_eq!(count.get(), 1);
2331 batch(|| a.set(1));
2332 assert_eq!(count.get(), 2);
2333 assert_eq!(b.get(), 1);
2334 }
2335
2336 #[cfg(debug_assertions)]
2339 #[test]
2340 #[should_panic(expected = "re-ran more than")]
2341 fn rerun_cap_panics_in_debug() {
2342 let s = Signal::new(0);
2343 Effect::new(move || {
2344 let v = s.get();
2345 s.set(v + 1); });
2347 batch(|| s.set(1));
2348 }
2349
2350 #[test]
2351 fn context_provides_down() {
2352 #[derive(Clone, PartialEq, Debug)]
2353 struct Theme(u32);
2354 let scope = Scope::child();
2355 scope.provide(Theme(7));
2356 let child = scope.create_child();
2357 assert_eq!(child.use_context::<Theme>(), Some(Theme(7)));
2358 scope.dispose();
2359 }
2360
2361 #[test]
2362 fn trigger_notifies() {
2363 let t = Trigger::new();
2364 let (count, bump) = counter();
2365 Effect::new(move || {
2366 t.track();
2367 bump();
2368 });
2369 batch(|| t.notify());
2370 assert_eq!(count.get(), 2);
2371 }
2372
2373 #[test]
2374 fn turn_end_runs_after_fixpoint() {
2375 let s = Signal::new(0);
2376 let order: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
2377 let o1 = order.clone();
2378 Effect::new(move || {
2379 s.track();
2380 o1.borrow_mut().push("effect");
2381 });
2382 let o2 = order.clone();
2383 on_turn_end(move || o2.borrow_mut().push("turn-end"));
2384 order.borrow_mut().clear();
2385 batch(|| s.set(1));
2386 assert_eq!(*order.borrow(), vec!["effect", "turn-end"]);
2387 }
2388
2389 #[test]
2390 fn at_turn_end_waits_for_the_turn_and_runs_once() {
2391 let s = Signal::new(0);
2392 let order: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
2393 let o = order.clone();
2395 at_turn_end(move || o.borrow_mut().push("now".into()));
2396 assert_eq!(*order.borrow(), vec!["now".to_string()]);
2397 order.borrow_mut().clear();
2398 let o1 = order.clone();
2400 Effect::new(move || {
2401 let v = s.get();
2402 o1.borrow_mut().push(format!("effect {v}"));
2403 });
2404 let o2 = order.clone();
2405 on_turn_end(move || o2.borrow_mut().push("standing".into()));
2406 order.borrow_mut().clear();
2407 let o3 = order.clone();
2408 batch(|| {
2409 at_turn_end(move || o3.borrow_mut().push("once".into()));
2410 s.set(1);
2411 });
2412 assert_eq!(*order.borrow(), vec!["effect 1", "once", "standing"]);
2413 order.borrow_mut().clear();
2415 let o4 = order.clone();
2416 batch(|| at_turn_end(move || o4.borrow_mut().push("quiet".into())));
2417 assert_eq!(*order.borrow(), vec!["quiet", "standing"]);
2418 }
2419
2420 #[test]
2421 fn bindings_run_before_effects() {
2422 let s = Signal::new(0);
2423 let order: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
2424 let o1 = order.clone();
2425 Effect::new(move || {
2427 s.track();
2428 o1.borrow_mut().push("effect");
2429 });
2430 let o2 = order.clone();
2431 bind(move || s.get(), move |_| o2.borrow_mut().push("bind"));
2432 order.borrow_mut().clear();
2433 batch(|| s.set(1));
2434 assert_eq!(*order.borrow(), vec!["bind", "effect"]);
2435 }
2436}
2437
2438#[cfg(test)]
2439mod resource_tests {
2440 use super::*;
2441 use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
2442
2443 thread_local! {
2449 static TEST_TASKS: RefCell<Vec<(u64, Option<LocalBoxFuture>)>> =
2450 const { RefCell::new(Vec::new()) };
2451 static NEXT_ID: Cell<u64> = const { Cell::new(1) };
2452 static ABORTED: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
2453 static INSTALLED: Cell<bool> = const { Cell::new(false) };
2454 }
2455
2456 fn noop_waker() -> Waker {
2457 fn raw() -> RawWaker {
2458 RawWaker::new(std::ptr::null(), &VT)
2459 }
2460 static VT: RawWakerVTable = RawWakerVTable::new(|_| raw(), |_| {}, |_| {}, |_| {});
2461 unsafe { Waker::from_raw(raw()) }
2463 }
2464
2465 fn poll_one(fut: &mut LocalBoxFuture) -> bool {
2466 let waker = noop_waker();
2467 let mut cx = Context::from_waker(&waker);
2468 fut.as_mut().poll(&mut cx).is_ready()
2469 }
2470
2471 fn install_test_spawner() {
2472 if INSTALLED.with(|c| c.replace(true)) {
2473 return;
2474 }
2475 install_spawner(|mut fut| {
2476 let id = NEXT_ID.with(|c| {
2477 let v = c.get();
2478 c.set(v + 1);
2479 v
2480 });
2481 if !poll_one(&mut fut) {
2482 TEST_TASKS.with(|t| t.borrow_mut().push((id, Some(fut))));
2483 }
2484 Box::new(move || {
2485 let removed = TEST_TASKS.with(|t| {
2486 let mut t = t.borrow_mut();
2487 let before = t.len();
2488 t.retain(|(i, _)| *i != id);
2489 before != t.len()
2490 });
2491 if removed {
2492 ABORTED.with(|a| a.borrow_mut().push(id));
2493 }
2494 })
2495 });
2496 }
2497
2498 fn aborted_count() -> usize {
2499 ABORTED.with(|a| a.borrow().len())
2500 }
2501
2502 fn pump() {
2504 let ids: Vec<u64> = TEST_TASKS.with(|t| t.borrow().iter().map(|(i, _)| *i).collect());
2505 for id in ids {
2506 let fut = TEST_TASKS.with(|t| {
2507 t.borrow_mut()
2508 .iter_mut()
2509 .find(|(i, _)| *i == id)
2510 .and_then(|(_, s)| s.take())
2511 });
2512 let Some(mut fut) = fut else { continue };
2513 if poll_one(&mut fut) {
2514 TEST_TASKS.with(|t| t.borrow_mut().retain(|(i, _)| *i != id));
2515 } else {
2516 TEST_TASKS.with(|t| {
2517 if let Some((_, s)) = t.borrow_mut().iter_mut().find(|(i, _)| *i == id) {
2518 *s = Some(fut);
2519 }
2520 });
2521 }
2522 }
2523 flush_sync();
2526 }
2527
2528 type Slot<T> = Rc<RefCell<Option<Result<T, TestErr>>>>;
2529
2530 fn manual_future<T: 'static>(slot: Slot<T>) -> impl Future<Output = Result<T, TestErr>> {
2533 std::future::poll_fn(move |_| match slot.borrow_mut().take() {
2534 Some(r) => Poll::Ready(r),
2535 None => Poll::Pending,
2536 })
2537 }
2538
2539 #[derive(Debug)]
2540 struct TestErr(&'static str);
2541 impl std::fmt::Display for TestErr {
2542 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2543 write!(f, "{}", self.0)
2544 }
2545 }
2546 impl std::error::Error for TestErr {}
2547
2548 #[test]
2549 fn resource_sync_fetcher_is_ready_immediately() {
2550 install_test_spawner();
2551 let r = Resource::new(|| (), |()| async { Ok::<_, std::convert::Infallible>(42) });
2552 assert!(r.ready());
2553 assert_eq!(r.with(|l| l.ready().copied()), Some(42));
2554 }
2555
2556 #[test]
2557 fn resource_loading_then_ready() {
2558 install_test_spawner();
2559 let slot: Slot<i32> = Rc::new(RefCell::new(None));
2560 let s2 = slot.clone();
2561 let r = Resource::new(move || (), move |()| manual_future(s2.clone()));
2562 assert!(r.loading());
2563 *slot.borrow_mut() = Some(Ok(7));
2564 pump();
2565 assert_eq!(r.with(|l| l.ready().copied()), Some(7));
2566 }
2567
2568 #[test]
2569 fn resource_failed_preserves_error() {
2570 install_test_spawner();
2571 let r = Resource::new(|| (), |()| async { Err::<i32, _>(TestErr("boom")) });
2572 assert!(!r.ready());
2573 assert_eq!(
2574 r.with(|l| l.error().map(std::string::ToString::to_string)),
2575 Some("boom".into())
2576 );
2577 }
2578
2579 #[test]
2580 fn resource_refetches_on_source_change() {
2581 install_test_spawner();
2582 let src = Signal::new(1i32);
2583 let fetches = Rc::new(Cell::new(0));
2584 let f = fetches.clone();
2585 let r = Resource::new(
2586 move || src.get(),
2587 move |v| {
2588 f.set(f.get() + 1);
2589 async move { Ok::<_, TestErr>(v * 10) }
2590 },
2591 );
2592 assert_eq!(fetches.get(), 1);
2593 assert_eq!(r.with(|l| l.ready().copied()), Some(10));
2594 batch(|| src.set(2));
2595 assert_eq!(fetches.get(), 2);
2596 assert_eq!(r.with(|l| l.ready().copied()), Some(20));
2597 }
2598
2599 #[test]
2600 fn resource_source_equality_gates() {
2601 install_test_spawner();
2602 let a = Signal::new(1i32);
2603 let b = Signal::new(10i32);
2604 let fetches = Rc::new(Cell::new(0));
2605 let f = fetches.clone();
2606 let r = Resource::new(
2607 move || {
2608 let _ = b.get(); a.get()
2610 },
2611 move |v| {
2612 f.set(f.get() + 1);
2613 async move { Ok::<_, TestErr>(v) }
2614 },
2615 );
2616 assert_eq!(fetches.get(), 1);
2617 batch(|| b.set(20)); assert_eq!(fetches.get(), 1);
2619 assert_eq!(r.with(|l| l.ready().copied()), Some(1));
2620 batch(|| a.set(2)); assert_eq!(fetches.get(), 2);
2622 }
2623
2624 #[test]
2625 fn resource_refetch_forces() {
2626 install_test_spawner();
2627 let fetches = Rc::new(Cell::new(0));
2628 let f = fetches.clone();
2629 let r = Resource::new(
2630 || (),
2631 move |()| {
2632 f.set(f.get() + 1);
2633 async { Ok::<_, TestErr>(0) }
2634 },
2635 );
2636 assert_eq!(fetches.get(), 1);
2637 batch(|| r.refetch()); assert_eq!(fetches.get(), 2);
2639 }
2640
2641 #[test]
2642 fn resource_latest_wins() {
2643 install_test_spawner();
2644 let src = Signal::new(1i32);
2645 let slots: Rc<RefCell<Vec<Slot<i32>>>> = Rc::new(RefCell::new(Vec::new()));
2646 let sl = slots.clone();
2647 let r = Resource::new(
2648 move || src.get(),
2649 move |_| {
2650 let slot: Slot<i32> = Rc::new(RefCell::new(None));
2651 sl.borrow_mut().push(slot.clone());
2652 manual_future(slot)
2653 },
2654 );
2655 assert!(r.loading());
2656 let before = aborted_count();
2657 batch(|| src.set(2)); assert_eq!(aborted_count(), before + 1, "the stale task was aborted");
2659 *slots.borrow()[0].borrow_mut() = Some(Ok(111));
2661 pump();
2662 assert!(r.loading(), "a stale result writes nothing");
2663 *slots.borrow()[1].borrow_mut() = Some(Ok(222));
2664 pump();
2665 assert_eq!(r.with(|l| l.ready().copied()), Some(222));
2666 }
2667
2668 #[test]
2669 fn resource_scope_disposal_aborts() {
2670 install_test_spawner();
2671 let scope = Scope::child();
2672 let slot: Slot<i32> = Rc::new(RefCell::new(None));
2673 let s2 = slot.clone();
2674 let r = scope.enter(|| Resource::new(move || (), move |()| manual_future(s2.clone())));
2675 assert!(r.loading());
2676 let before = aborted_count();
2677 scope.dispose();
2678 assert_eq!(aborted_count(), before + 1, "disposal aborted the fetch");
2679 *slot.borrow_mut() = Some(Ok(1));
2681 pump();
2682 }
2683
2684 #[test]
2685 fn resource_ready_is_tracked() {
2686 install_test_spawner();
2687 let slot: Slot<i32> = Rc::new(RefCell::new(None));
2688 let s2 = slot.clone();
2689 let r = Resource::new(move || (), move |()| manual_future(s2.clone()));
2690 let runs = Rc::new(Cell::new(0));
2691 let rn = runs.clone();
2692 Effect::new(move || {
2693 let _ = r.ready();
2694 rn.set(rn.get() + 1);
2695 });
2696 assert_eq!(runs.get(), 1);
2697 *slot.borrow_mut() = Some(Ok(1));
2698 pump();
2699 assert!(runs.get() >= 2, "ready() re-ran the effect on completion");
2700 }
2701
2702 #[test]
2703 #[should_panic(expected = "no spawner installed")]
2704 fn spawner_missing_panics() {
2705 let _r = Resource::new(|| (), |()| async { Ok::<_, std::convert::Infallible>(1) });
2707 }
2708}
2709
2710#[cfg(test)]
2711mod unwind_safety_tests {
2712 use super::*;
2713
2714 fn contained(f: impl FnOnce() + std::panic::UnwindSafe) {
2716 let prev = std::panic::take_hook();
2717 std::panic::set_hook(Box::new(|_| {}));
2718 let r = std::panic::catch_unwind(f);
2719 std::panic::set_hook(prev);
2720 assert!(r.is_err(), "expected the closure to panic");
2721 }
2722
2723 #[test]
2727 fn panic_in_scope_enter_restores_current_scope() {
2728 let before = with_rt(|rt| rt.current_scope);
2729 let scope = Scope::detached();
2730 contained(|| scope.enter(|| panic!("boom in enter")));
2731 assert_eq!(with_rt(|rt| rt.current_scope), before, "scope not restored");
2732 let s = Signal::new(7u32);
2734 assert_eq!(s.get(), 7);
2735 }
2736
2737 #[test]
2744 fn panic_in_effect_body_pops_its_observer_frame() {
2745 let depth = with_rt(|rt| rt.observers.len());
2746 let boom = Signal::new(false);
2747 Effect::new(move || {
2748 assert!(!boom.get(), "effect boom");
2749 });
2750 assert_eq!(with_rt(|rt| rt.observers.len()), depth);
2751 contained(|| batch(|| boom.set(true)));
2752 assert_eq!(
2753 with_rt(|rt| rt.observers.len()),
2754 depth,
2755 "observer frame stranded by the panicking effect run"
2756 );
2757 recover_from_panic(); }
2759
2760 #[test]
2761 fn panic_in_untrack_restores_tracking() {
2762 let depth = with_rt(|rt| rt.observers.len());
2763 contained(|| untrack(|| panic!("boom in untrack")));
2764 assert_eq!(with_rt(|rt| rt.observers.len()), depth, "observer stranded");
2765
2766 let src = Signal::new(0i32);
2768 let runs = Rc::new(RefCell::new(0));
2769 let r2 = runs.clone();
2770 Effect::new(move || {
2771 let _ = src.get();
2772 *r2.borrow_mut() += 1;
2773 });
2774 flush_sync();
2775 let before = *runs.borrow();
2776 src.set(1);
2777 flush_sync();
2778 assert!(
2779 *runs.borrow() > before,
2780 "effect did not re-run — tracking is off"
2781 );
2782 }
2783
2784 #[test]
2787 fn panic_in_batch_restores_depth() {
2788 let depth = with_rt(|rt| rt.batch_depth);
2789 contained(|| batch(|| panic!("boom in batch")));
2790 assert_eq!(with_rt(|rt| rt.batch_depth), depth, "batch depth stranded");
2791 }
2792
2793 #[test]
2797 fn panic_in_with_leaves_the_value_intact() {
2798 let s = Signal::new(String::from("intact"));
2799 contained(|| s.with(|_| panic!("boom in with")));
2800 assert_eq!(s.with(std::clone::Clone::clone), "intact");
2801 }
2802
2803 #[test]
2806 fn reentrant_read_inside_with_succeeds() {
2807 let s = Signal::new(5u32);
2808 let doubled = s.with(|outer| *outer + s.with(|inner| *inner));
2809 assert_eq!(doubled, 10);
2810 assert_eq!(
2811 s.with(|v| *v),
2812 5,
2813 "value still in place after the nested read"
2814 );
2815 }
2816
2817 #[test]
2820 fn nested_reads_of_distinct_signals_succeed() {
2821 let a = Signal::new(2u32);
2822 let b = Signal::new(3u32);
2823 assert_eq!(a.with(|x| *x * b.with(|y| *y)), 6);
2824 }
2825
2826 #[test]
2828 fn write_during_read_panics_with_a_clear_message() {
2829 let s = Signal::new(1u32);
2830 let prev = std::panic::take_hook();
2831 std::panic::set_hook(Box::new(|_| {}));
2832 let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2833 s.with(|_| s.set(2));
2834 }));
2835 std::panic::set_hook(prev);
2836 let payload = r.unwrap_err();
2837 let msg = payload
2839 .downcast_ref::<&str>()
2840 .map(std::string::ToString::to_string)
2841 .or_else(|| payload.downcast_ref::<String>().cloned())
2842 .expect("panic payload should be a string");
2843 assert!(
2844 msg.contains("in flight") && msg.contains("Signal"),
2845 "message should name the cause, got: {msg}"
2846 );
2847 }
2848
2849 #[cfg(not(debug_assertions))]
2854 #[test]
2855 fn rerun_cap_defers_instead_of_killing_the_binding() {
2856 let s = Signal::new(0u32);
2857 let runs = std::rc::Rc::new(std::cell::Cell::new(0u32));
2858 let r2 = runs.clone();
2859 Effect::new(move || {
2860 let v = s.get();
2861 r2.set(r2.get() + 1);
2862 if v < 1_000_000 {
2863 s.set(v + 1); }
2865 });
2866 flush_sync();
2867 let after_cycle = runs.get();
2868 assert!(
2869 after_cycle <= RERUN_CAP + 1,
2870 "cap did not bound the drain: {after_cycle} runs"
2871 );
2872
2873 batch(|| s.set(2_000_000)); assert_eq!(
2876 runs.get(),
2877 after_cycle + 1,
2878 "binding stayed dead after hitting the re-run cap"
2879 );
2880 }
2881}
2882
2883#[cfg(test)]
2884mod owner_scope_tests {
2885 use super::*;
2886
2887 #[test]
2888 fn reactions_and_lazy_memos_keep_their_owner_and_restore_the_caller() {
2889 let outer = Scope::child();
2890 outer.provide("outer fixture");
2891 let first = outer.create_child();
2892 let second = outer.create_child();
2893 first.provide("first fixture");
2894 second.provide("second fixture");
2895 let source = Signal::new(0);
2896 let seen = Rc::new(RefCell::new(Vec::new()));
2897 let lazy = first.enter(|| {
2898 Memo::new(move || {
2899 (
2900 source.get(),
2901 Scope::current().use_context::<&str>().unwrap(),
2902 )
2903 })
2904 });
2905 let nested = second.enter(|| {
2906 Memo::new(move || (lazy.get(), Scope::current().use_context::<&str>().unwrap()))
2907 });
2908 second.enter(|| assert_eq!(lazy.get(), (0, "first fixture")));
2909 assert_eq!(nested.get(), ((0, "first fixture"), "second fixture"));
2910 for (scope, name) in [(first, "first fixture"), (second, "second fixture")] {
2911 let seen = seen.clone();
2912 scope.enter(|| {
2913 Effect::new(move || {
2914 seen.borrow_mut()
2915 .push((source.get(), Scope::current().use_context::<&str>()));
2916 assert_eq!(Scope::current().use_context::<&str>(), Some(name));
2917 });
2918 });
2919 }
2920 second.enter(|| {
2921 batch(|| source.set(1));
2922 assert_eq!(
2923 Scope::current().use_context::<&str>(),
2924 Some("second fixture")
2925 );
2926 });
2927 assert_eq!(nested.get(), ((1, "first fixture"), "second fixture"));
2928 assert_eq!(seen.borrow().len(), 4);
2929 outer.dispose();
2930 batch(|| source.set(2));
2931 assert_eq!(seen.borrow().len(), 4, "disposed reactions must not run");
2932 }
2933
2934 #[test]
2935 fn watches_allocate_state_and_cleanup_in_their_owner() {
2936 let owner = Scope::child();
2937 let trigger = Signal::new(0);
2938 let allocated = Rc::new(Cell::new(None::<Signal<i32>>));
2939 let cleaned = Rc::new(Cell::new(0));
2940 owner.enter(|| {
2941 let allocated = allocated.clone();
2942 let cleaned = cleaned.clone();
2943 watch(
2944 move || trigger.get(),
2945 move |value, _| {
2946 allocated.set(Some(Signal::new(*value)));
2947 let cleaned = cleaned.clone();
2948 Scope::current().on_cleanup(move || cleaned.set(cleaned.get() + 1));
2949 },
2950 );
2951 });
2952 batch(|| trigger.set(1));
2953 let state = allocated.get().unwrap();
2954 assert_eq!(state.get(), 1);
2955 owner.dispose();
2956 assert_eq!(cleaned.get(), 1);
2957 assert!(state.try_get().is_none());
2958 }
2959
2960 #[test]
2961 fn panic_in_owned_computations_restores_scope_and_tracking() {
2962 let owner = Scope::child();
2963 owner.provide("owner fixture");
2964 let caller = Scope::child();
2965 caller.provide("caller fixture");
2966 let trigger = Signal::new(false);
2967 let memo = owner.enter(|| {
2968 Memo::new(move || {
2969 assert_eq!(
2970 Scope::current().use_context::<&str>(),
2971 Some("owner fixture")
2972 );
2973 assert!(!trigger.get(), "synthetic memo failure");
2974 7
2975 })
2976 });
2977 assert_eq!(memo.get(), 7);
2978 batch(|| trigger.set(true));
2979 caller.enter(|| {
2980 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| memo.get()));
2981 assert!(result.is_err());
2982 assert_eq!(
2983 Scope::current().use_context::<&str>(),
2984 Some("caller fixture")
2985 );
2986 assert!(with_rt(|rt| rt.observers.is_empty()));
2987 });
2988 owner.dispose();
2989 caller.dispose();
2990 }
2991}