Skip to main content

day_reactive/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day-reactive: the reactive core (DESIGN.md §3.3, §4).
5//!
6//! Build-once / bind-forever: signals, memos, effects, `bind`, and `watch` over a thread-local
7//! generational arena. All handles are `Copy` and `!Send`; the only cross-thread door is
8//! [`Setter`]. Writes batch; the drain runs to fixpoint in (priority, scope-depth, creation-seq)
9//! order; layout/turn-end callbacks run once after the fixpoint (§3.3's turn state machine).
10//!
11//! `Signal` is `!Send`:
12//! ```compile_fail
13//! fn assert_send<T: Send>(_: T) {}
14//! let s = day_reactive::Signal::new(1);
15//! assert_send(s); // must not compile
16//! ```
17
18// ---------------------------------------------------------------------------------------------
19// `tls_group!`: one pthread key for a module's whole set of thread-locals.
20//
21// On Android, Rust's `thread_local!` has no native-TLS path (`rustc --print cfg
22// --target aarch64-linux-android` emits no `target_thread_local`), so every `thread_local!`
23// static takes one of bionic's 128 `pthread_key_create` slots, allocated on first touch and
24// never released. day plus its dependencies declares far more than that, so a long-running app
25// exhausts the table as more of its code runs first, and the next library to ask for a key
26// fails. Android's WebView is the usual casualty: its browser startup takes several keys, gets
27// none, and traps with no message at all.
28//
29// This macro takes `thread_local!`'s syntax and gives back the same names with the same `.with`,
30// but backs all of them with one key: the slots become fields of a single per-module struct and
31// each name becomes a zero-sized handle that borrows its field. Call sites do not change.
32// Cell/RefCell conveniences (`set`/`get`/`replace`) are absent: go through `.with`, which is
33// what the field itself offers.
34#[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// ---------------------------------------------------------------------------------------------
67// `tls_root!` / `tls_slots!`: one pthread key for a whole crate.
68//
69// `tls_group!` above already collapses a module's statics to one key. These two go the last step:
70// each module declares its slots as a plain struct (`tls_slots!`) and the crate root gathers them
71// into a single thread-local (`tls_root!`). A crate then costs one key no matter how many modules
72// keep state, and the root is also the natural place to hang teardown.
73//
74// Call sites are unchanged: the names still answer `.with`. The cost is one line per module
75// naming its field in the root, and `tls_root!` listing the modules. `crate::tls_root` resolves
76// in the expanding crate, so each crate keeps its own root.
77#[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        /// Borrow the crate's single thread-local root. Reentrant: the root itself holds no
87        /// lock, so a slot's closure may reach another slot.
88        #[inline]
89        pub(crate) fn tls_root<R>(f: impl ::core::ops::FnOnce(&TlsRoot) -> R) -> R {
90            TLS_ROOT.with(f)
91        }
92        /// Best-effort access for destructor paths after the crate's TLS has gone away.
93        #[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/// One module's slots, stored as `$field` of the crate's [`tls_root!`].
104// `crate::tls_root` is correct here, and `$crate` would be wrong: the root belongs to the crate
105// expanding this macro, not to day-reactive. That resolution is what gives each crate a root of
106// its own, so the lint is describing the intent rather than a mistake.
107#[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// ---------------------------------------------------------------------------
158// Runtime
159// ---------------------------------------------------------------------------
160
161#[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    /// Effects, binds, watches: anything with a re-runnable reaction closure.
173    Reaction,
174}
175
176/// Type-erased memo comparator (a monomorphized `PartialEq::eq`).
177type MemoEq = fn(&dyn Any, &dyn Any) -> bool;
178
179/// A node's stored value, shared so a reader can hold it while the runtime borrow is released.
180///
181/// `with`/`try_with` must run the caller's closure without holding the thread-local runtime
182/// borrow (the closure routinely reads other signals, which re-enters `with_rt`). This used to be
183/// done by taking the value out of the node and putting it back afterwards, which had two costs: a
184/// re-entrant read of the same signal found the hole and reported "disposed", and a panic inside
185/// the closure lost the value permanently. Sharing the cell instead lets a reader clone it out
186/// cheaply, so concurrent reads work and the value is never in limbo.
187type NodeValue = Rc<RefCell<Box<dyn Any>>>;
188
189struct Node {
190    kind: NodeKind,
191    state: NodeState,
192    value: Option<NodeValue>,
193    /// Memo recompute (returns boxed new value), compared with `eq`.
194    memo_compute: Option<Rc<dyn Fn() -> Box<dyn Any>>>,
195    memo_eq: Option<MemoEq>,
196    /// Reaction closure (effect/bind/watch body).
197    reaction: Option<Rc<dyn Fn()>>,
198    sources: Vec<NodeKey>,
199    /// Callbacks an external dependency registry (day-model's trigger claims) hangs on this
200    /// computation's current run, drained when the run's sources clear (re-track or disposal),
201    /// mirroring the per-run lifetime of `sources` itself. Run outside the runtime borrow.
202    run_cleanups: Vec<Box<dyn FnOnce()>>,
203    observers: Vec<NodeKey>,
204    // Computations restore this owner when they run, including lazy memo reads.
205    scope: ScopeKey,
206    /// Ordering: (priority, scope depth, creation seq). Priority 0 = structural binding.
207    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    /// Observer stack; `None` = untracked frame.
231    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    /// The async-spawn door ([`install_spawner`]): runs a boxed future on the app's main-loop
240    /// executor, returning an abort closure.
241    spawner: Option<Spawner>,
242    turn_end: Vec<Rc<dyn Fn()>>,
243    /// One-shot callbacks for the end of the current turn ([`at_turn_end`]).
244    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
285/// Per-drain re-run cap (§4.2): panic in debug, warn-and-defer in release.
286const RERUN_CAP: u32 = 100;
287
288/// Per-turn cap on drain→turn-end rounds ([`flush_sync`]): same panic/warn split as
289/// [`RERUN_CAP`]. Two rounds settle the normal case (a turn-end hook scheduling reactive
290/// work, such as day-persistence's deferred requeries); reaching the cap means hooks are feeding
291/// each other every round.
292const 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// ---------------------------------------------------------------------------
299// Graph internals
300// ---------------------------------------------------------------------------
301
302#[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
332/// Register a tracked read: current observer gains `source` as a dependency.
333fn 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/// Unsubscribe `key` from its sources and hand back its run cleanups. The caller must run the
347/// returned closures after releasing the runtime borrow: they call into consumers (day-model
348/// claim release disposes trigger scopes) that re-enter the runtime.
349#[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
362/// Mark downstream after a source changed. Direct observers get `Dirty`; transitive
363/// (through memos) get `Check`. Reactions are enqueued.
364fn mark_observers(rt: &mut Runtime, source: NodeKey, level: NodeState) {
365    // Small explicit stack to avoid recursion borrow issues.
366    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; // already at least this dirty
377        }
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
396/// Enter a computation's owner and tracking frame together. A memo can be pulled by a
397/// different window's reaction, and a queued effect can run after its caller has left scope.
398/// Neither should inherit that caller's context or allocate state into its scope.
399fn 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
417/// Pull-refresh a memo: recompute if (transitively) dirty; bump `last_changed` only on real change.
418fn 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        // Refresh sources; only recompute if one actually changed since our last run.
427        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    // Recompute.
446    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                // A reader may be holding this cell; compare against it without disturbing them.
463                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            // Install a new cell rather than writing through the old one: a read in flight keeps
472            // reading the value it borrowed, for the duration of its closure, instead of panicking.
473            node.value = Some(Rc::new(RefCell::new(new_value)));
474            node.last_changed = tick;
475            rt.tick += 1;
476        }
477        // Downstream was already marked Check when we were invalidated; observers that pull us
478        // will see last_changed. Nothing further to do here.
479    });
480}
481
482/// Run one reaction if it is actually stale.
483fn 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    // Released claims must drop before the fresh run tracks, and outside the borrow.
524    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
537/// Drain the pending queue to fixpoint, then run turn-end callbacks (§3.3 steps 2–3),
538/// repeating both until the turn is quiescent. A turn-end callback may schedule new
539/// reactive work (day-persistence's autosave flush re-derives live queries and diffs the
540/// answers into signals); that work belongs to this turn: §3.3 step 2's "writes made
541/// during the drain extend the current drain", extended across the turn-end boundary.
542/// Left pending instead, every cross-row readout (a query-fed list, a derived bound)
543/// would render one turn stale. Round two drains the deltas and re-runs the hooks, and
544/// autosave then finds nothing dirty, so a settled app exits after two rounds;
545/// The turn-round cap stops turn-end hooks that feed each other forever.
546///
547/// # Panics
548///
549/// In debug builds, panics when one effect re-runs past the per-drain cap (a reactive cycle)
550/// or when turn-end callbacks keep scheduling work past the round cap. Release builds log a
551/// warning and recover.
552pub 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; // re-entrant flush folds into the current drain
562    }
563    let mut round = 0u32;
564    loop {
565        round += 1;
566        // Fresh per round: the re-run cap is per drain (§4.2), and each round is one drain.
567        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            // (priority, scope-depth, creation-seq): owners before descendants.
574            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                    // Break the cycle but leave the node runnable. This key was drained out of
598                    // `pending` above with `queued` still true; without the reset here,
599                    // `mark_observers` would never enqueue it again and the binding would be
600                    // silently dead for the rest of the process. Clean + unqueued means the next
601                    // source write re-marks and re-enqueues it with a fresh per-drain budget.
602                    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        // One-shot work first: it settles what this turn changed (a toolbar composed once from
619        // everything the turn contributed), which the standing hooks (layout) then see.
620        for cb in once {
621            cb();
622        }
623        for cb in turn_end {
624            cb();
625        }
626        // Quiescent, or a nested flush inside a callback already settled everything.
627        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            // The callbacks' first write posted a scheduled drain (draining was false
639            // then), so the deferred work still runs next turn, the same recovery shape as
640            // the re-run cap.
641            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
654/// Reset the runtime to a clean idle state after a panic unwound through a drain or batch,
655/// e.g. a reactive-cycle assertion (the rerun cap) that tripped inside a native event callback
656/// which the backend *contained* (rather than letting it abort the process across the C ABI; a
657/// GTK/Qt signal trampoline can't unwind). The in-flight `pending` work and the observer stack
658/// are dropped (the next interaction re-derives them); persistent registrations (effects, memos,
659/// turn-end hooks) are kept.
660pub 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        // The scope stack is unwound by `Scope::enter`'s guard, but a panic raised between
669        // scopes (or from a callsite that set `current_scope` directly) can still leave it on a
670        // disposed scope, where every later `Signal::new` would be born dead. Re-root it.
671        rt.current_scope = rt.root_scope;
672    });
673}
674
675/// After a write: schedule work. Inside a batch or drain, the fixpoint picks it up; outside,
676/// post a coalesced drain through the installed scheduler (§3.3 step 3).
677fn 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        // A write to a signal from inside its own `with`/`try_with` closure. Before the value
693        // was shared this silently did nothing (the read's restore clobbered the write), so
694        // say it plainly instead of losing the update.
695        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
718// ---------------------------------------------------------------------------
719// Public: batching / scheduling / turn end
720// ---------------------------------------------------------------------------
721
722/// Run `f` in a batch: writes coalesce; the synchronous fixpoint drain runs at batch close.
723/// Restores a piece of runtime state when it goes out of scope, on the normal path and on an
724/// unwind. day-core contains panics at its trampoline boundaries (`pump_events`, posted tasks,
725/// lifecycle) so a panicking app callback degrades the UI instead of aborting the process; that
726/// guarantee is only worth anything if the reactive runtime is still coherent afterwards.
727/// Restoring after `f()` returns is not enough, because that line is skipped on unwind.
728fn 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        // Runs on unwind too, so a contained panic can't strand `batch_depth` above zero, which
736        // would stop every later write from scheduling a drain (a silently frozen UI). Saturating:
737        // if `recover_from_panic` already zeroed the depth mid-unwind, a plain `-= 1` here would
738        // underflow: a panic inside this Drop, which is a process abort.
739        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
753/// Force a synchronous fixpoint drain **now**, even inside an open [`batch`]. Event dispatch wraps
754/// handlers in a batch (day-core), so a handler that needs its writes to drain immediately
755/// (namely `with_animation`, whose ambient animation must be live *while* the resulting patches
756/// apply) cannot rely on the batch's close (that runs later, after the scope ends). This
757/// temporarily drops the batch depth so [`flush_sync`] runs, then restores it. No-op if a drain
758/// is already in progress (the writes fold into it); harmless if nothing is pending.
759pub fn flush_now() {
760    let saved = with_rt(|rt| std::mem::replace(&mut rt.batch_depth, 0));
761    // Restored on unwind too: the debug rerun-cap panic can cross here under an event-dispatch
762    // batch, and skipping the restore would hand the enclosing batch guard a zero depth.
763    let _g = rt_guard(move |rt: &mut Runtime| rt.batch_depth = saved);
764    flush_sync();
765}
766
767/// Run `f` without tracking reads.
768pub fn untrack<R>(f: impl FnOnce() -> R) -> R {
769    with_rt(|rt| rt.observers.push(None));
770    // Popped on unwind too: a stranded `None` observer would silently disable dependency
771    // tracking for every read that followed, so nothing would ever update again.
772    let _g = rt_guard(|rt: &mut Runtime| {
773        rt.observers.pop();
774    });
775    f()
776}
777
778/// The identity of one reactive computation (a reaction or a memo) across its lifetime.
779/// Opaque; `Copy + Eq + Hash`, so an external dependency registry can key per-computation
780/// bookkeeping on it. Slotmap-generational underneath: a recycled slot is a new `RunId`.
781#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
782pub struct RunId(NodeKey);
783
784/// The computation currently tracking reads: `None` at top level and under [`untrack`].
785pub fn active_run() -> Option<RunId> {
786    with_rt(|rt| rt.observers.last().copied().flatten()).map(RunId)
787}
788
789/// Hang `f` on the active computation's current run: it fires when that computation next
790/// re-tracks (a re-run clears its sources first) or is disposed. This is the hook that lets an
791/// external dependency registry (day-model's trigger claims) mirror this graph's per-run
792/// source bookkeeping. Returns `false`, registering nothing, when no computation is tracking.
793pub 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
808/// Install "post a drain on the main loop". Backends call this once at startup.
809pub fn install_scheduler(post: impl Fn() + 'static) {
810    with_rt(|rt| rt.scheduler = Some(Rc::new(post)));
811}
812
813/// A boxed, `!Send` future for the [`install_spawner`] executor door.
814pub type LocalBoxFuture = Pin<Box<dyn Future<Output = ()> + 'static>>;
815
816/// The installed spawner: runs a future on the main-loop executor, returns its abort closure.
817type Spawner = Rc<dyn Fn(LocalBoxFuture) -> Box<dyn FnOnce()>>;
818
819/// Install the async-spawn door: `spawn` runs a future on the app's main-loop executor and
820/// returns an abort closure (remove + drop the future). The abort must be a no-op once the
821/// task has completed: [`Resource`] stores it after an eager first poll, so a synchronously
822/// ready future has already finished by then. day-core's `launch_with` wires this to
823/// `day::task` / `TaskHandle::abort`; call it once at startup (docs/async.md).
824pub fn install_spawner(spawn: impl Fn(LocalBoxFuture) -> Box<dyn FnOnce()> + 'static) {
825    with_rt(|rt| rt.spawner = Some(Rc::new(spawn)));
826}
827
828/// Spawn through the installed door ([`install_spawner`]); the [`on_main`] panic model.
829fn 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
837/// Register a callback run once after every fixpoint drain (day-core's layout turn).
838pub fn on_turn_end(cb: impl Fn() + 'static) {
839    with_rt(|rt| rt.turn_end.push(Rc::new(cb)));
840}
841
842/// Run `cb` once, when the current turn settles: after the drain inside a drain or a batch
843/// (even a batch that leaves no reactive work behind), or right away when no turn is open.
844///
845/// This is how a consumer coalesces a burst of changes into one pass. Swapping a page
846/// withdraws the old page's toolbar items and contributes the new page's within one turn, and
847/// only the settled result is worth handing to the toolkit.
848pub 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
862// ---------------------------------------------------------------------------
863// Cross-thread: the main poster + Setter
864// ---------------------------------------------------------------------------
865
866type MainPoster = Box<dyn Fn(Box<dyn FnOnce() + Send>) + Send + Sync>;
867static MAIN_POSTER: std::sync::OnceLock<MainPoster> = std::sync::OnceLock::new();
868
869/// Install the cross-thread → main-thread door. Backends call this once at startup.
870pub fn install_main_poster(post: impl Fn(Box<dyn FnOnce() + Send>) + Send + Sync + 'static) {
871    let _ = MAIN_POSTER.set(Box::new(post));
872}
873
874/// Whether a backend has installed the main poster yet, i.e. whether [`on_main`] would work
875/// rather than panic. Platform glue that can be called before launch (a notification tap that
876/// cold-starts the process) probes this and buffers instead of posting. The poster is set once
877/// and never cleared, so a `false` can only become `true`: a caller that buffers on a false
878/// negative is still correct, provided something drains the buffer at launch.
879pub fn has_main_poster() -> bool {
880    MAIN_POSTER.get().is_some()
881}
882
883/// Schedule `f` on the UI thread (usable from any thread once a backend installed the poster).
884///
885/// # Panics
886///
887/// Panics when no backend has installed the main poster yet (see [`has_main_poster`]).
888pub 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
898/// Install the timer door (`Platform::post_delayed`). Backends call this once at startup.
899pub 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
905/// Schedule `f` on the UI thread after (at least) `ms` milliseconds, the rail behind
906/// `day::sleep` (docs/async.md).
907///
908/// # Panics
909///
910/// Panics when no backend has installed the delayed poster yet.
911pub 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    // The browser has no monotonic clock in `std`, and `setTimeout` already fires in deadline
918    // order, so the closure goes to the timer as it is.
919    #[cfg(target_arch = "wasm32")]
920    post(ms, Box::new(f));
921}
922
923/// Deadline order for [`on_main_delayed`], whatever the native timer does when it runs late.
924///
925/// A native timer promises "not before", and several toolkits dispatch timers that are overdue
926/// together in the order they were armed, not the order they were due: after a stalled main loop,
927/// `GLib` runs a 200 ms timeout armed first before a 100 ms one armed after it. Sleeps would then
928/// resolve out of order exactly when the app is busiest.
929///
930/// So the closures wait here, and each native timer runs every closure due by the time it
931/// fires, earliest first. A closure is run by its own timer at the latest, and by an
932/// earlier-armed, later-due timer when that one happens to be dispatched first.
933///
934/// A timer runs ahead of time only closures armed on the thread it fires on. That is every
935/// sleep of an app, whose timers are armed and fired on the UI thread. It keeps a closure armed
936/// elsewhere for its own timer, and it keeps the threads of a test binary, each a UI thread of
937/// its own over the mock toolkit, from running one another's sleeps.
938#[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        /// Arming order, so two closures due at the same instant run first-armed first.
949        seq: u64,
950        /// The thread that armed it.
951        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    /// Queue `job` to be due `ms` from now; the returned closure is what the native timer runs.
966    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    /// Run the closure armed as `own_seq` and every closure of this thread due by now (and in
984    /// any case by `own`), earliest first: a timer that fires a hair early by this clock still
985    /// runs the closure it was armed for.
986    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            // The lock is released before the closure runs: it may arm another timer.
991            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        /// Timers dispatched late and in arming order still run their closures in deadline
1013        /// order: the case a stalled `GLib` main loop produces.
1014        #[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            // Everything is overdue by the time the loop gets round to it.
1023            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        /// A timer runs its own closure even when nothing else is due, and leaves later ones.
1031        #[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            // Fired a minute early by this clock: it still runs the closure it was armed for.
1043            later();
1044            assert_eq!(*ran.lock().unwrap(), ["soon", "later"]);
1045        }
1046
1047        /// A timer firing on one thread leaves the closures armed on another for their own
1048        /// timers, however overdue they are.
1049        #[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            // Its own timer runs it, on whatever thread that fires.
1067            theirs();
1068            assert_eq!(*ran.lock().unwrap(), ["mine", "theirs"]);
1069        }
1070    }
1071}
1072
1073// ---------------------------------------------------------------------------
1074// Scope
1075// ---------------------------------------------------------------------------
1076
1077/// Ownership scope for signals/effects (§4.3). `Copy` handle; not `Send`.
1078#[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    /// Create a child of the current scope.
1100    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    /// A scope owned by nobody; dispose it manually.
1128    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    /// Run `f` with `self` as the current scope.
1146    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        // Restored on unwind too. Otherwise a contained panic leaves the runtime parented to
1149        // this (usually transient, soon-disposed) scope, so every later `Signal::new` is created
1150        // dead and its first read panics with a misleading "read of disposed Signal".
1151        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    /// Dispose this scope: children first, then own nodes (unsubscribed + dropped) and cleanups.
1169    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                // Detach us from downstream observers too.
1198                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                // Pending entries for removed nodes are skipped at pop (generational key check).
1210            }
1211        });
1212        // A dying computation's per-run claims drop like a re-track would drop them: outside
1213        // the borrow, before the scope's own cleanups (which may release scope-level claims).
1214        for f in run_cleanups {
1215            f();
1216        }
1217        for c in cleanups {
1218            c();
1219        }
1220    }
1221
1222    /// Provide a context value visible to this scope and its descendants.
1223    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    /// Look up a context value here or in any ancestor (requires `T: Clone`).
1232    #[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
1247// ---------------------------------------------------------------------------
1248// Signal
1249// ---------------------------------------------------------------------------
1250
1251/// A `Copy`, `!Send` reactive value handle (§4.2).
1252pub 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    /// A process-global signal: allocated in the root scope regardless of where the call
1278    /// runs, so it never dies with a transient caller. **Every lazily-initialized global
1279    /// registry must use this, not [`Signal::new`]**, because a lazy global first touched inside a
1280    /// presented cover / pushed page / `when` arm otherwise inherits that scope and is
1281    /// disposed with it, and every later read panics (the day-localization locale signal was the
1282    /// observed case).
1283    #[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    /// Tracked read by reference.
1305    ///
1306    /// # Panics
1307    ///
1308    /// Panics when the signal's scope was disposed. Use [`Signal::try_with`] in closures that
1309    /// can outlive their scope.
1310    #[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        // Clone the shared cell out so `f` runs with the runtime borrow released (it routinely
1323        // reads other signals). The value stays in the node throughout, so a re-entrant read of
1324        // This signal inside `f` succeeds instead of reporting a disposed node, and a panic in
1325        // `f` cannot strand it.
1326        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    /// Mark-only tracked read (subscribe without reading).
1364    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            // Writes to disposed handles are defined no-ops (§4.3), warned once per callsite.
1404            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    /// A `Send` write-only handle (§3.3).
1421    #[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
1433/// `Send` write-only handle to a signal; delivery hops to the UI thread via the main poster.
1434/// Writes after disposal are silent no-ops (§4.3).
1435pub 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
1471// ---------------------------------------------------------------------------
1472// Memo
1473// ---------------------------------------------------------------------------
1474
1475/// Cached, equality-diffed derived value (§4.2).
1476pub 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        // The value is stored as EqBox<T> (value + comparator together), so diffing needs no
1502        // specialization and the arena-level eq is a plain fn pointer (eqbox_eq::<T>).
1503        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; // lazy: computed on first read
1514            node.created_at = created_at;
1515        });
1516        Memo {
1517            key,
1518            created_at,
1519            _m: PhantomData,
1520        }
1521    }
1522
1523    /// Tracked read by reference, recomputing first when a source changed.
1524    ///
1525    /// # Panics
1526    ///
1527    /// Panics when the memo's scope was disposed.
1528    #[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            // Shared, like `Signal::try_with`: the memo stays readable while `f` runs.
1537            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
1561/// Value + comparator stored together so memo diffing needs no specialization.
1562struct 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
1574// ---------------------------------------------------------------------------
1575// Effect / bind / watch / Trigger
1576// ---------------------------------------------------------------------------
1577
1578/// A reaction that re-runs when its tracked reads change. Runs once at creation.
1579/// Every run enters the scope that created it. Ambient context and any new state or
1580/// cleanup registrations belong to that owner, including when another scope triggers it.
1581pub struct Effect;
1582
1583impl Effect {
1584    // Constructor-style registration: the reaction is owned by the current Scope (disposed
1585    // with it), so there is no handle value to return.
1586    #[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/// The binding primitive (§4.2): compute (tracked) + apply (untracked), equality-gated.
1619/// Structural priority: bindings drain before plain effects. `apply` receives the new value
1620/// by reference so `V` needs only `PartialEq` (no `Clone`).
1621#[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/// `bind` pre-seeded with the value already applied at build time: the initial run does not
1640/// re-apply (pieces pass initial values through realize props; §5.2's no-duplicate-op rule).
1641#[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/// `bind` for payloads without `PartialEq`, applying on every recompute.
1661#[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/// Derive-state without effect-write loops (§4.2): `source` is tracked; `cb` runs untracked
1673/// with (new, old). Does not fire for the initial value: a "load whatever is selected"
1674/// reaction has to run once by hand first, or use [`bind`], which applies the initial value
1675/// and then every change.
1676#[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/// Data-less invalidation source.
1695#[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
1722// ---------------------------------------------------------------------------
1723// Two-way binding surface (§5.3)
1724// ---------------------------------------------------------------------------
1725
1726/// A readable-writable value a control can bind to two-way: a `Signal`, or any projection that
1727/// knows how to read and write its own slot (day-model's `Field` is the other implementor).
1728///
1729/// The trait lives here rather than in day-pieces so a store crate can implement it without
1730/// depending on the piece vocabulary; day-pieces re-exports it, so piece code sees no move.
1731pub trait Binding<T: 'static>: Clone + 'static {
1732    /// Tracked read: the current value, subscribing the running computation to changes.
1733    fn read(&self) -> T;
1734    /// Untracked read: the current value, subscribing nothing (the reactive world's "peek").
1735    fn peek(&self) -> T;
1736    /// Write the value, waking whatever tracks it.
1737    fn write(&self, v: T);
1738    /// A live write mid-gesture (`Event::ValueChanged`): readers must follow, but nothing
1739    /// durable should key off it. Defaults to [`Binding::write`]: a plain signal has no
1740    /// notion of "durable", and a degraded backend that never commits stays correct.
1741    fn write_preview(&self, v: T) {
1742        self.write(v);
1743    }
1744    /// The settled value that ends a gesture (`Event::ValueCommitted`). Defaults to
1745    /// [`Binding::write`]; a day-model field seals its preview session here: one change
1746    /// record, one undo unit, one UPDATE for the whole drag.
1747    fn write_commit(&self, v: T) {
1748        self.write(v);
1749    }
1750    /// Seal the last preview when its control is disposed. Persistent bindings default to
1751    /// committing; scope-owned signals have already received the preview and may be gone.
1752    fn write_teardown(&self, v: T) {
1753        self.write_commit(v);
1754    }
1755    /// Close an open preview session without recording it: the app wrote a value of its own over
1756    /// what the gesture previewed (a text field's text replaced while being typed in), and that
1757    /// write recorded its own change. The next preview starts a fresh session whose prior is
1758    /// the app's value. Defaults to nothing: a plain signal keeps no session.
1759    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
1775/// The object-safe half of [`Binding`], behind [`AnyBinding`]. Its methods carry an `erased_`
1776/// prefix so a call on a `Signal` inside this crate never sees two candidates named `read`.
1777trait 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
1811/// A type-erased [`Binding`]: what a piece stores when its builder takes `impl Binding<T>`
1812/// (docs/api-style.md "Three input spellings"), so the piece itself needs no type parameter
1813/// per bound value.
1814///
1815/// `Copy`, like [`Signal`], so it captures into closures the same way: the erased binding lives
1816/// in a slot owned by the reactive scope that created it, which is the scope building the
1817/// piece. Reads and writes forward to the binding it wraps, preview and commit included.
1818pub 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    /// Erase `binding`. Call it where the piece is built: the slot belongs to the current scope.
1831    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    /// Tracked read.
1841    #[must_use]
1842    pub fn get(self) -> T {
1843        self.inner().erased_read()
1844    }
1845    /// Tracked read, or `None` once the scope that created the binding is disposed.
1846    #[must_use]
1847    pub fn try_get(self) -> Option<T> {
1848        self.slot.try_get().map(|b| b.erased_read())
1849    }
1850    /// Untracked read.
1851    #[must_use]
1852    pub fn get_untracked(self) -> T {
1853        self.inner().erased_peek()
1854    }
1855    /// Tracked read through a projection.
1856    pub fn with<R>(self, f: impl FnOnce(&T) -> R) -> R {
1857        let v = self.inner().erased_read();
1858        f(&v)
1859    }
1860    /// Write, waking whatever tracks the binding.
1861    pub fn set(self, v: T) {
1862        self.inner().erased_write(v);
1863    }
1864    /// Write only when the value differs from the current one.
1865    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    /// Read the current value, let `f` change it, write it back.
1875    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// ---------------------------------------------------------------------------
1908// Async data loading: Load + Resource (§4.5, docs/async.md)
1909// ---------------------------------------------------------------------------
1910
1911/// The lifecycle of an async-loaded value. `Failed` carries the fetcher's error as a shared
1912/// trait object so `Load` stays `Clone` for signal reads.
1913#[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    /// The loaded value, if ready.
1922    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    /// The failure, if the last fetch failed.
1935    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
1953/// Latest-wins bookkeeping shared by a Resource's reaction, its spawned futures, and disposal.
1954struct FetchState {
1955    generation: Cell<u64>,
1956    abort: RefCell<Option<Box<dyn FnOnce()>>>,
1957}
1958
1959impl FetchState {
1960    /// Invalidate the in-flight fetch: bump the generation first (so a completion that cannot
1961    /// be aborted still fails its check), then take-and-call the abort outside the borrow
1962    /// (dropping a future can re-enter reactive state).
1963    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
1974/// Declarative async data loading (§4.5): a tracked `source` whose value feeds an async
1975/// `fetcher`; the result lands in a `Signal<Load<T>>`. The source re-runs when its tracked
1976/// reads change; an unchanged source value refetches nothing, [`Resource::refetch`] always
1977/// does. Latest wins: a source change supersedes the in-flight fetch (aborting its task;
1978/// dropping any `FetchFuture` inside cancels the platform request) and a stale completion
1979/// writes nothing. Scope disposal aborts the in-flight fetch the same way.
1980///
1981/// ```ignore
1982/// let stations = Resource::new(
1983///     move || region.get(),                              // tracked: refetch on change
1984///     |region| async move { fetch_stations(region).await },
1985/// );
1986/// when(move || stations.ready(), move || station_list(stations));
1987/// ```
1988pub 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    /// Start loading: `source` runs tracked (its signal reads become dependencies) and its
2003    /// value moves into `fetcher`'s future, which runs on the main-loop executor via the
2004    /// installed spawner, so no `Send` bound anywhere, and the future may read/write signals
2005    /// after its awaits. Infallible fetchers use `E = std::convert::Infallible`.
2006    #[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                // Tracked reads first: the refetch counter and the source. Everything else runs
2027                // untracked: the fetcher may read signals without making them dependencies.
2028                let count = refetch_count.get();
2029                let s = source();
2030                let fs = reaction_fs.clone();
2031                untrack(|| {
2032                    // Equality gate on (source value, refetch count): a rerun caused by an
2033                    // unrelated tracked read refetches nothing; refetch() always changes the
2034                    // pair, so it always fetches.
2035                    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; // superseded while in flight; latest wins
2051                        }
2052                        done.abort.borrow_mut().take(); // completed: the stored abort is dead
2053                        match result {
2054                            Ok(v) => state.set(Load::Ready(v)),
2055                            Err(e) => state.set(Load::Failed(Arc::new(e))),
2056                        }
2057                    }));
2058                    // Eager-poll ordering: the spawner polls once before returning, so a
2059                    // synchronously-ready fetcher has already completed here; storing its
2060                    // abort is harmless only because the spawner contract makes aborting a
2061                    // finished task a no-op (this line is why that contract exists).
2062                    *fs.abort.borrow_mut() = Some(abort);
2063                });
2064            }),
2065            1,
2066        );
2067        // Disposal: supersede + abort the in-flight task. (A completion that slipped through
2068        // would write to disposed signals, the defined no-op, but aborting frees the platform
2069        // request immediately.)
2070        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    /// The underlying state signal (tracked reads, `when(move || …)` guards, `each` sources).
2082    #[must_use]
2083    pub fn signal(self) -> Signal<Load<T>> {
2084        self.state
2085    }
2086
2087    /// The current load state (tracked).
2088    #[must_use]
2089    pub fn get(self) -> Load<T>
2090    where
2091        T: Clone,
2092    {
2093        self.state.get()
2094    }
2095
2096    /// Read the current load state by reference (tracked).
2097    pub fn with<R>(self, f: impl FnOnce(&Load<T>) -> R) -> R {
2098        self.state.with(f)
2099    }
2100
2101    /// Whether a fetch is in flight (tracked).
2102    pub fn loading(self) -> bool {
2103        self.with(Load::is_loading)
2104    }
2105
2106    /// Whether a value is ready (tracked): `when(move || r.ready(), …)`.
2107    pub fn ready(self) -> bool {
2108        self.with(Load::is_ready)
2109    }
2110
2111    /// Force a refetch with the current source value (even if unchanged).
2112    pub fn refetch(self) {
2113        self.refetch_count.update(|c| *c = c.wrapping_add(1));
2114    }
2115}
2116
2117// ---------------------------------------------------------------------------
2118// Tests
2119// ---------------------------------------------------------------------------
2120
2121#[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); // initial run
2196        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); // initial + one drain
2216        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); // no re-run
2229    }
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); // cached
2243        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)); // same value → memo recomputes? signal changed, memo recomputes, same output
2250        // memo output unchanged (1*2 == 2)? s was already 1 → set(1) marks dirty (set is not diffed)
2251        assert_eq!(effect_runs.get(), 1); // memo diffing gates the effect
2252        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)); // update always marks; bind's eq gate stops the apply
2270        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); // effect gone
2307        inner.set(9); // silent no-op
2308        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        // Owner effect (created first in outer scope) disposes the child scope when s becomes 1.
2317        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        // Owner ran first (created earlier, same depth? owner depth 0 < child depth 1) and
2335        // disposed the child → child effect must not run again.
2336        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); // write during drain extends the drain
2347            }
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    // Debug-only: release warns-and-defers instead of panicking (the release
2360    // side is pinned by `unwind_safety_tests::rerun_cap_defers_instead_of_killing_the_binding`).
2361    #[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); // classic cycle
2369        });
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        // Outside a turn: now.
2417        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        // Inside a batch: after the drain, and before the standing hooks.
2422        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        // A batch with no reactive work still ends its turn for a deferred callback.
2437        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        // Plain effect created first (lower seq); priority must still put the bind first.
2449        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    // ---- test executor: mirrors day::task's shape (eager first poll; abort = remove+drop;
2467    // pump() re-polls whatever is still pending). `ABORTED` records aborts of still-pending
2468    // tasks, the probe the latest-wins/disposal tests read. All thread-local: each #[test]
2469    // thread gets a fresh Runtime and a fresh executor.
2470
2471    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        // SAFETY: every vtable entry ignores the data pointer.
2485        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    /// Re-poll every pending task once (completions drop out).
2526    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        // Completions wrote signals; with no scheduler installed a test must drain explicitly
2547        // (the production main loop drains via the installed scheduler).
2548        flush_sync();
2549    }
2550
2551    type Slot<T> = Rc<RefCell<Option<Result<T, TestErr>>>>;
2552
2553    /// A future the test resolves by hand (fill the slot, then `pump()`); no waker wiring, since
2554    /// pump re-polls everything.
2555    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(); // tracked but not part of the source value
2632                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)); // reruns the reaction; the source value is unchanged → no refetch
2641        assert_eq!(fetches.get(), 1);
2642        assert_eq!(r.with(|l| l.ready().copied()), Some(1));
2643        batch(|| a.set(2)); // the value changed → refetch
2644        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()); // same source value; the refetch counter forces it past the gate
2661        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)); // supersede generation 1 while it is in flight
2681        assert_eq!(aborted_count(), before + 1, "the stale task was aborted");
2682        // Resolving generation 1 anyway must change nothing (its future is gone).
2683        *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        // Resolving afterwards is inert: the future is gone; nothing pends; no panic.
2703        *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        // No test spawner installed: this test thread's Runtime has none.
2729        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    /// Run `f`, swallowing a panic, with the panic hook silenced so the test output stays clean.
2738    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    /// A panic inside `Scope::enter` must not leave the runtime parented to the transient scope.
2747    /// Before the guard, every later `Signal::new` landed in a disposed scope and its first read
2748    /// panicked with a misleading "read of disposed Signal".
2749    #[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        // The real symptom: a signal created afterwards must still be alive and readable.
2756        let s = Signal::new(7u32);
2757        assert_eq!(s.get(), 7);
2758    }
2759
2760    /// A panic inside `untrack` must pop its `None` observer, or dependency tracking stays off
2761    /// for the rest of the process and nothing ever updates again.
2762    /// A panic inside an effect's own closure (contained by a backend trampoline) must pop
2763    /// the effect's observer frame during unwind; a stranded frame would attribute every
2764    /// later read to the dead run, even through a user's own `catch_unwind`, without any
2765    /// call to `recover_from_panic`.
2766    #[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(); // clear draining/pending for the tests that follow
2781    }
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        // Tracking still works: an effect re-runs when its source changes.
2790        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    /// A panic inside `batch` must not strand `batch_depth`, which would stop every later write
2808    /// from scheduling a drain.
2809    #[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    /// A panic inside a `with` closure must not consume the signal's value. Before the value was
2817    /// shared it was taken out for the closure's duration, so an unwind lost it permanently and
2818    /// the signal was dead for the rest of the process.
2819    #[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    /// Reading a signal from inside its own `with` closure now works. It used to find the hole
2827    /// left by the take and panic with "read of disposed Signal".
2828    #[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    /// Two different signals read inside one another's closures: the ordinary case, and the
2841    /// reason the closure must run with the runtime borrow released.
2842    #[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    /// Writing a signal while a read of it is in flight is reported instead of silently lost.
2850    #[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        // A `panic!` with no format arguments carries a `&'static str`, not a `String`.
2861        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    /// Release builds must survive a reactive cycle: the capped effect is skipped for the
2873    /// rest of the drain but re-arms on the next source write; it must not be permanently
2874    /// disabled. Release-only because the same cycle panics under
2875    /// `debug_assertions`; run via `cargo test --release -p day-reactive`.
2876    #[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); // self-sustaining cycle: trips the cap every drain
2887            }
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        // A fresh external write must re-arm the effect with a new per-drain budget.
2897        batch(|| s.set(2_000_000)); // past the cycle threshold: the effect runs once, quietly
2898        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}