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"))]
939mod delayed {
940 use std::sync::{Mutex, PoisonError};
941 use std::thread::ThreadId;
942 use std::time::{Duration, Instant};
943
944 type Job = Box<dyn FnOnce() + Send>;
945
946 struct Entry {
947 due: Instant,
948 seq: u64,
950 thread: ThreadId,
952 job: Job,
953 }
954
955 struct Queue {
956 waiting: Vec<Entry>,
957 next_seq: u64,
958 }
959
960 static QUEUE: Mutex<Queue> = Mutex::new(Queue {
961 waiting: Vec::new(),
962 next_seq: 0,
963 });
964
965 pub(super) fn arm(ms: u32, job: Job) -> Job {
967 let due = Instant::now() + Duration::from_millis(u64::from(ms));
968 let seq = {
969 let mut queue = QUEUE.lock().unwrap_or_else(PoisonError::into_inner);
970 let seq = queue.next_seq;
971 queue.next_seq += 1;
972 queue.waiting.push(Entry {
973 due,
974 seq,
975 thread: std::thread::current().id(),
976 job,
977 });
978 seq
979 };
980 Box::new(move || run_due(seq, due))
981 }
982
983 fn run_due(own_seq: u64, own: Instant) {
987 let until = own.max(Instant::now());
988 let here = std::thread::current().id();
989 loop {
990 let job = {
992 let mut queue = QUEUE.lock().unwrap_or_else(PoisonError::into_inner);
993 queue
994 .waiting
995 .iter()
996 .enumerate()
997 .filter(|(_, e)| e.seq == own_seq || (e.thread == here && e.due <= until))
998 .min_by_key(|(_, e)| (e.due, e.seq))
999 .map(|(at, _)| at)
1000 .map(|at| queue.waiting.swap_remove(at).job)
1001 };
1002 let Some(job) = job else { break };
1003 job();
1004 }
1005 }
1006
1007 #[cfg(test)]
1008 mod tests {
1009 use super::*;
1010 use std::sync::Arc;
1011
1012 #[test]
1015 fn overdue_timers_run_in_deadline_order_whatever_order_they_fire_in() {
1016 let ran = Arc::new(Mutex::new(Vec::new()));
1017 let mut timers = Vec::new();
1018 for ms in [200u32, 10, 100, 50] {
1019 let ran = ran.clone();
1020 timers.push(arm(ms, Box::new(move || ran.lock().unwrap().push(ms))));
1021 }
1022 std::thread::sleep(Duration::from_millis(230));
1024 for timer in timers {
1025 timer();
1026 }
1027 assert_eq!(*ran.lock().unwrap(), [10, 50, 100, 200]);
1028 }
1029
1030 #[test]
1032 fn a_timer_runs_its_own_closure_and_nothing_due_later() {
1033 let ran = Arc::new(Mutex::new(Vec::new()));
1034 let note = |tag: &'static str| {
1035 let ran = ran.clone();
1036 Box::new(move || ran.lock().unwrap().push(tag)) as Job
1037 };
1038 let soon = arm(0, note("soon"));
1039 let later = arm(60_000, note("later"));
1040 soon();
1041 assert_eq!(*ran.lock().unwrap(), ["soon"]);
1042 later();
1044 assert_eq!(*ran.lock().unwrap(), ["soon", "later"]);
1045 }
1046
1047 #[test]
1050 fn a_timer_leaves_another_threads_closures_alone() {
1051 let ran = Arc::new(Mutex::new(Vec::new()));
1052 let theirs = {
1053 let ran = ran.clone();
1054 std::thread::spawn(move || {
1055 arm(0, Box::new(move || ran.lock().unwrap().push("theirs")))
1056 })
1057 .join()
1058 .unwrap()
1059 };
1060 let mine = {
1061 let ran = ran.clone();
1062 arm(60_000, Box::new(move || ran.lock().unwrap().push("mine")))
1063 };
1064 mine();
1065 assert_eq!(*ran.lock().unwrap(), ["mine"]);
1066 theirs();
1068 assert_eq!(*ran.lock().unwrap(), ["mine", "theirs"]);
1069 }
1070 }
1071}
1072
1073#[derive(Clone, Copy, PartialEq, Eq)]
1079pub struct Scope {
1080 key: ScopeKey,
1081 _not_send: PhantomData<*const ()>,
1082}
1083
1084impl Scope {
1085 pub fn current() -> Scope {
1086 Scope {
1087 key: with_rt(|rt| rt.current_scope),
1088 _not_send: PhantomData,
1089 }
1090 }
1091
1092 pub fn root() -> Scope {
1093 Scope {
1094 key: with_rt(|rt| rt.root_scope),
1095 _not_send: PhantomData,
1096 }
1097 }
1098
1099 pub fn child() -> Scope {
1101 Scope::current().create_child()
1102 }
1103
1104 #[must_use]
1105 pub fn create_child(self) -> Scope {
1106 let key = with_rt(|rt| {
1107 let depth = rt.scopes.get(self.key).map_or(1, |s| s.depth + 1);
1108 let child = rt.scopes.insert(ScopeData {
1109 parent: self.key,
1110 children: Vec::new(),
1111 nodes: Vec::new(),
1112 cleanups: Vec::new(),
1113 context: HashMap::new(),
1114 depth,
1115 });
1116 if let Some(p) = rt.scopes.get_mut(self.key) {
1117 p.children.push(child);
1118 }
1119 child
1120 });
1121 Scope {
1122 key,
1123 _not_send: PhantomData,
1124 }
1125 }
1126
1127 pub fn detached() -> Scope {
1129 let key = with_rt(|rt| {
1130 rt.scopes.insert(ScopeData {
1131 parent: ScopeKey::null(),
1132 children: Vec::new(),
1133 nodes: Vec::new(),
1134 cleanups: Vec::new(),
1135 context: HashMap::new(),
1136 depth: 0,
1137 })
1138 });
1139 Scope {
1140 key,
1141 _not_send: PhantomData,
1142 }
1143 }
1144
1145 pub fn enter<R>(self, f: impl FnOnce() -> R) -> R {
1147 let prev = with_rt(|rt| std::mem::replace(&mut rt.current_scope, self.key));
1148 let _g = rt_guard(move |rt: &mut Runtime| rt.current_scope = prev);
1152 f()
1153 }
1154
1155 pub fn on_cleanup(self, f: impl FnOnce() + 'static) {
1156 with_rt(|rt| {
1157 if let Some(s) = rt.scopes.get_mut(self.key) {
1158 s.cleanups.push(Box::new(f));
1159 }
1160 });
1161 }
1162
1163 #[must_use]
1164 pub fn is_alive(self) -> bool {
1165 with_rt(|rt| rt.scopes.contains_key(self.key))
1166 }
1167
1168 pub fn dispose(self) {
1170 let Some(children) = with_rt(|rt| rt.scopes.get(self.key).map(|s| s.children.clone()))
1171 else {
1172 return;
1173 };
1174 for c in children {
1175 (Scope {
1176 key: c,
1177 _not_send: PhantomData,
1178 })
1179 .dispose();
1180 }
1181 let Some((nodes, cleanups, parent)) = with_rt(|rt| {
1182 rt.scopes
1183 .remove(self.key)
1184 .map(|s| (s.nodes, s.cleanups, s.parent))
1185 }) else {
1186 return;
1187 };
1188 let mut run_cleanups: Vec<Box<dyn FnOnce()>> = Vec::new();
1189 with_rt(|rt| {
1190 if let Some(p) = rt.scopes.get_mut(parent)
1191 && let Some(pos) = p.children.iter().position(|&c| c == self.key)
1192 {
1193 p.children.swap_remove(pos);
1194 }
1195 for key in nodes {
1196 run_cleanups.extend(clear_sources(rt, key));
1197 if let Some(node) = rt.nodes.get_mut(key) {
1199 let observers = std::mem::take(&mut node.observers);
1200 for o in observers {
1201 if let Some(on) = rt.nodes.get_mut(o)
1202 && let Some(pos) = on.sources.iter().position(|&s| s == key)
1203 {
1204 on.sources.swap_remove(pos);
1205 }
1206 }
1207 }
1208 rt.nodes.remove(key);
1209 }
1211 });
1212 for f in run_cleanups {
1215 f();
1216 }
1217 for c in cleanups {
1218 c();
1219 }
1220 }
1221
1222 pub fn provide<T: 'static>(self, value: T) {
1224 with_rt(|rt| {
1225 if let Some(s) = rt.scopes.get_mut(self.key) {
1226 s.context.insert(TypeId::of::<T>(), Box::new(value));
1227 }
1228 });
1229 }
1230
1231 #[must_use]
1233 pub fn use_context<T: Clone + 'static>(self) -> Option<T> {
1234 with_rt(|rt| {
1235 let mut cur = self.key;
1236 while let Some(s) = rt.scopes.get(cur) {
1237 if let Some(v) = s.context.get(&TypeId::of::<T>()) {
1238 return v.downcast_ref::<T>().cloned();
1239 }
1240 cur = s.parent;
1241 }
1242 None
1243 })
1244 }
1245}
1246
1247pub struct Signal<T: 'static> {
1253 key: NodeKey,
1254 created_at: &'static Location<'static>,
1255 _m: PhantomData<*const T>,
1256}
1257
1258impl<T: 'static> Clone for Signal<T> {
1259 fn clone(&self) -> Self {
1260 *self
1261 }
1262}
1263impl<T: 'static> Copy for Signal<T> {}
1264
1265impl<T: 'static> std::fmt::Debug for Signal<T> {
1266 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1267 write!(f, "Signal({:?})", self.key)
1268 }
1269}
1270
1271impl<T: 'static> Signal<T> {
1272 #[track_caller]
1273 pub fn new(value: T) -> Self {
1274 Self::new_in(Scope::current(), value)
1275 }
1276
1277 #[track_caller]
1284 pub fn global(value: T) -> Self {
1285 Self::new_in(Scope::root(), value)
1286 }
1287
1288 #[track_caller]
1289 pub fn new_in(scope: Scope, value: T) -> Self {
1290 let created_at = Location::caller();
1291 let key = with_rt(|rt| {
1292 let k = create_node(rt, NodeKind::Signal, scope.key);
1293 rt.nodes[k].value = Some(Rc::new(RefCell::new(Box::new(value) as Box<dyn Any>)));
1294 rt.nodes[k].created_at = created_at;
1295 k
1296 });
1297 Signal {
1298 key,
1299 created_at,
1300 _m: PhantomData,
1301 }
1302 }
1303
1304 #[track_caller]
1311 pub fn with<R>(self, f: impl FnOnce(&T) -> R) -> R {
1312 match self.try_with(f) {
1313 Some(r) => r,
1314 None => panic!(
1315 "day-reactive: read of disposed Signal created at {} (use try_with in closures that can outlive their scope)",
1316 self.created_at
1317 ),
1318 }
1319 }
1320
1321 pub fn try_with<R>(self, f: impl FnOnce(&T) -> R) -> Option<R> {
1322 let cell = with_rt(|rt| {
1327 track_read(rt, self.key);
1328 rt.nodes.get(self.key).and_then(|n| n.value.clone())
1329 })?;
1330 let value = cell.borrow();
1331 value.downcast_ref::<T>().map(f)
1332 }
1333
1334 pub fn with_untracked<R>(self, f: impl FnOnce(&T) -> R) -> R {
1335 untrack(|| self.with(f))
1336 }
1337
1338 #[track_caller]
1339 #[must_use]
1340 pub fn get(self) -> T
1341 where
1342 T: Clone,
1343 {
1344 self.with(std::clone::Clone::clone)
1345 }
1346
1347 #[must_use]
1348 pub fn try_get(self) -> Option<T>
1349 where
1350 T: Clone,
1351 {
1352 self.try_with(std::clone::Clone::clone)
1353 }
1354
1355 #[must_use]
1356 pub fn get_untracked(self) -> T
1357 where
1358 T: Clone,
1359 {
1360 untrack(|| self.get())
1361 }
1362
1363 pub fn track(self) {
1365 with_rt(|rt| track_read(rt, self.key));
1366 }
1367
1368 #[track_caller]
1369 pub fn set(self, value: T) {
1370 self.write_check(move |slot| {
1371 *slot = value;
1372 true
1373 });
1374 }
1375
1376 #[track_caller]
1377 pub fn set_if_changed(self, value: T)
1378 where
1379 T: PartialEq,
1380 {
1381 self.write_check(move |slot| {
1382 if *slot == value {
1383 false
1384 } else {
1385 *slot = value;
1386 true
1387 }
1388 });
1389 }
1390
1391 #[track_caller]
1392 pub fn update(self, f: impl FnOnce(&mut T)) {
1393 self.write_check(move |slot| {
1394 f(slot);
1395 true
1396 });
1397 }
1398
1399 #[track_caller]
1400 fn write_check(self, apply: impl FnOnce(&mut T) -> bool) {
1401 let alive = with_rt(|rt| rt.nodes.contains_key(self.key));
1402 if !alive {
1403 let loc = Location::caller();
1405 let first = with_rt(|rt| rt.warned_writes.insert(std::ptr::from_ref(loc)));
1406 if first && cfg!(debug_assertions) {
1407 log::warn!(
1408 "day-reactive: write at {loc} to a disposed signal (created at {}) ignored",
1409 self.created_at
1410 );
1411 }
1412 return;
1413 }
1414 signal_write_boxed(self.key, |boxed| match boxed.downcast_mut::<T>() {
1415 Some(slot) => apply(slot),
1416 None => false,
1417 });
1418 }
1419
1420 #[must_use]
1422 pub fn setter(self) -> Setter<T>
1423 where
1424 T: Send,
1425 {
1426 Setter {
1427 key: self.key,
1428 _m: PhantomData,
1429 }
1430 }
1431}
1432
1433pub struct Setter<T: Send + 'static> {
1436 key: NodeKey,
1437 _m: PhantomData<fn(T)>,
1438}
1439
1440impl<T: Send + 'static> Clone for Setter<T> {
1441 fn clone(&self) -> Self {
1442 *self
1443 }
1444}
1445impl<T: Send + 'static> Copy for Setter<T> {}
1446
1447impl<T: Send + 'static> Setter<T> {
1448 pub fn set(self, value: T) {
1449 let key = self.key;
1450 on_main(move || {
1451 let poster = with_rt(|rt| {
1452 let cell = rt.nodes.get(key)?.value.clone()?;
1453 {
1454 let mut boxed = cell.try_borrow_mut().ok()?;
1455 let slot = boxed.downcast_mut::<T>()?;
1456 *slot = value;
1457 }
1458 let node = rt.nodes.get_mut(key)?;
1459 node.last_changed = rt.tick;
1460 rt.tick += 1;
1461 mark_observers(rt, key, NodeState::Dirty);
1462 schedule_after_write(rt)
1463 });
1464 if let Some(post) = poster {
1465 post();
1466 }
1467 });
1468 }
1469}
1470
1471pub struct Memo<T: 'static> {
1477 key: NodeKey,
1478 created_at: &'static Location<'static>,
1479 _m: PhantomData<*const T>,
1480}
1481
1482impl<T: 'static> Clone for Memo<T> {
1483 fn clone(&self) -> Self {
1484 *self
1485 }
1486}
1487impl<T: 'static> Copy for Memo<T> {}
1488
1489impl<T: 'static> Memo<T> {
1490 #[track_caller]
1491 pub fn new(f: impl Fn() -> T + 'static) -> Self
1492 where
1493 T: PartialEq,
1494 {
1495 Self::new_with_eq(f, |a, b| a == b)
1496 }
1497
1498 #[track_caller]
1499 pub fn new_with_eq(f: impl Fn() -> T + 'static, eq: fn(&T, &T) -> bool) -> Self {
1500 let created_at = Location::caller();
1501 let key = with_rt(|rt| {
1504 let scope = rt.current_scope;
1505 create_node(rt, NodeKind::Memo, scope)
1506 });
1507 let compute: Rc<dyn Fn() -> Box<dyn Any>> =
1508 Rc::new(move || Box::new(EqBox { value: f(), eq }) as Box<dyn Any>);
1509 with_rt(|rt| {
1510 let node = &mut rt.nodes[key];
1511 node.memo_compute = Some(compute);
1512 node.memo_eq = Some(eqbox_eq::<T>);
1513 node.state = NodeState::Dirty; node.created_at = created_at;
1515 });
1516 Memo {
1517 key,
1518 created_at,
1519 _m: PhantomData,
1520 }
1521 }
1522
1523 #[track_caller]
1529 pub fn with<R>(self, f: impl FnOnce(&T) -> R) -> R {
1530 refresh_memo(self.key);
1531 let value = with_rt(|rt| {
1532 track_read(rt, self.key);
1533 rt.nodes.get(self.key).and_then(|n| n.value.clone())
1534 });
1535 match value {
1536 Some(cell) => {
1538 let boxed = cell.borrow();
1539 boxed.downcast_ref::<EqBox<T>>().map_or_else(
1540 || panic!("day-reactive: memo type mismatch"),
1541 |e| f(&e.value),
1542 )
1543 }
1544 None => panic!(
1545 "day-reactive: read of disposed Memo created at {}",
1546 self.created_at
1547 ),
1548 }
1549 }
1550
1551 #[track_caller]
1552 #[must_use]
1553 pub fn get(self) -> T
1554 where
1555 T: Clone,
1556 {
1557 self.with(std::clone::Clone::clone)
1558 }
1559}
1560
1561struct EqBox<T> {
1563 value: T,
1564 eq: fn(&T, &T) -> bool,
1565}
1566
1567fn eqbox_eq<T: 'static>(a: &dyn Any, b: &dyn Any) -> bool {
1568 match (a.downcast_ref::<EqBox<T>>(), b.downcast_ref::<EqBox<T>>()) {
1569 (Some(a), Some(b)) => (a.eq)(&a.value, &b.value),
1570 _ => false,
1571 }
1572}
1573
1574pub struct Effect;
1582
1583impl Effect {
1584 #[allow(clippy::new_ret_no_self)]
1587 #[track_caller]
1588 pub fn new(f: impl Fn() + 'static) {
1589 create_reaction(Rc::new(f), 1);
1590 }
1591}
1592
1593#[track_caller]
1594fn create_reaction(f: Rc<dyn Fn()>, priority: u8) -> NodeKey {
1595 let created_at = Location::caller();
1596 let key = with_rt(|rt| {
1597 let scope = rt.current_scope;
1598 let k = create_node(rt, NodeKind::Reaction, scope);
1599 rt.nodes[k].reaction = Some(f);
1600 rt.nodes[k].priority = priority;
1601 rt.nodes[k].created_at = created_at;
1602 k
1603 });
1604 let reaction = with_rt(|rt| rt.nodes[key].reaction.clone());
1605 if let Some(reaction) = reaction {
1606 compute_in_owner(key, || reaction());
1607 }
1608 with_rt(|rt| {
1609 let tick = rt.tick;
1610 rt.tick += 1;
1611 if let Some(n) = rt.nodes.get_mut(key) {
1612 n.last_run = tick;
1613 }
1614 });
1615 key
1616}
1617
1618#[track_caller]
1622pub fn bind<V: PartialEq + 'static>(
1623 compute: impl Fn() -> V + 'static,
1624 apply: impl Fn(&V) + 'static,
1625) {
1626 let last: RefCell<Option<V>> = RefCell::new(None);
1627 create_reaction(
1628 Rc::new(move || {
1629 let v = compute();
1630 if last.borrow().as_ref() != Some(&v) {
1631 untrack(|| apply(&v));
1632 *last.borrow_mut() = Some(v);
1633 }
1634 }),
1635 0,
1636 );
1637}
1638
1639#[track_caller]
1642pub fn bind_seeded<V: PartialEq + 'static>(
1643 seed: V,
1644 compute: impl Fn() -> V + 'static,
1645 apply: impl Fn(&V) + 'static,
1646) {
1647 let last: RefCell<Option<V>> = RefCell::new(Some(seed));
1648 create_reaction(
1649 Rc::new(move || {
1650 let v = compute();
1651 if last.borrow().as_ref() != Some(&v) {
1652 untrack(|| apply(&v));
1653 *last.borrow_mut() = Some(v);
1654 }
1655 }),
1656 0,
1657 );
1658}
1659
1660#[track_caller]
1662pub fn bind_always<V: 'static>(compute: impl Fn() -> V + 'static, apply: impl Fn(V) + 'static) {
1663 create_reaction(
1664 Rc::new(move || {
1665 let v = compute();
1666 untrack(|| apply(v));
1667 }),
1668 0,
1669 );
1670}
1671
1672#[track_caller]
1677pub fn watch<S: Clone + 'static>(
1678 source: impl Fn() -> S + 'static,
1679 cb: impl Fn(&S, Option<&S>) + 'static,
1680) {
1681 let prev: RefCell<Option<S>> = RefCell::new(None);
1682 create_reaction(
1683 Rc::new(move || {
1684 let new = source();
1685 let old = prev.borrow_mut().replace(new.clone());
1686 if old.is_some() {
1687 untrack(|| cb(&new, old.as_ref()));
1688 }
1689 }),
1690 1,
1691 );
1692}
1693
1694#[derive(Clone, Copy)]
1696pub struct Trigger {
1697 signal: Signal<u64>,
1698}
1699
1700impl Trigger {
1701 #[track_caller]
1702 #[must_use]
1703 pub fn new() -> Self {
1704 Trigger {
1705 signal: Signal::new(0),
1706 }
1707 }
1708 pub fn track(self) {
1709 self.signal.track();
1710 }
1711 pub fn notify(self) {
1712 self.signal.update(|v| *v = v.wrapping_add(1));
1713 }
1714}
1715
1716impl Default for Trigger {
1717 fn default() -> Self {
1718 Self::new()
1719 }
1720}
1721
1722pub trait Binding<T: 'static>: Clone + 'static {
1732 fn read(&self) -> T;
1734 fn peek(&self) -> T;
1736 fn write(&self, v: T);
1738 fn write_preview(&self, v: T) {
1742 self.write(v);
1743 }
1744 fn write_commit(&self, v: T) {
1748 self.write(v);
1749 }
1750 fn write_teardown(&self, v: T) {
1753 self.write_commit(v);
1754 }
1755 fn end_preview(&self) {}
1760}
1761
1762impl<T: Clone + 'static> Binding<T> for Signal<T> {
1763 fn read(&self) -> T {
1764 self.get()
1765 }
1766 fn peek(&self) -> T {
1767 self.get_untracked()
1768 }
1769 fn write(&self, v: T) {
1770 self.set(v);
1771 }
1772 fn write_teardown(&self, _v: T) {}
1773}
1774
1775trait ErasedBinding<T: 'static> {
1778 fn erased_read(&self) -> T;
1779 fn erased_peek(&self) -> T;
1780 fn erased_write(&self, v: T);
1781 fn erased_write_preview(&self, v: T);
1782 fn erased_write_commit(&self, v: T);
1783 fn erased_write_teardown(&self, v: T);
1784 fn erased_end_preview(&self);
1785}
1786
1787impl<T: 'static, B: Binding<T>> ErasedBinding<T> for B {
1788 fn erased_read(&self) -> T {
1789 Binding::read(self)
1790 }
1791 fn erased_peek(&self) -> T {
1792 Binding::peek(self)
1793 }
1794 fn erased_write(&self, v: T) {
1795 Binding::write(self, v);
1796 }
1797 fn erased_write_preview(&self, v: T) {
1798 Binding::write_preview(self, v);
1799 }
1800 fn erased_write_commit(&self, v: T) {
1801 Binding::write_commit(self, v);
1802 }
1803 fn erased_write_teardown(&self, v: T) {
1804 Binding::write_teardown(self, v);
1805 }
1806 fn erased_end_preview(&self) {
1807 Binding::end_preview(self);
1808 }
1809}
1810
1811pub struct AnyBinding<T: 'static> {
1819 slot: Signal<Rc<dyn ErasedBinding<T>>>,
1820}
1821
1822impl<T: 'static> Clone for AnyBinding<T> {
1823 fn clone(&self) -> Self {
1824 *self
1825 }
1826}
1827impl<T: 'static> Copy for AnyBinding<T> {}
1828
1829impl<T: 'static> AnyBinding<T> {
1830 pub fn new(binding: impl Binding<T>) -> Self {
1832 let erased: Rc<dyn ErasedBinding<T>> = Rc::new(binding);
1833 AnyBinding {
1834 slot: Signal::new(erased),
1835 }
1836 }
1837 fn inner(self) -> Rc<dyn ErasedBinding<T>> {
1838 self.slot.get_untracked()
1839 }
1840 #[must_use]
1842 pub fn get(self) -> T {
1843 self.inner().erased_read()
1844 }
1845 #[must_use]
1847 pub fn try_get(self) -> Option<T> {
1848 self.slot.try_get().map(|b| b.erased_read())
1849 }
1850 #[must_use]
1852 pub fn get_untracked(self) -> T {
1853 self.inner().erased_peek()
1854 }
1855 pub fn with<R>(self, f: impl FnOnce(&T) -> R) -> R {
1857 let v = self.inner().erased_read();
1858 f(&v)
1859 }
1860 pub fn set(self, v: T) {
1862 self.inner().erased_write(v);
1863 }
1864 pub fn set_if_changed(self, v: T)
1866 where
1867 T: PartialEq,
1868 {
1869 let b = self.inner();
1870 if b.erased_peek() != v {
1871 b.erased_write(v);
1872 }
1873 }
1874 pub fn update(self, f: impl FnOnce(&mut T)) {
1876 let b = self.inner();
1877 let mut v = b.erased_peek();
1878 f(&mut v);
1879 b.erased_write(v);
1880 }
1881}
1882
1883impl<T: 'static> Binding<T> for AnyBinding<T> {
1884 fn read(&self) -> T {
1885 self.inner().erased_read()
1886 }
1887 fn peek(&self) -> T {
1888 self.inner().erased_peek()
1889 }
1890 fn write(&self, v: T) {
1891 self.inner().erased_write(v);
1892 }
1893 fn write_preview(&self, v: T) {
1894 self.inner().erased_write_preview(v);
1895 }
1896 fn write_commit(&self, v: T) {
1897 self.inner().erased_write_commit(v);
1898 }
1899 fn write_teardown(&self, v: T) {
1900 self.inner().erased_write_teardown(v);
1901 }
1902 fn end_preview(&self) {
1903 self.inner().erased_end_preview();
1904 }
1905}
1906
1907#[derive(Clone)]
1914pub enum Load<T> {
1915 Loading,
1916 Ready(T),
1917 Failed(Arc<dyn std::error::Error + Send + Sync>),
1918}
1919
1920impl<T> Load<T> {
1921 pub fn ready(&self) -> Option<&T> {
1923 match self {
1924 Load::Ready(v) => Some(v),
1925 _ => None,
1926 }
1927 }
1928 pub fn is_loading(&self) -> bool {
1929 matches!(self, Load::Loading)
1930 }
1931 pub fn is_ready(&self) -> bool {
1932 matches!(self, Load::Ready(_))
1933 }
1934 pub fn error(&self) -> Option<&(dyn std::error::Error + Send + Sync + 'static)> {
1936 match self {
1937 Load::Failed(e) => Some(e.as_ref()),
1938 _ => None,
1939 }
1940 }
1941}
1942
1943impl<T: std::fmt::Debug> std::fmt::Debug for Load<T> {
1944 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1945 match self {
1946 Load::Loading => write!(f, "Loading"),
1947 Load::Ready(v) => f.debug_tuple("Ready").field(v).finish(),
1948 Load::Failed(e) => f.debug_tuple("Failed").field(&e.to_string()).finish(),
1949 }
1950 }
1951}
1952
1953struct FetchState {
1955 generation: Cell<u64>,
1956 abort: RefCell<Option<Box<dyn FnOnce()>>>,
1957}
1958
1959impl FetchState {
1960 fn supersede(&self) -> u64 {
1964 let next = self.generation.get() + 1;
1965 self.generation.set(next);
1966 let old = self.abort.borrow_mut().take();
1967 if let Some(abort) = old {
1968 abort();
1969 }
1970 next
1971 }
1972}
1973
1974pub struct Resource<T: 'static> {
1989 state: Signal<Load<T>>,
1990 refetch_count: Signal<u64>,
1991 _not_send: PhantomData<*const T>,
1992}
1993
1994impl<T> Clone for Resource<T> {
1995 fn clone(&self) -> Self {
1996 *self
1997 }
1998}
1999impl<T> Copy for Resource<T> {}
2000
2001impl<T: 'static> Resource<T> {
2002 #[track_caller]
2007 pub fn new<S, Fut, E>(
2008 source: impl Fn() -> S + 'static,
2009 fetcher: impl Fn(S) -> Fut + 'static,
2010 ) -> Resource<T>
2011 where
2012 S: Clone + PartialEq + 'static,
2013 Fut: Future<Output = Result<T, E>> + 'static,
2014 E: std::error::Error + Send + Sync + 'static,
2015 {
2016 let state: Signal<Load<T>> = Signal::new(Load::Loading);
2017 let refetch_count: Signal<u64> = Signal::new(0);
2018 let fs = Rc::new(FetchState {
2019 generation: Cell::new(0),
2020 abort: RefCell::new(None),
2021 });
2022 let reaction_fs = fs.clone();
2023 let prev: RefCell<Option<(S, u64)>> = RefCell::new(None);
2024 create_reaction(
2025 Rc::new(move || {
2026 let count = refetch_count.get();
2029 let s = source();
2030 let fs = reaction_fs.clone();
2031 untrack(|| {
2032 let same = prev
2036 .borrow()
2037 .as_ref()
2038 .is_some_and(|(ps, pc)| ps == &s && *pc == count);
2039 if same {
2040 return;
2041 }
2042 *prev.borrow_mut() = Some((s.clone(), count));
2043 let my_generation = fs.supersede();
2044 state.set(Load::Loading);
2045 let fut = fetcher(s);
2046 let done = fs.clone();
2047 let abort = spawn_local(Box::pin(async move {
2048 let result = fut.await;
2049 if done.generation.get() != my_generation {
2050 return; }
2052 done.abort.borrow_mut().take(); match result {
2054 Ok(v) => state.set(Load::Ready(v)),
2055 Err(e) => state.set(Load::Failed(Arc::new(e))),
2056 }
2057 }));
2058 *fs.abort.borrow_mut() = Some(abort);
2063 });
2064 }),
2065 1,
2066 );
2067 let cleanup_fs = fs;
2071 Scope::current().on_cleanup(move || {
2072 cleanup_fs.supersede();
2073 });
2074 Resource {
2075 state,
2076 refetch_count,
2077 _not_send: PhantomData,
2078 }
2079 }
2080
2081 #[must_use]
2083 pub fn signal(self) -> Signal<Load<T>> {
2084 self.state
2085 }
2086
2087 #[must_use]
2089 pub fn get(self) -> Load<T>
2090 where
2091 T: Clone,
2092 {
2093 self.state.get()
2094 }
2095
2096 pub fn with<R>(self, f: impl FnOnce(&Load<T>) -> R) -> R {
2098 self.state.with(f)
2099 }
2100
2101 pub fn loading(self) -> bool {
2103 self.with(Load::is_loading)
2104 }
2105
2106 pub fn ready(self) -> bool {
2108 self.with(Load::is_ready)
2109 }
2110
2111 pub fn refetch(self) {
2113 self.refetch_count.update(|c| *c = c.wrapping_add(1));
2114 }
2115}
2116
2117#[cfg(test)]
2122mod tests {
2123 use super::*;
2124 use std::cell::Cell as StdCell;
2125 use std::rc::Rc;
2126
2127 fn counter() -> (Rc<StdCell<u32>>, impl Fn()) {
2128 let c = Rc::new(StdCell::new(0));
2129 let c2 = c.clone();
2130 (c, move || c2.set(c2.get() + 1))
2131 }
2132
2133 #[test]
2134 fn signal_get_set() {
2135 let s = Signal::new(1);
2136 assert_eq!(s.get(), 1);
2137 s.set(5);
2138 assert_eq!(s.get(), 5);
2139 s.update(|v| *v += 1);
2140 assert_eq!(s.get(), 6);
2141 }
2142
2143 #[test]
2144 fn signal_teardown_does_not_write_after_scope_disposal() {
2145 let scope = Scope::child();
2146 let warned = with_rt(|rt| rt.warned_writes.len());
2147 scope.enter(|| {
2148 let signal = Signal::new(String::new());
2149 signal.write_preview("Fixture final edit".into());
2150 assert_eq!(signal.peek(), "Fixture final edit");
2151 Scope::current().on_cleanup(move || {
2152 signal.write_teardown("Fixture final edit".into());
2153 });
2154 });
2155 scope.dispose();
2156 assert_eq!(with_rt(|rt| rt.warned_writes.len()), warned);
2157 }
2158
2159 #[test]
2160 fn persistent_binding_teardown_seals_preview() {
2161 #[derive(Clone)]
2162 struct FixtureBinding(Rc<RefCell<Vec<String>>>);
2163 impl Binding<String> for FixtureBinding {
2164 fn read(&self) -> String {
2165 String::new()
2166 }
2167 fn peek(&self) -> String {
2168 self.read()
2169 }
2170 fn write(&self, value: String) {
2171 self.0.borrow_mut().push(value);
2172 }
2173 fn write_preview(&self, _value: String) {}
2174 }
2175 let committed = Rc::new(RefCell::new(Vec::new()));
2176 let binding = FixtureBinding(committed.clone());
2177 let scope = Scope::child();
2178 scope.enter(|| {
2179 binding.write_preview("Fixture edit".into());
2180 Scope::current().on_cleanup(move || binding.write_teardown("Fixture edit".into()));
2181 });
2182 assert!(committed.borrow().is_empty());
2183 scope.dispose();
2184 assert_eq!(*committed.borrow(), ["Fixture edit"]);
2185 }
2186
2187 #[test]
2188 fn effect_reruns_on_change() {
2189 let s = Signal::new(1);
2190 let (count, bump) = counter();
2191 Effect::new(move || {
2192 s.track();
2193 bump();
2194 });
2195 assert_eq!(count.get(), 1); batch(|| s.set(2));
2197 assert_eq!(count.get(), 2);
2198 batch(|| s.set(3));
2199 assert_eq!(count.get(), 3);
2200 }
2201
2202 #[test]
2203 fn batch_coalesces() {
2204 let s = Signal::new(0);
2205 let (count, bump) = counter();
2206 Effect::new(move || {
2207 s.track();
2208 bump();
2209 });
2210 batch(|| {
2211 s.set(1);
2212 s.set(2);
2213 s.set(3);
2214 });
2215 assert_eq!(count.get(), 2); assert_eq!(s.get(), 3);
2217 }
2218
2219 #[test]
2220 fn set_if_changed_no_op() {
2221 let s = Signal::new(7);
2222 let (count, bump) = counter();
2223 Effect::new(move || {
2224 s.track();
2225 bump();
2226 });
2227 batch(|| s.set_if_changed(7));
2228 assert_eq!(count.get(), 1); }
2230
2231 #[test]
2232 fn memo_caches_and_diffs() {
2233 let s = Signal::new(1);
2234 let computes = Rc::new(StdCell::new(0));
2235 let c2 = computes.clone();
2236 let doubled = Memo::new(move || {
2237 c2.set(c2.get() + 1);
2238 s.get() * 2
2239 });
2240 assert_eq!(doubled.get(), 2);
2241 assert_eq!(doubled.get(), 2);
2242 assert_eq!(computes.get(), 1); let (effect_runs, bump) = counter();
2244 Effect::new(move || {
2245 let _ = doubled.get();
2246 bump();
2247 });
2248 assert_eq!(effect_runs.get(), 1);
2249 batch(|| s.set(1)); assert_eq!(effect_runs.get(), 1); batch(|| s.set(5));
2253 assert_eq!(doubled.get(), 10);
2254 assert_eq!(effect_runs.get(), 2);
2255 }
2256
2257 #[test]
2258 fn bind_applies_on_change_only() {
2259 let s = Signal::new(1);
2260 let applied: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
2261 let a2 = applied.clone();
2262 bind(
2263 move || s.get().to_string(),
2264 move |v| a2.borrow_mut().push(v.clone()),
2265 );
2266 assert_eq!(*applied.borrow(), vec!["1"]);
2267 batch(|| s.set(2));
2268 assert_eq!(*applied.borrow(), vec!["1", "2"]);
2269 batch(|| s.update(|v| *v = 2)); assert_eq!(*applied.borrow(), vec!["1", "2"]);
2271 }
2272
2273 #[test]
2274 fn watch_skips_initial_and_passes_old() {
2275 type Log = Rc<RefCell<Vec<(i32, Option<i32>)>>>;
2276 let s = Signal::new(10);
2277 let log: Log = Rc::new(RefCell::new(Vec::new()));
2278 let l2 = log.clone();
2279 watch(
2280 move || s.get(),
2281 move |new, old| l2.borrow_mut().push((*new, old.copied())),
2282 );
2283 assert!(log.borrow().is_empty());
2284 batch(|| s.set(11));
2285 assert_eq!(*log.borrow(), vec![(11, Some(10))]);
2286 }
2287
2288 #[test]
2289 fn scope_dispose_stops_effects_and_write_is_noop() {
2290 let s = Signal::new(0);
2291 let (count, bump) = counter();
2292 let scope = Scope::child();
2293 let inner = scope.enter(|| {
2294 let inner = Signal::new(1);
2295 Effect::new(move || {
2296 s.track();
2297 bump();
2298 });
2299 inner
2300 });
2301 assert_eq!(count.get(), 1);
2302 batch(|| s.set(1));
2303 assert_eq!(count.get(), 2);
2304 scope.dispose();
2305 batch(|| s.set(2));
2306 assert_eq!(count.get(), 2); inner.set(9); assert_eq!(inner.try_get(), None);
2309 }
2310
2311 #[test]
2312 fn dispose_during_drain_skips_pending() {
2313 let s = Signal::new(0);
2314 let scope = Scope::child();
2315 let (count, bump) = counter();
2316 let scope_cell = Rc::new(StdCell::new(Some(scope)));
2318 let sc = scope_cell.clone();
2319 Effect::new(move || {
2320 if s.get() == 1
2321 && let Some(scope) = sc.take()
2322 {
2323 scope.dispose();
2324 }
2325 });
2326 scope.enter(|| {
2327 Effect::new(move || {
2328 s.track();
2329 bump();
2330 });
2331 });
2332 assert_eq!(count.get(), 1);
2333 batch(|| s.set(1));
2334 assert_eq!(count.get(), 1);
2337 }
2338
2339 #[test]
2340 fn fixpoint_extends_drain() {
2341 let a = Signal::new(0);
2342 let b = Signal::new(0);
2343 let (count, bump) = counter();
2344 Effect::new(move || {
2345 if a.get() == 1 {
2346 b.set(1); }
2348 });
2349 Effect::new(move || {
2350 b.track();
2351 bump();
2352 });
2353 assert_eq!(count.get(), 1);
2354 batch(|| a.set(1));
2355 assert_eq!(count.get(), 2);
2356 assert_eq!(b.get(), 1);
2357 }
2358
2359 #[cfg(debug_assertions)]
2362 #[test]
2363 #[should_panic(expected = "re-ran more than")]
2364 fn rerun_cap_panics_in_debug() {
2365 let s = Signal::new(0);
2366 Effect::new(move || {
2367 let v = s.get();
2368 s.set(v + 1); });
2370 batch(|| s.set(1));
2371 }
2372
2373 #[test]
2374 fn context_provides_down() {
2375 #[derive(Clone, PartialEq, Debug)]
2376 struct Theme(u32);
2377 let scope = Scope::child();
2378 scope.provide(Theme(7));
2379 let child = scope.create_child();
2380 assert_eq!(child.use_context::<Theme>(), Some(Theme(7)));
2381 scope.dispose();
2382 }
2383
2384 #[test]
2385 fn trigger_notifies() {
2386 let t = Trigger::new();
2387 let (count, bump) = counter();
2388 Effect::new(move || {
2389 t.track();
2390 bump();
2391 });
2392 batch(|| t.notify());
2393 assert_eq!(count.get(), 2);
2394 }
2395
2396 #[test]
2397 fn turn_end_runs_after_fixpoint() {
2398 let s = Signal::new(0);
2399 let order: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
2400 let o1 = order.clone();
2401 Effect::new(move || {
2402 s.track();
2403 o1.borrow_mut().push("effect");
2404 });
2405 let o2 = order.clone();
2406 on_turn_end(move || o2.borrow_mut().push("turn-end"));
2407 order.borrow_mut().clear();
2408 batch(|| s.set(1));
2409 assert_eq!(*order.borrow(), vec!["effect", "turn-end"]);
2410 }
2411
2412 #[test]
2413 fn at_turn_end_waits_for_the_turn_and_runs_once() {
2414 let s = Signal::new(0);
2415 let order: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
2416 let o = order.clone();
2418 at_turn_end(move || o.borrow_mut().push("now".into()));
2419 assert_eq!(*order.borrow(), vec!["now".to_string()]);
2420 order.borrow_mut().clear();
2421 let o1 = order.clone();
2423 Effect::new(move || {
2424 let v = s.get();
2425 o1.borrow_mut().push(format!("effect {v}"));
2426 });
2427 let o2 = order.clone();
2428 on_turn_end(move || o2.borrow_mut().push("standing".into()));
2429 order.borrow_mut().clear();
2430 let o3 = order.clone();
2431 batch(|| {
2432 at_turn_end(move || o3.borrow_mut().push("once".into()));
2433 s.set(1);
2434 });
2435 assert_eq!(*order.borrow(), vec!["effect 1", "once", "standing"]);
2436 order.borrow_mut().clear();
2438 let o4 = order.clone();
2439 batch(|| at_turn_end(move || o4.borrow_mut().push("quiet".into())));
2440 assert_eq!(*order.borrow(), vec!["quiet", "standing"]);
2441 }
2442
2443 #[test]
2444 fn bindings_run_before_effects() {
2445 let s = Signal::new(0);
2446 let order: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
2447 let o1 = order.clone();
2448 Effect::new(move || {
2450 s.track();
2451 o1.borrow_mut().push("effect");
2452 });
2453 let o2 = order.clone();
2454 bind(move || s.get(), move |_| o2.borrow_mut().push("bind"));
2455 order.borrow_mut().clear();
2456 batch(|| s.set(1));
2457 assert_eq!(*order.borrow(), vec!["bind", "effect"]);
2458 }
2459}
2460
2461#[cfg(test)]
2462mod resource_tests {
2463 use super::*;
2464 use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
2465
2466 thread_local! {
2472 static TEST_TASKS: RefCell<Vec<(u64, Option<LocalBoxFuture>)>> =
2473 const { RefCell::new(Vec::new()) };
2474 static NEXT_ID: Cell<u64> = const { Cell::new(1) };
2475 static ABORTED: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
2476 static INSTALLED: Cell<bool> = const { Cell::new(false) };
2477 }
2478
2479 fn noop_waker() -> Waker {
2480 fn raw() -> RawWaker {
2481 RawWaker::new(std::ptr::null(), &VT)
2482 }
2483 static VT: RawWakerVTable = RawWakerVTable::new(|_| raw(), |_| {}, |_| {}, |_| {});
2484 unsafe { Waker::from_raw(raw()) }
2486 }
2487
2488 fn poll_one(fut: &mut LocalBoxFuture) -> bool {
2489 let waker = noop_waker();
2490 let mut cx = Context::from_waker(&waker);
2491 fut.as_mut().poll(&mut cx).is_ready()
2492 }
2493
2494 fn install_test_spawner() {
2495 if INSTALLED.with(|c| c.replace(true)) {
2496 return;
2497 }
2498 install_spawner(|mut fut| {
2499 let id = NEXT_ID.with(|c| {
2500 let v = c.get();
2501 c.set(v + 1);
2502 v
2503 });
2504 if !poll_one(&mut fut) {
2505 TEST_TASKS.with(|t| t.borrow_mut().push((id, Some(fut))));
2506 }
2507 Box::new(move || {
2508 let removed = TEST_TASKS.with(|t| {
2509 let mut t = t.borrow_mut();
2510 let before = t.len();
2511 t.retain(|(i, _)| *i != id);
2512 before != t.len()
2513 });
2514 if removed {
2515 ABORTED.with(|a| a.borrow_mut().push(id));
2516 }
2517 })
2518 });
2519 }
2520
2521 fn aborted_count() -> usize {
2522 ABORTED.with(|a| a.borrow().len())
2523 }
2524
2525 fn pump() {
2527 let ids: Vec<u64> = TEST_TASKS.with(|t| t.borrow().iter().map(|(i, _)| *i).collect());
2528 for id in ids {
2529 let fut = TEST_TASKS.with(|t| {
2530 t.borrow_mut()
2531 .iter_mut()
2532 .find(|(i, _)| *i == id)
2533 .and_then(|(_, s)| s.take())
2534 });
2535 let Some(mut fut) = fut else { continue };
2536 if poll_one(&mut fut) {
2537 TEST_TASKS.with(|t| t.borrow_mut().retain(|(i, _)| *i != id));
2538 } else {
2539 TEST_TASKS.with(|t| {
2540 if let Some((_, s)) = t.borrow_mut().iter_mut().find(|(i, _)| *i == id) {
2541 *s = Some(fut);
2542 }
2543 });
2544 }
2545 }
2546 flush_sync();
2549 }
2550
2551 type Slot<T> = Rc<RefCell<Option<Result<T, TestErr>>>>;
2552
2553 fn manual_future<T: 'static>(slot: Slot<T>) -> impl Future<Output = Result<T, TestErr>> {
2556 std::future::poll_fn(move |_| match slot.borrow_mut().take() {
2557 Some(r) => Poll::Ready(r),
2558 None => Poll::Pending,
2559 })
2560 }
2561
2562 #[derive(Debug)]
2563 struct TestErr(&'static str);
2564 impl std::fmt::Display for TestErr {
2565 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2566 write!(f, "{}", self.0)
2567 }
2568 }
2569 impl std::error::Error for TestErr {}
2570
2571 #[test]
2572 fn resource_sync_fetcher_is_ready_immediately() {
2573 install_test_spawner();
2574 let r = Resource::new(|| (), |()| async { Ok::<_, std::convert::Infallible>(42) });
2575 assert!(r.ready());
2576 assert_eq!(r.with(|l| l.ready().copied()), Some(42));
2577 }
2578
2579 #[test]
2580 fn resource_loading_then_ready() {
2581 install_test_spawner();
2582 let slot: Slot<i32> = Rc::new(RefCell::new(None));
2583 let s2 = slot.clone();
2584 let r = Resource::new(move || (), move |()| manual_future(s2.clone()));
2585 assert!(r.loading());
2586 *slot.borrow_mut() = Some(Ok(7));
2587 pump();
2588 assert_eq!(r.with(|l| l.ready().copied()), Some(7));
2589 }
2590
2591 #[test]
2592 fn resource_failed_preserves_error() {
2593 install_test_spawner();
2594 let r = Resource::new(|| (), |()| async { Err::<i32, _>(TestErr("boom")) });
2595 assert!(!r.ready());
2596 assert_eq!(
2597 r.with(|l| l.error().map(std::string::ToString::to_string)),
2598 Some("boom".into())
2599 );
2600 }
2601
2602 #[test]
2603 fn resource_refetches_on_source_change() {
2604 install_test_spawner();
2605 let src = Signal::new(1i32);
2606 let fetches = Rc::new(Cell::new(0));
2607 let f = fetches.clone();
2608 let r = Resource::new(
2609 move || src.get(),
2610 move |v| {
2611 f.set(f.get() + 1);
2612 async move { Ok::<_, TestErr>(v * 10) }
2613 },
2614 );
2615 assert_eq!(fetches.get(), 1);
2616 assert_eq!(r.with(|l| l.ready().copied()), Some(10));
2617 batch(|| src.set(2));
2618 assert_eq!(fetches.get(), 2);
2619 assert_eq!(r.with(|l| l.ready().copied()), Some(20));
2620 }
2621
2622 #[test]
2623 fn resource_source_equality_gates() {
2624 install_test_spawner();
2625 let a = Signal::new(1i32);
2626 let b = Signal::new(10i32);
2627 let fetches = Rc::new(Cell::new(0));
2628 let f = fetches.clone();
2629 let r = Resource::new(
2630 move || {
2631 let _ = b.get(); a.get()
2633 },
2634 move |v| {
2635 f.set(f.get() + 1);
2636 async move { Ok::<_, TestErr>(v) }
2637 },
2638 );
2639 assert_eq!(fetches.get(), 1);
2640 batch(|| b.set(20)); assert_eq!(fetches.get(), 1);
2642 assert_eq!(r.with(|l| l.ready().copied()), Some(1));
2643 batch(|| a.set(2)); assert_eq!(fetches.get(), 2);
2645 }
2646
2647 #[test]
2648 fn resource_refetch_forces() {
2649 install_test_spawner();
2650 let fetches = Rc::new(Cell::new(0));
2651 let f = fetches.clone();
2652 let r = Resource::new(
2653 || (),
2654 move |()| {
2655 f.set(f.get() + 1);
2656 async { Ok::<_, TestErr>(0) }
2657 },
2658 );
2659 assert_eq!(fetches.get(), 1);
2660 batch(|| r.refetch()); assert_eq!(fetches.get(), 2);
2662 }
2663
2664 #[test]
2665 fn resource_latest_wins() {
2666 install_test_spawner();
2667 let src = Signal::new(1i32);
2668 let slots: Rc<RefCell<Vec<Slot<i32>>>> = Rc::new(RefCell::new(Vec::new()));
2669 let sl = slots.clone();
2670 let r = Resource::new(
2671 move || src.get(),
2672 move |_| {
2673 let slot: Slot<i32> = Rc::new(RefCell::new(None));
2674 sl.borrow_mut().push(slot.clone());
2675 manual_future(slot)
2676 },
2677 );
2678 assert!(r.loading());
2679 let before = aborted_count();
2680 batch(|| src.set(2)); assert_eq!(aborted_count(), before + 1, "the stale task was aborted");
2682 *slots.borrow()[0].borrow_mut() = Some(Ok(111));
2684 pump();
2685 assert!(r.loading(), "a stale result writes nothing");
2686 *slots.borrow()[1].borrow_mut() = Some(Ok(222));
2687 pump();
2688 assert_eq!(r.with(|l| l.ready().copied()), Some(222));
2689 }
2690
2691 #[test]
2692 fn resource_scope_disposal_aborts() {
2693 install_test_spawner();
2694 let scope = Scope::child();
2695 let slot: Slot<i32> = Rc::new(RefCell::new(None));
2696 let s2 = slot.clone();
2697 let r = scope.enter(|| Resource::new(move || (), move |()| manual_future(s2.clone())));
2698 assert!(r.loading());
2699 let before = aborted_count();
2700 scope.dispose();
2701 assert_eq!(aborted_count(), before + 1, "disposal aborted the fetch");
2702 *slot.borrow_mut() = Some(Ok(1));
2704 pump();
2705 }
2706
2707 #[test]
2708 fn resource_ready_is_tracked() {
2709 install_test_spawner();
2710 let slot: Slot<i32> = Rc::new(RefCell::new(None));
2711 let s2 = slot.clone();
2712 let r = Resource::new(move || (), move |()| manual_future(s2.clone()));
2713 let runs = Rc::new(Cell::new(0));
2714 let rn = runs.clone();
2715 Effect::new(move || {
2716 let _ = r.ready();
2717 rn.set(rn.get() + 1);
2718 });
2719 assert_eq!(runs.get(), 1);
2720 *slot.borrow_mut() = Some(Ok(1));
2721 pump();
2722 assert!(runs.get() >= 2, "ready() re-ran the effect on completion");
2723 }
2724
2725 #[test]
2726 #[should_panic(expected = "no spawner installed")]
2727 fn spawner_missing_panics() {
2728 let _r = Resource::new(|| (), |()| async { Ok::<_, std::convert::Infallible>(1) });
2730 }
2731}
2732
2733#[cfg(test)]
2734mod unwind_safety_tests {
2735 use super::*;
2736
2737 fn contained(f: impl FnOnce() + std::panic::UnwindSafe) {
2739 let prev = std::panic::take_hook();
2740 std::panic::set_hook(Box::new(|_| {}));
2741 let r = std::panic::catch_unwind(f);
2742 std::panic::set_hook(prev);
2743 assert!(r.is_err(), "expected the closure to panic");
2744 }
2745
2746 #[test]
2750 fn panic_in_scope_enter_restores_current_scope() {
2751 let before = with_rt(|rt| rt.current_scope);
2752 let scope = Scope::detached();
2753 contained(|| scope.enter(|| panic!("boom in enter")));
2754 assert_eq!(with_rt(|rt| rt.current_scope), before, "scope not restored");
2755 let s = Signal::new(7u32);
2757 assert_eq!(s.get(), 7);
2758 }
2759
2760 #[test]
2767 fn panic_in_effect_body_pops_its_observer_frame() {
2768 let depth = with_rt(|rt| rt.observers.len());
2769 let boom = Signal::new(false);
2770 Effect::new(move || {
2771 assert!(!boom.get(), "effect boom");
2772 });
2773 assert_eq!(with_rt(|rt| rt.observers.len()), depth);
2774 contained(|| batch(|| boom.set(true)));
2775 assert_eq!(
2776 with_rt(|rt| rt.observers.len()),
2777 depth,
2778 "observer frame stranded by the panicking effect run"
2779 );
2780 recover_from_panic(); }
2782
2783 #[test]
2784 fn panic_in_untrack_restores_tracking() {
2785 let depth = with_rt(|rt| rt.observers.len());
2786 contained(|| untrack(|| panic!("boom in untrack")));
2787 assert_eq!(with_rt(|rt| rt.observers.len()), depth, "observer stranded");
2788
2789 let src = Signal::new(0i32);
2791 let runs = Rc::new(RefCell::new(0));
2792 let r2 = runs.clone();
2793 Effect::new(move || {
2794 let _ = src.get();
2795 *r2.borrow_mut() += 1;
2796 });
2797 flush_sync();
2798 let before = *runs.borrow();
2799 src.set(1);
2800 flush_sync();
2801 assert!(
2802 *runs.borrow() > before,
2803 "effect did not re-run — tracking is off"
2804 );
2805 }
2806
2807 #[test]
2810 fn panic_in_batch_restores_depth() {
2811 let depth = with_rt(|rt| rt.batch_depth);
2812 contained(|| batch(|| panic!("boom in batch")));
2813 assert_eq!(with_rt(|rt| rt.batch_depth), depth, "batch depth stranded");
2814 }
2815
2816 #[test]
2820 fn panic_in_with_leaves_the_value_intact() {
2821 let s = Signal::new(String::from("intact"));
2822 contained(|| s.with(|_| panic!("boom in with")));
2823 assert_eq!(s.with(std::clone::Clone::clone), "intact");
2824 }
2825
2826 #[test]
2829 fn reentrant_read_inside_with_succeeds() {
2830 let s = Signal::new(5u32);
2831 let doubled = s.with(|outer| *outer + s.with(|inner| *inner));
2832 assert_eq!(doubled, 10);
2833 assert_eq!(
2834 s.with(|v| *v),
2835 5,
2836 "value still in place after the nested read"
2837 );
2838 }
2839
2840 #[test]
2843 fn nested_reads_of_distinct_signals_succeed() {
2844 let a = Signal::new(2u32);
2845 let b = Signal::new(3u32);
2846 assert_eq!(a.with(|x| *x * b.with(|y| *y)), 6);
2847 }
2848
2849 #[test]
2851 fn write_during_read_panics_with_a_clear_message() {
2852 let s = Signal::new(1u32);
2853 let prev = std::panic::take_hook();
2854 std::panic::set_hook(Box::new(|_| {}));
2855 let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2856 s.with(|_| s.set(2));
2857 }));
2858 std::panic::set_hook(prev);
2859 let payload = r.unwrap_err();
2860 let msg = payload
2862 .downcast_ref::<&str>()
2863 .map(std::string::ToString::to_string)
2864 .or_else(|| payload.downcast_ref::<String>().cloned())
2865 .expect("panic payload should be a string");
2866 assert!(
2867 msg.contains("in flight") && msg.contains("Signal"),
2868 "message should name the cause, got: {msg}"
2869 );
2870 }
2871
2872 #[cfg(not(debug_assertions))]
2877 #[test]
2878 fn rerun_cap_defers_instead_of_killing_the_binding() {
2879 let s = Signal::new(0u32);
2880 let runs = std::rc::Rc::new(std::cell::Cell::new(0u32));
2881 let r2 = runs.clone();
2882 Effect::new(move || {
2883 let v = s.get();
2884 r2.set(r2.get() + 1);
2885 if v < 1_000_000 {
2886 s.set(v + 1); }
2888 });
2889 flush_sync();
2890 let after_cycle = runs.get();
2891 assert!(
2892 after_cycle <= RERUN_CAP + 1,
2893 "cap did not bound the drain: {after_cycle} runs"
2894 );
2895
2896 batch(|| s.set(2_000_000)); assert_eq!(
2899 runs.get(),
2900 after_cycle + 1,
2901 "binding stayed dead after hitting the re-run cap"
2902 );
2903 }
2904}
2905
2906#[cfg(test)]
2907mod owner_scope_tests {
2908 use super::*;
2909
2910 #[test]
2911 fn reactions_and_lazy_memos_keep_their_owner_and_restore_the_caller() {
2912 let outer = Scope::child();
2913 outer.provide("outer fixture");
2914 let first = outer.create_child();
2915 let second = outer.create_child();
2916 first.provide("first fixture");
2917 second.provide("second fixture");
2918 let source = Signal::new(0);
2919 let seen = Rc::new(RefCell::new(Vec::new()));
2920 let lazy = first.enter(|| {
2921 Memo::new(move || {
2922 (
2923 source.get(),
2924 Scope::current().use_context::<&str>().unwrap(),
2925 )
2926 })
2927 });
2928 let nested = second.enter(|| {
2929 Memo::new(move || (lazy.get(), Scope::current().use_context::<&str>().unwrap()))
2930 });
2931 second.enter(|| assert_eq!(lazy.get(), (0, "first fixture")));
2932 assert_eq!(nested.get(), ((0, "first fixture"), "second fixture"));
2933 for (scope, name) in [(first, "first fixture"), (second, "second fixture")] {
2934 let seen = seen.clone();
2935 scope.enter(|| {
2936 Effect::new(move || {
2937 seen.borrow_mut()
2938 .push((source.get(), Scope::current().use_context::<&str>()));
2939 assert_eq!(Scope::current().use_context::<&str>(), Some(name));
2940 });
2941 });
2942 }
2943 second.enter(|| {
2944 batch(|| source.set(1));
2945 assert_eq!(
2946 Scope::current().use_context::<&str>(),
2947 Some("second fixture")
2948 );
2949 });
2950 assert_eq!(nested.get(), ((1, "first fixture"), "second fixture"));
2951 assert_eq!(seen.borrow().len(), 4);
2952 outer.dispose();
2953 batch(|| source.set(2));
2954 assert_eq!(seen.borrow().len(), 4, "disposed reactions must not run");
2955 }
2956
2957 #[test]
2958 fn watches_allocate_state_and_cleanup_in_their_owner() {
2959 let owner = Scope::child();
2960 let trigger = Signal::new(0);
2961 let allocated = Rc::new(Cell::new(None::<Signal<i32>>));
2962 let cleaned = Rc::new(Cell::new(0));
2963 owner.enter(|| {
2964 let allocated = allocated.clone();
2965 let cleaned = cleaned.clone();
2966 watch(
2967 move || trigger.get(),
2968 move |value, _| {
2969 allocated.set(Some(Signal::new(*value)));
2970 let cleaned = cleaned.clone();
2971 Scope::current().on_cleanup(move || cleaned.set(cleaned.get() + 1));
2972 },
2973 );
2974 });
2975 batch(|| trigger.set(1));
2976 let state = allocated.get().unwrap();
2977 assert_eq!(state.get(), 1);
2978 owner.dispose();
2979 assert_eq!(cleaned.get(), 1);
2980 assert!(state.try_get().is_none());
2981 }
2982
2983 #[test]
2984 fn panic_in_owned_computations_restores_scope_and_tracking() {
2985 let owner = Scope::child();
2986 owner.provide("owner fixture");
2987 let caller = Scope::child();
2988 caller.provide("caller fixture");
2989 let trigger = Signal::new(false);
2990 let memo = owner.enter(|| {
2991 Memo::new(move || {
2992 assert_eq!(
2993 Scope::current().use_context::<&str>(),
2994 Some("owner fixture")
2995 );
2996 assert!(!trigger.get(), "synthetic memo failure");
2997 7
2998 })
2999 });
3000 assert_eq!(memo.get(), 7);
3001 batch(|| trigger.set(true));
3002 caller.enter(|| {
3003 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| memo.get()));
3004 assert!(result.is_err());
3005 assert_eq!(
3006 Scope::current().use_context::<&str>(),
3007 Some("caller fixture")
3008 );
3009 assert!(with_rt(|rt| rt.observers.is_empty()));
3010 });
3011 owner.dispose();
3012 caller.dispose();
3013 }
3014}