1use std::cell::{Cell, RefCell};
22use std::collections::{HashMap, HashSet};
23use std::rc::Rc;
24
25#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
26pub struct SubscriberId(pub u64);
27
28#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
29pub struct SignalId(pub u64);
30
31#[derive(Default)]
33struct ReactiveState {
34 subscriber_stack: Vec<(SubscriberId, u64)>,
38 dirty: HashSet<SubscriberId>,
40 next_subscriber_id: u64,
42 next_signal_id: u64,
44 subscriber_epoch: HashMap<SubscriberId, u64>,
47 next_subscriber_epoch: u64,
49 subscriber_generation: HashMap<SubscriberId, u64>,
51 next_subscriber_generation: u64,
53 subscriber_scope: HashMap<SubscriberId, u64>,
56 batch_depth: usize,
58 pending_dirty: HashSet<SubscriberId>,
60 memo_registry: HashMap<SubscriberId, Rc<MemoCore>>,
62 effect_registry: HashMap<SubscriberId, Rc<EffectCore>>,
64 pending_effects: Vec<Rc<EffectCore>>,
66}
67
68thread_local! {
69 static REACTIVE: RefCell<ReactiveState> = RefCell::new(ReactiveState::default());
70 static TRACKING_PAUSED: Cell<usize> = const { Cell::new(0) };
72}
73
74pub fn enter_subscriber(sub_id: SubscriberId) {
76 let generation = subscriber_generation(sub_id);
77 enter_subscriber_generation(sub_id, generation);
78}
79
80fn enter_subscriber_generation(sub_id: SubscriberId, generation: u64) {
81 REACTIVE.with(|s| s.borrow_mut().subscriber_stack.push((sub_id, generation)));
82}
83
84pub fn exit_subscriber() {
86 REACTIVE.with(|s| {
87 s.borrow_mut().subscriber_stack.pop();
88 });
89}
90
91struct SubscriberScope;
94
95impl SubscriberScope {
96 fn enter(id: SubscriberId) -> Self {
97 enter_subscriber(id);
98 Self
99 }
100
101 fn enter_generation(id: SubscriberId, generation: u64) -> Self {
103 enter_subscriber_generation(id, generation);
104 Self
105 }
106}
107
108impl Drop for SubscriberScope {
109 fn drop(&mut self) {
110 exit_subscriber();
111 }
112}
113
114pub fn with_subscriber<T>(id: SubscriberId, f: impl FnOnce() -> T) -> T {
119 let _scope = SubscriberScope::enter(id);
120 f()
121}
122
123fn subscriber_epoch(id: SubscriberId) -> u64 {
125 REACTIVE.with(|s| s.borrow().subscriber_epoch.get(&id).copied().unwrap_or(0))
126}
127
128fn subscriber_generation(id: SubscriberId) -> u64 {
130 REACTIVE.with(|s| s.borrow().subscriber_generation.get(&id).copied().unwrap_or(0))
131}
132
133fn bump_subscriber_generation(id: SubscriberId) -> u64 {
135 REACTIVE.with(|s| {
136 let mut s = s.borrow_mut();
137 let next = s.next_subscriber_generation.wrapping_add(1);
138 s.next_subscriber_generation = next;
139 s.subscriber_generation.insert(id, next);
140 next
141 })
142}
143
144fn current_generation() -> u64 {
146 REACTIVE.with(|s| s.borrow().subscriber_stack.last().map(|(_, generation)| *generation).unwrap_or(0))
147}
148
149pub(crate) fn invalidate_subscriber(id: SubscriberId) {
155 REACTIVE.with(|s| {
156 let mut s = s.borrow_mut();
157 let next = s.next_subscriber_epoch.wrapping_add(1);
158 s.next_subscriber_epoch = next;
159 s.subscriber_epoch.insert(id, next);
160 });
161}
162
163pub fn take_dirty() -> HashSet<SubscriberId> {
165 REACTIVE.with(|s| std::mem::take(&mut s.borrow_mut().dirty))
166}
167
168pub(crate) fn register_subscriber_scope(id: SubscriberId, scope: u64) {
170 REACTIVE.with(|s| {
171 s.borrow_mut().subscriber_scope.insert(id, scope);
172 });
173}
174
175pub(crate) fn release_subscriber_scope(id: SubscriberId) {
177 REACTIVE.with(|s| {
178 let mut state = s.borrow_mut();
179 state.subscriber_scope.remove(&id);
180 state.dirty.remove(&id);
183 state.pending_dirty.remove(&id);
184 });
185}
186
187pub(crate) fn take_dirty_for_scope(scope: u64) -> HashSet<SubscriberId> {
193 REACTIVE.with(|s| {
194 let mut state = s.borrow_mut();
195 let dirty = std::mem::take(&mut state.dirty);
196 let mut mine = HashSet::new();
197 let mut keep = HashSet::new();
198 for id in dirty {
199 let owner = state.subscriber_scope.get(&id).copied().unwrap_or(0);
200 if owner == 0 || owner == scope {
201 mine.insert(id);
202 } else {
203 keep.insert(id);
204 }
205 }
206 state.dirty = keep;
207 mine
208 })
209}
210
211pub fn peek_dirty_for_scope(scope: u64) -> HashSet<SubscriberId> {
213 REACTIVE.with(|s| {
214 let state = s.borrow();
215 let mut mine = HashSet::new();
216 for id in state.dirty.iter().copied() {
217 let owner = state.subscriber_scope.get(&id).copied().unwrap_or(0);
218 if owner == 0 || owner == scope {
219 mine.insert(id);
220 }
221 }
222 mine
223 })
224}
225
226thread_local! {
227 static ANY_SIGNAL_SET: Cell<bool> = const { Cell::new(false) };
231 static ANY_SIGNAL_EPOCH: Cell<u64> = const { Cell::new(0) };
234 static SIGNAL_TRACE_ENABLED: Cell<bool> = const { Cell::new(false) };
236}
237
238fn with_signal_trace<R>(f: impl FnOnce(&crate::devtools_trace::DevtoolsTrace<SignalTraceEntry>) -> R) -> R {
241 use std::sync::Mutex;
242 thread_local! {
243 static SIG_TRACE: Mutex<crate::devtools_trace::DevtoolsTrace<SignalTraceEntry>> =
244 Mutex::new(crate::devtools_trace::DevtoolsTrace::new(256));
245 }
246 SIG_TRACE.with(|t| {
247 let guard = t.lock().unwrap_or_else(|e| e.into_inner());
248 f(&guard)
249 })
250}
251
252pub fn take_any_signal_set() -> bool {
254 ANY_SIGNAL_SET.with(|c| c.replace(false))
255}
256
257pub fn any_signal_epoch() -> u64 {
259 ANY_SIGNAL_EPOCH.with(|c| c.get())
260}
261
262fn mark_any_signal_set() {
264 ANY_SIGNAL_SET.with(|c| c.set(true));
265 ANY_SIGNAL_EPOCH.with(|c| c.set(c.get().wrapping_add(1)));
266}
267
268#[derive(Clone, Debug)]
274pub struct SignalTraceEntry {
275 pub signal_id: SignalId,
276 pub subscribers: Vec<SubscriberId>,
278 pub peeked: bool,
280 pub timestamp_ms: u64,
282}
283
284pub fn set_signal_trace_enabled(on: bool) {
286 SIGNAL_TRACE_ENABLED.with(|c| c.set(on));
287 with_signal_trace(|t| t.set_enabled(on));
288}
289
290pub fn signal_trace_enabled() -> bool {
292 SIGNAL_TRACE_ENABLED.with(|c| c.get())
293}
294
295fn push_signal_trace(signal_id: SignalId, subscribers: &[SubscriberId], peeked: bool) {
297 if !signal_trace_enabled() {
298 return;
299 }
300 use crate::devtools_trace::now_ms;
301 with_signal_trace(|t| {
302 if !t.enabled() {
304 return;
305 }
306 t.push(SignalTraceEntry { signal_id, subscribers: subscribers.to_vec(), peeked, timestamp_ms: now_ms() })
307 });
308}
309
310pub fn peek_signal_trace(max: usize) -> Vec<SignalTraceEntry> {
312 if !signal_trace_enabled() {
313 return Vec::new();
314 }
315 with_signal_trace(|t| {
316 if !t.enabled() {
317 return Vec::new();
318 }
319 t.peek(max)
320 })
321}
322
323pub fn clear_signal_trace() {
325 with_signal_trace(|t| t.clear());
326}
327
328pub fn mark_dirty(sub_id: SubscriberId) {
330 REACTIVE.with(|s| {
331 let mut s = s.borrow_mut();
332 if s.batch_depth > 0 {
333 s.pending_dirty.insert(sub_id);
334 } else {
335 s.dirty.insert(sub_id);
336 }
337 });
338}
339
340pub fn new_subscriber_id() -> SubscriberId {
342 REACTIVE.with(|s| {
343 let mut s = s.borrow_mut();
344 let id = SubscriberId(s.next_subscriber_id);
345 s.next_subscriber_id += 1;
346 id
347 })
348}
349
350pub fn new_signal_id() -> SignalId {
352 REACTIVE.with(|s| {
353 let mut s = s.borrow_mut();
354 let id = SignalId(s.next_signal_id);
355 s.next_signal_id += 1;
356 id
357 })
358}
359
360fn current_subscriber() -> Option<SubscriberId> {
362 REACTIVE.with(|s| s.borrow().subscriber_stack.last().map(|(id, _)| *id))
363}
364
365fn tracking_enabled() -> bool {
367 TRACKING_PAUSED.with(|c| c.get() == 0)
368}
369
370pub fn untracked<T>(f: impl FnOnce() -> T) -> T {
372 struct TrackingGuard;
373 impl Drop for TrackingGuard {
374 fn drop(&mut self) {
375 TRACKING_PAUSED.with(|c| c.set(c.get().saturating_sub(1)));
376 }
377 }
378 TRACKING_PAUSED.with(|c| c.set(c.get() + 1));
379 let _guard = TrackingGuard;
380 f()
381}
382
383pub fn batch<T>(f: impl FnOnce() -> T) -> T {
386 struct BatchGuard {
387 completed: bool,
388 }
389 impl Drop for BatchGuard {
390 fn drop(&mut self) {
391 let depth = REACTIVE.with(|s| {
392 let mut s = s.borrow_mut();
393 s.batch_depth = s.batch_depth.saturating_sub(1);
394 s.batch_depth
395 });
396 if depth == 0 {
397 REACTIVE.with(|s| {
398 let mut s = s.borrow_mut();
399 let pending = std::mem::take(&mut s.pending_dirty);
400 s.dirty.extend(pending);
401 if !self.completed {
402 s.pending_effects.clear();
404 }
405 });
406 }
407 }
408 }
409
410 REACTIVE.with(|s| s.borrow_mut().batch_depth += 1);
411 let mut guard = BatchGuard { completed: false };
412 let out = f();
413 guard.completed = true;
414 drop(guard);
415 let effects = REACTIVE.with(|s| std::mem::take(&mut s.borrow_mut().pending_effects));
416 for core in effects {
417 run_effect_core(&core);
418 }
419 out
420}
421
422struct MemoCore {
428 stale: Cell<bool>,
430 computing: Cell<bool>,
432 subscribers: RefCell<HashSet<(SubscriberId, u64, u64)>>,
434}
435
436struct EffectCore {
438 run: Box<dyn Fn()>,
439 running: Cell<bool>,
441 pending: Cell<bool>,
442}
443
444fn notify_subscribers(subs: &[SubscriberId]) {
446 let mut memo_cores = Vec::new();
447 let mut effect_cores = Vec::new();
448 REACTIVE.with(|s| {
449 let mut s = s.borrow_mut();
450 for sub in subs {
451 if s.batch_depth > 0 {
452 s.pending_dirty.insert(*sub);
453 } else {
454 s.dirty.insert(*sub);
455 }
456 if let Some(c) = s.memo_registry.get(sub).cloned() {
457 memo_cores.push(c);
458 }
459 if let Some(c) = s.effect_registry.get(sub).cloned() {
460 effect_cores.push(c);
461 }
462 }
463 });
464 for c in memo_cores {
465 notify_memo_stale(&c);
466 }
467 for c in effect_cores {
468 schedule_effect(c);
469 }
470}
471
472fn notify_memo_stale(core: &Rc<MemoCore>) {
474 if core.stale.get() {
475 return;
476 }
477 core.stale.set(true);
478 core.subscribers
480 .borrow_mut()
481 .retain(|(id, epoch, generation)| *epoch == subscriber_epoch(*id) && *generation == subscriber_generation(*id));
482 let downstream: Vec<SubscriberId> = core.subscribers.borrow().iter().map(|(id, _, _)| *id).collect();
483 for d in downstream {
484 mark_dirty(d);
485 let next = REACTIVE.with(|s| s.borrow().memo_registry.get(&d).cloned());
486 if let Some(c) = next {
487 notify_memo_stale(&c);
488 }
489 }
490}
491
492fn schedule_effect(core: Rc<EffectCore>) {
494 let in_batch = REACTIVE.with(|s| s.borrow().batch_depth > 0);
495 if in_batch {
496 REACTIVE.with(|s| {
497 let mut s = s.borrow_mut();
498 if !s.pending_effects.iter().any(|c| Rc::ptr_eq(c, &core)) {
499 s.pending_effects.push(core);
500 }
501 });
502 } else {
503 run_effect_core(&core);
504 }
505}
506
507fn run_effect_core(core: &Rc<EffectCore>) {
509 if core.running.get() {
510 core.pending.set(true);
511 return;
512 }
513 let id = REACTIVE.with(|s| s.borrow().effect_registry.iter().find(|(_, c)| Rc::ptr_eq(c, core)).map(|(k, _)| *k));
514 let Some(id) = id else { return };
515 struct RunningGuard<'a>(&'a Cell<bool>);
516 impl Drop for RunningGuard<'_> {
517 fn drop(&mut self) {
518 self.0.set(false);
519 }
520 }
521 core.running.set(true);
522 let _running = RunningGuard(&core.running);
523 let generation = bump_subscriber_generation(id);
526 let _scope = SubscriberScope::enter_generation(id, generation);
527 (core.run)();
528 drop(_scope);
529 drop(_running);
530 if core.pending.replace(false) {
531 run_effect_core(core);
532 }
533}
534
535struct SignalInner<T> {
540 value: T,
541 subscribers: HashSet<(SubscriberId, u64, u64)>,
543 peeked: bool,
547}
548
549pub struct Signal<T> {
551 id: SignalId,
552 inner: Rc<RefCell<SignalInner<T>>>,
553}
554
555impl<T: Clone + 'static> Signal<T> {
556 pub fn new(initial: T) -> Self {
557 Self {
558 id: new_signal_id(),
559 inner: Rc::new(RefCell::new(SignalInner { value: initial, subscribers: HashSet::new(), peeked: false })),
560 }
561 }
562
563 pub fn id(&self) -> SignalId {
564 self.id
565 }
566
567 pub fn get(&self) -> T {
569 if tracking_enabled() {
570 if let Some(sub) = current_subscriber() {
571 let epoch = subscriber_epoch(sub);
572 let generation = current_generation();
573 self.inner.borrow_mut().subscribers.insert((sub, epoch, generation));
574 }
575 }
576 self.inner.borrow().value.clone()
577 }
578
579 pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
583 if tracking_enabled() {
584 if let Some(sub) = current_subscriber() {
585 let epoch = subscriber_epoch(sub);
586 let generation = current_generation();
587 self.inner.borrow_mut().subscribers.insert((sub, epoch, generation));
588 }
589 }
590 f(&self.inner.borrow().value)
591 }
592
593 pub fn peek(&self) -> T {
598 let mut inner = self.inner.borrow_mut();
599 inner.peeked = true;
600 inner.value.clone()
601 }
602
603 pub fn peek_with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
605 let mut inner = self.inner.borrow_mut();
606 inner.peeked = true;
607 f(&inner.value)
608 }
609
610 pub fn peek_silent(&self) -> T {
615 self.inner.borrow().value.clone()
616 }
617
618 pub fn peek_silent_with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
620 f(&self.inner.borrow().value)
621 }
622
623 pub fn set(&self, value: T) {
625 let (subs, peeked) = {
626 let mut inner = self.inner.borrow_mut();
627 inner.value = value;
628 inner.subscribers.retain(|(id, epoch, generation)| {
629 *epoch == subscriber_epoch(*id) && *generation == subscriber_generation(*id)
630 });
631 (inner.subscribers.iter().map(|(id, _, _)| *id).collect::<Vec<_>>(), inner.peeked)
632 };
633 if peeked {
634 mark_any_signal_set();
635 }
636 push_signal_trace(self.id, &subs, peeked);
637 notify_subscribers(&subs);
638 }
639
640 pub fn set_if_changed(&self, value: T) -> bool
644 where
645 T: PartialEq,
646 {
647 if self.inner.borrow().value == value {
648 return false;
649 }
650 self.set(value);
651 true
652 }
653
654 pub fn update_if_changed(&self, f: impl FnOnce(&mut T)) -> bool
656 where
657 T: PartialEq,
658 {
659 let mut next = self.inner.borrow().value.clone();
660 f(&mut next);
661 if self.inner.borrow().value == next {
662 return false;
663 }
664 self.set(next);
665 true
666 }
667
668 pub fn update(&self, f: impl FnOnce(&mut T)) {
670 let (subs, peeked) = {
671 let mut inner = self.inner.borrow_mut();
672 f(&mut inner.value);
673 inner.subscribers.retain(|(id, epoch, generation)| {
674 *epoch == subscriber_epoch(*id) && *generation == subscriber_generation(*id)
675 });
676 (inner.subscribers.iter().map(|(id, _, _)| *id).collect::<Vec<_>>(), inner.peeked)
677 };
678 if peeked {
679 mark_any_signal_set();
680 }
681 push_signal_trace(self.id, &subs, peeked);
682 notify_subscribers(&subs);
683 }
684
685 pub fn subscriber_count(&self) -> usize {
687 self.inner.borrow().subscribers.len()
688 }
689}
690
691impl<T: 'static> Clone for Signal<T> {
692 fn clone(&self) -> Self {
693 Self { id: self.id, inner: self.inner.clone() }
694 }
695}
696
697impl<T: 'static> std::fmt::Debug for Signal<T> {
698 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
699 f.debug_struct("Signal").field("id", &self.id).field("value_type", &std::any::type_name::<T>()).finish()
700 }
701}
702
703pub struct Memo<T> {
709 id: SubscriberId,
710 core: Rc<MemoCore>,
711 inner: Rc<RefCell<MemoInner<T>>>,
712 _registration: Rc<MemoRegistration>,
714}
715
716struct MemoInner<T> {
717 compute: Box<dyn Fn() -> T>,
718 cached: Option<T>,
719}
720
721struct MemoRegistration {
726 id: SubscriberId,
727}
728
729impl Drop for MemoRegistration {
730 fn drop(&mut self) {
731 REACTIVE.with(|s| {
732 s.borrow_mut().memo_registry.remove(&self.id);
733 });
734 }
735}
736
737impl<T: Clone + 'static> Memo<T> {
738 pub fn new(compute: impl Fn() -> T + 'static) -> Self {
739 let id = new_subscriber_id();
740 let memo = Self {
741 id,
742 core: Rc::new(MemoCore {
743 stale: Cell::new(false),
744 computing: Cell::new(false),
745 subscribers: RefCell::new(HashSet::new()),
746 }),
747 inner: Rc::new(RefCell::new(MemoInner { compute: Box::new(compute), cached: None })),
748 _registration: Rc::new(MemoRegistration { id }),
749 };
750 REACTIVE.with(|s| {
751 s.borrow_mut().memo_registry.insert(id, memo.core.clone());
752 });
753 memo.recompute();
754 memo
755 }
756
757 fn recompute(&self) {
758 if self.core.computing.get() {
759 panic!("Memo: circular dependency detected");
760 }
761 struct ComputeGuard<'a> {
762 core: &'a MemoCore,
763 completed: bool,
764 }
765 impl Drop for ComputeGuard<'_> {
766 fn drop(&mut self) {
767 self.core.computing.set(false);
768 if !self.completed {
769 self.core.stale.set(true);
772 }
773 }
774 }
775
776 self.core.computing.set(true);
777 self.core.stale.set(false);
778 let mut guard = ComputeGuard { core: &self.core, completed: false };
779 let generation = bump_subscriber_generation(self.id);
782 let value = {
783 let _scope = SubscriberScope::enter_generation(self.id, generation);
784 (self.inner.borrow().compute)()
785 };
786 self.inner.borrow_mut().cached = Some(value);
787 guard.completed = true;
788 }
789
790 pub fn get(&self) -> T {
791 if tracking_enabled() {
792 if let Some(sub) = current_subscriber() {
793 if sub != self.id {
794 let epoch = subscriber_epoch(sub);
795 let generation = current_generation();
796 self.core.subscribers.borrow_mut().insert((sub, epoch, generation));
797 }
798 }
799 }
800 if self.core.stale.replace(false) || self.inner.borrow().cached.is_none() {
801 self.recompute();
802 }
803 self.inner.borrow().cached.clone().expect("Memo: cached after recompute")
804 }
805
806 pub fn peek(&self) -> Option<T> {
807 self.inner.borrow().cached.clone()
808 }
809}
810
811impl<T: 'static> Clone for Memo<T> {
812 fn clone(&self) -> Self {
813 Self {
814 id: self.id,
815 core: self.core.clone(),
816 inner: self.inner.clone(),
817 _registration: self._registration.clone(),
818 }
819 }
820}
821
822impl<T: 'static> std::fmt::Debug for Memo<T> {
823 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
824 f.debug_struct("Memo").field("id", &self.id).field("value_type", &std::any::type_name::<T>()).finish()
825 }
826}
827
828pub struct Effect {
834 id: SubscriberId,
835 core: Rc<EffectCore>,
836}
837
838impl Effect {
839 pub fn new(run: impl Fn() + 'static) -> Self {
840 let id = new_subscriber_id();
841 let effect = Self {
842 id,
843 core: Rc::new(EffectCore { run: Box::new(run), running: Cell::new(false), pending: Cell::new(false) }),
844 };
845 REACTIVE.with(|s| {
846 s.borrow_mut().effect_registry.insert(id, effect.core.clone());
847 });
848 run_effect_core(&effect.core);
850 effect
851 }
852
853 pub fn rerun(&self) {
854 run_effect_core(&self.core);
855 }
856}
857
858impl Drop for Effect {
859 fn drop(&mut self) {
860 REACTIVE.with(|s| {
861 s.borrow_mut().effect_registry.remove(&self.id);
862 });
863 }
864}
865
866impl std::fmt::Debug for Effect {
867 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
868 f.debug_struct("Effect").field("id", &self.id).finish()
869 }
870}
871
872#[cfg(test)]
873mod tests {
874 use super::*;
875 use std::panic::{self, AssertUnwindSafe};
876
877 fn quietly<R>(f: impl FnOnce() -> R) -> std::thread::Result<R> {
879 let prev = panic::take_hook();
880 panic::set_hook(Box::new(|_| {}));
881 let out = panic::catch_unwind(AssertUnwindSafe(f));
882 panic::set_hook(prev);
883 out
884 }
885
886 #[test]
887 fn signal_trace_records_only_while_enabled() {
888 clear_signal_trace();
889 set_signal_trace_enabled(false);
890 assert!(!signal_trace_enabled());
891
892 let sig = Signal::new(0);
893 let _ = sig.peek();
894 sig.set(1);
895 assert!(peek_signal_trace(0).is_empty(), "关闭时快照也应为空");
896
897 set_signal_trace_enabled(true);
898 sig.set(2);
899 let snap = peek_signal_trace(0);
900 assert_eq!(snap.len(), 1);
901 assert_eq!(snap[0].signal_id, sig.id);
902 assert!(snap[0].peeked, "peek 读过的 Signal 必须带宿主级标记");
903
904 clear_signal_trace();
905 set_signal_trace_enabled(false);
906 }
907
908 #[test]
909 fn signal_trace_clear_works_while_disabled() {
910 clear_signal_trace();
911 set_signal_trace_enabled(true);
912 let sig = Signal::new(0);
913 sig.set(1);
914 assert_eq!(peek_signal_trace(0).len(), 1);
915
916 set_signal_trace_enabled(false);
917 clear_signal_trace();
918 set_signal_trace_enabled(true);
919 assert!(peek_signal_trace(0).is_empty(), "关闭期间的显式 clear 必须生效");
920 set_signal_trace_enabled(false);
921 }
922
923 #[test]
924 fn dropping_memo_clone_keeps_shared_registration() {
925 let sig = Signal::new(1);
926 let s = sig.clone();
927 let memo = Memo::new(move || s.get() * 2);
928 assert_eq!(memo.get(), 2);
929
930 let clone = memo.clone();
931 drop(clone);
932
933 sig.set(7);
934 assert_eq!(memo.get(), 14, "clone 析构不应注销原 Memo 的依赖注册");
935 }
936
937 #[test]
938 fn memo_panic_keeps_stale_and_recomputes() {
939 let sig = Signal::new(1);
940 let fail = Rc::new(Cell::new(false));
941 let (s, f) = (sig.clone(), fail.clone());
942 let memo = Memo::new(move || {
943 let v = s.get();
944 if f.get() {
945 panic!("memo boom");
946 }
947 v * 2
948 });
949 assert_eq!(memo.get(), 2);
950
951 fail.set(true);
952 sig.set(5);
953 assert!(quietly(|| memo.get()).is_err());
954
955 fail.set(false);
956 assert_eq!(memo.get(), 10, "panic 后必须保留 stale 并重新计算");
957 }
958
959 #[test]
960 fn effect_panic_resets_running_guard() {
961 let sig = Signal::new(0);
962 let fail = Rc::new(Cell::new(false));
963 let runs = Rc::new(Cell::new(0usize));
964 let (s, f, r) = (sig.clone(), fail.clone(), runs.clone());
965 let effect = Effect::new(move || {
966 let _ = s.get();
967 r.set(r.get() + 1);
968 if f.get() {
969 panic!("effect boom");
970 }
971 });
972 assert_eq!(runs.get(), 1);
973
974 fail.set(true);
975 assert!(quietly(|| sig.set(1)).is_err());
976 fail.set(false);
977
978 sig.set(2);
979 assert_eq!(runs.get(), 3, "panic 后 effect 应能继续响应依赖变化");
980 drop(effect);
981 }
982
983 #[test]
984 fn batch_panic_restores_depth() {
985 let sig = Signal::new(0);
986 assert!(quietly(|| batch(|| {
987 sig.set(1);
988 panic!("batch boom");
989 }))
990 .is_err());
991
992 let runs = Rc::new(Cell::new(0usize));
993 let (s, r) = (sig.clone(), runs.clone());
994 let effect = Effect::new(move || {
995 let _ = s.get();
996 r.set(r.get() + 1);
997 });
998 assert_eq!(runs.get(), 1);
999
1000 sig.set(2);
1001 assert_eq!(runs.get(), 2, "batch panic 后 depth 必须归零,set 应立即通知");
1002 drop(effect);
1003 }
1004
1005 #[test]
1006 fn untracked_panic_restores_tracking() {
1007 let sig = Signal::new(0);
1008 assert!(quietly(|| untracked(|| {
1009 let _ = sig.get();
1010 panic!("untracked boom");
1011 }))
1012 .is_err());
1013
1014 let runs = Rc::new(Cell::new(0usize));
1015 let (s, r) = (sig.clone(), runs.clone());
1016 let effect = Effect::new(move || {
1017 let _ = s.get();
1018 r.set(r.get() + 1);
1019 });
1020 sig.set(1);
1021 assert_eq!(runs.get(), 2, "untracked panic 后必须恢复依赖追踪");
1022 drop(effect);
1023 }
1024
1025 #[test]
1026 fn only_peeked_signals_mark_global_rebuild() {
1027 let _ = take_any_signal_set();
1028 let scoped = Signal::new(0);
1029 let id = new_subscriber_id();
1030 with_subscriber(id, || {
1031 let _ = scoped.get();
1032 });
1033 scoped.set(1);
1034 assert!(!take_any_signal_set(), "仅 build 内 get 的 Signal 不应触发全树 rebuild");
1035
1036 let peeked = Signal::new(0);
1037 let _ = peeked.peek();
1038 peeked.set(1);
1039 assert!(take_any_signal_set(), "peek 过的 Signal 变化应触发全树 rebuild");
1040 }
1041
1042 #[test]
1043 fn invalidated_subscriber_is_pruned_on_next_set() {
1044 let sig = Signal::new(0);
1045 let id = new_subscriber_id();
1046 with_subscriber(id, || {
1047 let _ = sig.get();
1048 });
1049 assert_eq!(sig.subscriber_count(), 1);
1050 invalidate_subscriber(id);
1051 sig.set(1);
1052 assert_eq!(sig.subscriber_count(), 0, "失效订阅应在下一次 set 时被剔除");
1053 }
1054
1055 #[test]
1056 fn effect_rerun_drops_stale_dependencies() {
1057 let sig = Signal::new(0);
1058 let gate = Signal::new(true);
1059 let runs = Rc::new(Cell::new(0usize));
1060 let (s, g, r) = (sig.clone(), gate.clone(), runs.clone());
1061 let effect = Effect::new(move || {
1062 r.set(r.get() + 1);
1063 if g.get() {
1064 let _ = s.get();
1065 }
1066 });
1067 assert_eq!(runs.get(), 1);
1068
1069 gate.set(false);
1070 assert_eq!(runs.get(), 2, "gate 变化应重跑");
1071 sig.set(1);
1072 assert_eq!(runs.get(), 2, "gate=false 后旧 Signal 依赖必须被剔除");
1073 drop(effect);
1074 }
1075
1076 #[test]
1077 fn memo_recompute_drops_stale_dependencies() {
1078 let sig = Signal::new(0);
1079 let gate = Signal::new(true);
1080 let computes = Rc::new(Cell::new(0usize));
1081 let (s, g, c) = (sig.clone(), gate.clone(), computes.clone());
1082 let memo = Memo::new(move || {
1083 c.set(c.get() + 1);
1084 if g.get() {
1085 s.get()
1086 } else {
1087 0
1088 }
1089 });
1090 assert_eq!(memo.get(), 0);
1091 assert_eq!(computes.get(), 1);
1092
1093 gate.set(false);
1094 assert_eq!(memo.get(), 0);
1095 assert_eq!(computes.get(), 2, "gate 变化后应重算");
1096
1097 sig.set(1);
1098 assert_eq!(memo.get(), 0);
1099 assert_eq!(computes.get(), 2, "gate=false 后旧 Signal 依赖必须被剔除");
1100 }
1101}