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, sorted by deadline, and each native timer runs every closure due by
931/// the time it 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#[cfg(not(target_arch = "wasm32"))]
934mod delayed {
935    use std::cmp::Reverse;
936    use std::collections::BinaryHeap;
937    use std::sync::{Mutex, PoisonError};
938    use std::time::{Duration, Instant};
939
940    type Job = Box<dyn FnOnce() + Send>;
941
942    struct Entry {
943        due: Instant,
944        /// Arming order, so two closures due at the same instant run first-armed first.
945        seq: u64,
946        job: Job,
947    }
948
949    impl PartialEq for Entry {
950        fn eq(&self, other: &Self) -> bool {
951            (self.due, self.seq) == (other.due, other.seq)
952        }
953    }
954    impl Eq for Entry {}
955    impl PartialOrd for Entry {
956        fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
957            Some(self.cmp(other))
958        }
959    }
960    impl Ord for Entry {
961        fn cmp(&self, other: &Self) -> std::cmp::Ordering {
962            (self.due, self.seq).cmp(&(other.due, other.seq))
963        }
964    }
965
966    struct Queue {
967        waiting: BinaryHeap<Reverse<Entry>>,
968        next_seq: u64,
969    }
970
971    static QUEUE: Mutex<Queue> = Mutex::new(Queue {
972        waiting: BinaryHeap::new(),
973        next_seq: 0,
974    });
975
976    /// Queue `job` to be due `ms` from now; the returned closure is what the native timer runs.
977    pub(super) fn arm(ms: u32, job: Job) -> Job {
978        let due = Instant::now() + Duration::from_millis(u64::from(ms));
979        {
980            let mut queue = QUEUE.lock().unwrap_or_else(PoisonError::into_inner);
981            let seq = queue.next_seq;
982            queue.next_seq += 1;
983            queue.waiting.push(Reverse(Entry { due, seq, job }));
984        }
985        Box::new(move || run_due(due))
986    }
987
988    /// Run every waiting closure due by now, and in any case by `own`: a timer that fires a hair
989    /// early by this clock still runs the closure it was armed for.
990    fn run_due(own: Instant) {
991        let until = own.max(Instant::now());
992        loop {
993            // The lock is released before the closure runs: it may arm another timer.
994            let job = {
995                let mut queue = QUEUE.lock().unwrap_or_else(PoisonError::into_inner);
996                match queue.waiting.peek() {
997                    Some(Reverse(entry)) if entry.due <= until => {
998                        queue.waiting.pop().map(|Reverse(entry)| entry.job)
999                    }
1000                    _ => None,
1001                }
1002            };
1003            let Some(job) = job else { break };
1004            job();
1005        }
1006    }
1007
1008    #[cfg(test)]
1009    mod tests {
1010        use super::*;
1011        use std::sync::Arc;
1012
1013        /// Timers dispatched late and in arming order still run their closures in deadline
1014        /// order: the case a stalled `GLib` main loop produces.
1015        #[test]
1016        fn overdue_timers_run_in_deadline_order_whatever_order_they_fire_in() {
1017            let ran = Arc::new(Mutex::new(Vec::new()));
1018            let mut timers = Vec::new();
1019            for ms in [200u32, 10, 100, 50] {
1020                let ran = ran.clone();
1021                timers.push(arm(ms, Box::new(move || ran.lock().unwrap().push(ms))));
1022            }
1023            // Everything is overdue by the time the loop gets round to it.
1024            std::thread::sleep(Duration::from_millis(230));
1025            for timer in timers {
1026                timer();
1027            }
1028            assert_eq!(*ran.lock().unwrap(), [10, 50, 100, 200]);
1029        }
1030
1031        /// A timer runs its own closure even when nothing else is due, and leaves later ones.
1032        #[test]
1033        fn a_timer_runs_its_own_closure_and_nothing_due_later() {
1034            let ran = Arc::new(Mutex::new(Vec::new()));
1035            let note = |tag: &'static str| {
1036                let ran = ran.clone();
1037                Box::new(move || ran.lock().unwrap().push(tag)) as Job
1038            };
1039            let soon = arm(0, note("soon"));
1040            let later = arm(60_000, note("later"));
1041            soon();
1042            assert_eq!(*ran.lock().unwrap(), ["soon"]);
1043            // Fired a minute early by this clock: it still runs the closure it was armed for.
1044            later();
1045            assert_eq!(*ran.lock().unwrap(), ["soon", "later"]);
1046        }
1047    }
1048}
1049
1050// ---------------------------------------------------------------------------
1051// Scope
1052// ---------------------------------------------------------------------------
1053
1054/// Ownership scope for signals/effects (§4.3). `Copy` handle; not `Send`.
1055#[derive(Clone, Copy, PartialEq, Eq)]
1056pub struct Scope {
1057    key: ScopeKey,
1058    _not_send: PhantomData<*const ()>,
1059}
1060
1061impl Scope {
1062    pub fn current() -> Scope {
1063        Scope {
1064            key: with_rt(|rt| rt.current_scope),
1065            _not_send: PhantomData,
1066        }
1067    }
1068
1069    pub fn root() -> Scope {
1070        Scope {
1071            key: with_rt(|rt| rt.root_scope),
1072            _not_send: PhantomData,
1073        }
1074    }
1075
1076    /// Create a child of the current scope.
1077    pub fn child() -> Scope {
1078        Scope::current().create_child()
1079    }
1080
1081    #[must_use]
1082    pub fn create_child(self) -> Scope {
1083        let key = with_rt(|rt| {
1084            let depth = rt.scopes.get(self.key).map_or(1, |s| s.depth + 1);
1085            let child = rt.scopes.insert(ScopeData {
1086                parent: self.key,
1087                children: Vec::new(),
1088                nodes: Vec::new(),
1089                cleanups: Vec::new(),
1090                context: HashMap::new(),
1091                depth,
1092            });
1093            if let Some(p) = rt.scopes.get_mut(self.key) {
1094                p.children.push(child);
1095            }
1096            child
1097        });
1098        Scope {
1099            key,
1100            _not_send: PhantomData,
1101        }
1102    }
1103
1104    /// A scope owned by nobody; dispose it manually.
1105    pub fn detached() -> Scope {
1106        let key = with_rt(|rt| {
1107            rt.scopes.insert(ScopeData {
1108                parent: ScopeKey::null(),
1109                children: Vec::new(),
1110                nodes: Vec::new(),
1111                cleanups: Vec::new(),
1112                context: HashMap::new(),
1113                depth: 0,
1114            })
1115        });
1116        Scope {
1117            key,
1118            _not_send: PhantomData,
1119        }
1120    }
1121
1122    /// Run `f` with `self` as the current scope.
1123    pub fn enter<R>(self, f: impl FnOnce() -> R) -> R {
1124        let prev = with_rt(|rt| std::mem::replace(&mut rt.current_scope, self.key));
1125        // Restored on unwind too. Otherwise a contained panic leaves the runtime parented to
1126        // this (usually transient, soon-disposed) scope, so every later `Signal::new` is created
1127        // dead and its first read panics with a misleading "read of disposed Signal".
1128        let _g = rt_guard(move |rt: &mut Runtime| rt.current_scope = prev);
1129        f()
1130    }
1131
1132    pub fn on_cleanup(self, f: impl FnOnce() + 'static) {
1133        with_rt(|rt| {
1134            if let Some(s) = rt.scopes.get_mut(self.key) {
1135                s.cleanups.push(Box::new(f));
1136            }
1137        });
1138    }
1139
1140    #[must_use]
1141    pub fn is_alive(self) -> bool {
1142        with_rt(|rt| rt.scopes.contains_key(self.key))
1143    }
1144
1145    /// Dispose this scope: children first, then own nodes (unsubscribed + dropped) and cleanups.
1146    pub fn dispose(self) {
1147        let Some(children) = with_rt(|rt| rt.scopes.get(self.key).map(|s| s.children.clone()))
1148        else {
1149            return;
1150        };
1151        for c in children {
1152            (Scope {
1153                key: c,
1154                _not_send: PhantomData,
1155            })
1156            .dispose();
1157        }
1158        let Some((nodes, cleanups, parent)) = with_rt(|rt| {
1159            rt.scopes
1160                .remove(self.key)
1161                .map(|s| (s.nodes, s.cleanups, s.parent))
1162        }) else {
1163            return;
1164        };
1165        let mut run_cleanups: Vec<Box<dyn FnOnce()>> = Vec::new();
1166        with_rt(|rt| {
1167            if let Some(p) = rt.scopes.get_mut(parent)
1168                && let Some(pos) = p.children.iter().position(|&c| c == self.key)
1169            {
1170                p.children.swap_remove(pos);
1171            }
1172            for key in nodes {
1173                run_cleanups.extend(clear_sources(rt, key));
1174                // Detach us from downstream observers too.
1175                if let Some(node) = rt.nodes.get_mut(key) {
1176                    let observers = std::mem::take(&mut node.observers);
1177                    for o in observers {
1178                        if let Some(on) = rt.nodes.get_mut(o)
1179                            && let Some(pos) = on.sources.iter().position(|&s| s == key)
1180                        {
1181                            on.sources.swap_remove(pos);
1182                        }
1183                    }
1184                }
1185                rt.nodes.remove(key);
1186                // Pending entries for removed nodes are skipped at pop (generational key check).
1187            }
1188        });
1189        // A dying computation's per-run claims drop like a re-track would drop them: outside
1190        // the borrow, before the scope's own cleanups (which may release scope-level claims).
1191        for f in run_cleanups {
1192            f();
1193        }
1194        for c in cleanups {
1195            c();
1196        }
1197    }
1198
1199    /// Provide a context value visible to this scope and its descendants.
1200    pub fn provide<T: 'static>(self, value: T) {
1201        with_rt(|rt| {
1202            if let Some(s) = rt.scopes.get_mut(self.key) {
1203                s.context.insert(TypeId::of::<T>(), Box::new(value));
1204            }
1205        });
1206    }
1207
1208    /// Look up a context value here or in any ancestor (requires `T: Clone`).
1209    #[must_use]
1210    pub fn use_context<T: Clone + 'static>(self) -> Option<T> {
1211        with_rt(|rt| {
1212            let mut cur = self.key;
1213            while let Some(s) = rt.scopes.get(cur) {
1214                if let Some(v) = s.context.get(&TypeId::of::<T>()) {
1215                    return v.downcast_ref::<T>().cloned();
1216                }
1217                cur = s.parent;
1218            }
1219            None
1220        })
1221    }
1222}
1223
1224// ---------------------------------------------------------------------------
1225// Signal
1226// ---------------------------------------------------------------------------
1227
1228/// A `Copy`, `!Send` reactive value handle (§4.2).
1229pub struct Signal<T: 'static> {
1230    key: NodeKey,
1231    created_at: &'static Location<'static>,
1232    _m: PhantomData<*const T>,
1233}
1234
1235impl<T: 'static> Clone for Signal<T> {
1236    fn clone(&self) -> Self {
1237        *self
1238    }
1239}
1240impl<T: 'static> Copy for Signal<T> {}
1241
1242impl<T: 'static> std::fmt::Debug for Signal<T> {
1243    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1244        write!(f, "Signal({:?})", self.key)
1245    }
1246}
1247
1248impl<T: 'static> Signal<T> {
1249    #[track_caller]
1250    pub fn new(value: T) -> Self {
1251        Self::new_in(Scope::current(), value)
1252    }
1253
1254    /// A process-global signal: allocated in the root scope regardless of where the call
1255    /// runs, so it never dies with a transient caller. **Every lazily-initialized global
1256    /// registry must use this, not [`Signal::new`]**, because a lazy global first touched inside a
1257    /// presented cover / pushed page / `when` arm otherwise inherits that scope and is
1258    /// disposed with it, and every later read panics (the day-localization locale signal was the
1259    /// observed case).
1260    #[track_caller]
1261    pub fn global(value: T) -> Self {
1262        Self::new_in(Scope::root(), value)
1263    }
1264
1265    #[track_caller]
1266    pub fn new_in(scope: Scope, value: T) -> Self {
1267        let created_at = Location::caller();
1268        let key = with_rt(|rt| {
1269            let k = create_node(rt, NodeKind::Signal, scope.key);
1270            rt.nodes[k].value = Some(Rc::new(RefCell::new(Box::new(value) as Box<dyn Any>)));
1271            rt.nodes[k].created_at = created_at;
1272            k
1273        });
1274        Signal {
1275            key,
1276            created_at,
1277            _m: PhantomData,
1278        }
1279    }
1280
1281    /// Tracked read by reference.
1282    ///
1283    /// # Panics
1284    ///
1285    /// Panics when the signal's scope was disposed. Use [`Signal::try_with`] in closures that
1286    /// can outlive their scope.
1287    #[track_caller]
1288    pub fn with<R>(self, f: impl FnOnce(&T) -> R) -> R {
1289        match self.try_with(f) {
1290            Some(r) => r,
1291            None => panic!(
1292                "day-reactive: read of disposed Signal created at {} (use try_with in closures that can outlive their scope)",
1293                self.created_at
1294            ),
1295        }
1296    }
1297
1298    pub fn try_with<R>(self, f: impl FnOnce(&T) -> R) -> Option<R> {
1299        // Clone the shared cell out so `f` runs with the runtime borrow released (it routinely
1300        // reads other signals). The value stays in the node throughout, so a re-entrant read of
1301        // This signal inside `f` succeeds instead of reporting a disposed node, and a panic in
1302        // `f` cannot strand it.
1303        let cell = with_rt(|rt| {
1304            track_read(rt, self.key);
1305            rt.nodes.get(self.key).and_then(|n| n.value.clone())
1306        })?;
1307        let value = cell.borrow();
1308        value.downcast_ref::<T>().map(f)
1309    }
1310
1311    pub fn with_untracked<R>(self, f: impl FnOnce(&T) -> R) -> R {
1312        untrack(|| self.with(f))
1313    }
1314
1315    #[track_caller]
1316    #[must_use]
1317    pub fn get(self) -> T
1318    where
1319        T: Clone,
1320    {
1321        self.with(std::clone::Clone::clone)
1322    }
1323
1324    #[must_use]
1325    pub fn try_get(self) -> Option<T>
1326    where
1327        T: Clone,
1328    {
1329        self.try_with(std::clone::Clone::clone)
1330    }
1331
1332    #[must_use]
1333    pub fn get_untracked(self) -> T
1334    where
1335        T: Clone,
1336    {
1337        untrack(|| self.get())
1338    }
1339
1340    /// Mark-only tracked read (subscribe without reading).
1341    pub fn track(self) {
1342        with_rt(|rt| track_read(rt, self.key));
1343    }
1344
1345    #[track_caller]
1346    pub fn set(self, value: T) {
1347        self.write_check(move |slot| {
1348            *slot = value;
1349            true
1350        });
1351    }
1352
1353    #[track_caller]
1354    pub fn set_if_changed(self, value: T)
1355    where
1356        T: PartialEq,
1357    {
1358        self.write_check(move |slot| {
1359            if *slot == value {
1360                false
1361            } else {
1362                *slot = value;
1363                true
1364            }
1365        });
1366    }
1367
1368    #[track_caller]
1369    pub fn update(self, f: impl FnOnce(&mut T)) {
1370        self.write_check(move |slot| {
1371            f(slot);
1372            true
1373        });
1374    }
1375
1376    #[track_caller]
1377    fn write_check(self, apply: impl FnOnce(&mut T) -> bool) {
1378        let alive = with_rt(|rt| rt.nodes.contains_key(self.key));
1379        if !alive {
1380            // Writes to disposed handles are defined no-ops (§4.3), warned once per callsite.
1381            let loc = Location::caller();
1382            let first = with_rt(|rt| rt.warned_writes.insert(std::ptr::from_ref(loc)));
1383            if first && cfg!(debug_assertions) {
1384                log::warn!(
1385                    "day-reactive: write at {loc} to a disposed signal (created at {}) ignored",
1386                    self.created_at
1387                );
1388            }
1389            return;
1390        }
1391        signal_write_boxed(self.key, |boxed| match boxed.downcast_mut::<T>() {
1392            Some(slot) => apply(slot),
1393            None => false,
1394        });
1395    }
1396
1397    /// A `Send` write-only handle (§3.3).
1398    #[must_use]
1399    pub fn setter(self) -> Setter<T>
1400    where
1401        T: Send,
1402    {
1403        Setter {
1404            key: self.key,
1405            _m: PhantomData,
1406        }
1407    }
1408}
1409
1410/// `Send` write-only handle to a signal; delivery hops to the UI thread via the main poster.
1411/// Writes after disposal are silent no-ops (§4.3).
1412pub struct Setter<T: Send + 'static> {
1413    key: NodeKey,
1414    _m: PhantomData<fn(T)>,
1415}
1416
1417impl<T: Send + 'static> Clone for Setter<T> {
1418    fn clone(&self) -> Self {
1419        *self
1420    }
1421}
1422impl<T: Send + 'static> Copy for Setter<T> {}
1423
1424impl<T: Send + 'static> Setter<T> {
1425    pub fn set(self, value: T) {
1426        let key = self.key;
1427        on_main(move || {
1428            let poster = with_rt(|rt| {
1429                let cell = rt.nodes.get(key)?.value.clone()?;
1430                {
1431                    let mut boxed = cell.try_borrow_mut().ok()?;
1432                    let slot = boxed.downcast_mut::<T>()?;
1433                    *slot = value;
1434                }
1435                let node = rt.nodes.get_mut(key)?;
1436                node.last_changed = rt.tick;
1437                rt.tick += 1;
1438                mark_observers(rt, key, NodeState::Dirty);
1439                schedule_after_write(rt)
1440            });
1441            if let Some(post) = poster {
1442                post();
1443            }
1444        });
1445    }
1446}
1447
1448// ---------------------------------------------------------------------------
1449// Memo
1450// ---------------------------------------------------------------------------
1451
1452/// Cached, equality-diffed derived value (§4.2).
1453pub struct Memo<T: 'static> {
1454    key: NodeKey,
1455    created_at: &'static Location<'static>,
1456    _m: PhantomData<*const T>,
1457}
1458
1459impl<T: 'static> Clone for Memo<T> {
1460    fn clone(&self) -> Self {
1461        *self
1462    }
1463}
1464impl<T: 'static> Copy for Memo<T> {}
1465
1466impl<T: 'static> Memo<T> {
1467    #[track_caller]
1468    pub fn new(f: impl Fn() -> T + 'static) -> Self
1469    where
1470        T: PartialEq,
1471    {
1472        Self::new_with_eq(f, |a, b| a == b)
1473    }
1474
1475    #[track_caller]
1476    pub fn new_with_eq(f: impl Fn() -> T + 'static, eq: fn(&T, &T) -> bool) -> Self {
1477        let created_at = Location::caller();
1478        // The value is stored as EqBox<T> (value + comparator together), so diffing needs no
1479        // specialization and the arena-level eq is a plain fn pointer (eqbox_eq::<T>).
1480        let key = with_rt(|rt| {
1481            let scope = rt.current_scope;
1482            create_node(rt, NodeKind::Memo, scope)
1483        });
1484        let compute: Rc<dyn Fn() -> Box<dyn Any>> =
1485            Rc::new(move || Box::new(EqBox { value: f(), eq }) as Box<dyn Any>);
1486        with_rt(|rt| {
1487            let node = &mut rt.nodes[key];
1488            node.memo_compute = Some(compute);
1489            node.memo_eq = Some(eqbox_eq::<T>);
1490            node.state = NodeState::Dirty; // lazy: computed on first read
1491            node.created_at = created_at;
1492        });
1493        Memo {
1494            key,
1495            created_at,
1496            _m: PhantomData,
1497        }
1498    }
1499
1500    /// Tracked read by reference, recomputing first when a source changed.
1501    ///
1502    /// # Panics
1503    ///
1504    /// Panics when the memo's scope was disposed.
1505    #[track_caller]
1506    pub fn with<R>(self, f: impl FnOnce(&T) -> R) -> R {
1507        refresh_memo(self.key);
1508        let value = with_rt(|rt| {
1509            track_read(rt, self.key);
1510            rt.nodes.get(self.key).and_then(|n| n.value.clone())
1511        });
1512        match value {
1513            // Shared, like `Signal::try_with`: the memo stays readable while `f` runs.
1514            Some(cell) => {
1515                let boxed = cell.borrow();
1516                boxed.downcast_ref::<EqBox<T>>().map_or_else(
1517                    || panic!("day-reactive: memo type mismatch"),
1518                    |e| f(&e.value),
1519                )
1520            }
1521            None => panic!(
1522                "day-reactive: read of disposed Memo created at {}",
1523                self.created_at
1524            ),
1525        }
1526    }
1527
1528    #[track_caller]
1529    #[must_use]
1530    pub fn get(self) -> T
1531    where
1532        T: Clone,
1533    {
1534        self.with(std::clone::Clone::clone)
1535    }
1536}
1537
1538/// Value + comparator stored together so memo diffing needs no specialization.
1539struct EqBox<T> {
1540    value: T,
1541    eq: fn(&T, &T) -> bool,
1542}
1543
1544fn eqbox_eq<T: 'static>(a: &dyn Any, b: &dyn Any) -> bool {
1545    match (a.downcast_ref::<EqBox<T>>(), b.downcast_ref::<EqBox<T>>()) {
1546        (Some(a), Some(b)) => (a.eq)(&a.value, &b.value),
1547        _ => false,
1548    }
1549}
1550
1551// ---------------------------------------------------------------------------
1552// Effect / bind / watch / Trigger
1553// ---------------------------------------------------------------------------
1554
1555/// A reaction that re-runs when its tracked reads change. Runs once at creation.
1556/// Every run enters the scope that created it. Ambient context and any new state or
1557/// cleanup registrations belong to that owner, including when another scope triggers it.
1558pub struct Effect;
1559
1560impl Effect {
1561    // Constructor-style registration: the reaction is owned by the current Scope (disposed
1562    // with it), so there is no handle value to return.
1563    #[allow(clippy::new_ret_no_self)]
1564    #[track_caller]
1565    pub fn new(f: impl Fn() + 'static) {
1566        create_reaction(Rc::new(f), 1);
1567    }
1568}
1569
1570#[track_caller]
1571fn create_reaction(f: Rc<dyn Fn()>, priority: u8) -> NodeKey {
1572    let created_at = Location::caller();
1573    let key = with_rt(|rt| {
1574        let scope = rt.current_scope;
1575        let k = create_node(rt, NodeKind::Reaction, scope);
1576        rt.nodes[k].reaction = Some(f);
1577        rt.nodes[k].priority = priority;
1578        rt.nodes[k].created_at = created_at;
1579        k
1580    });
1581    let reaction = with_rt(|rt| rt.nodes[key].reaction.clone());
1582    if let Some(reaction) = reaction {
1583        compute_in_owner(key, || reaction());
1584    }
1585    with_rt(|rt| {
1586        let tick = rt.tick;
1587        rt.tick += 1;
1588        if let Some(n) = rt.nodes.get_mut(key) {
1589            n.last_run = tick;
1590        }
1591    });
1592    key
1593}
1594
1595/// The binding primitive (§4.2): compute (tracked) + apply (untracked), equality-gated.
1596/// Structural priority: bindings drain before plain effects. `apply` receives the new value
1597/// by reference so `V` needs only `PartialEq` (no `Clone`).
1598#[track_caller]
1599pub fn bind<V: PartialEq + 'static>(
1600    compute: impl Fn() -> V + 'static,
1601    apply: impl Fn(&V) + 'static,
1602) {
1603    let last: RefCell<Option<V>> = RefCell::new(None);
1604    create_reaction(
1605        Rc::new(move || {
1606            let v = compute();
1607            if last.borrow().as_ref() != Some(&v) {
1608                untrack(|| apply(&v));
1609                *last.borrow_mut() = Some(v);
1610            }
1611        }),
1612        0,
1613    );
1614}
1615
1616/// `bind` pre-seeded with the value already applied at build time: the initial run does not
1617/// re-apply (pieces pass initial values through realize props; §5.2's no-duplicate-op rule).
1618#[track_caller]
1619pub fn bind_seeded<V: PartialEq + 'static>(
1620    seed: V,
1621    compute: impl Fn() -> V + 'static,
1622    apply: impl Fn(&V) + 'static,
1623) {
1624    let last: RefCell<Option<V>> = RefCell::new(Some(seed));
1625    create_reaction(
1626        Rc::new(move || {
1627            let v = compute();
1628            if last.borrow().as_ref() != Some(&v) {
1629                untrack(|| apply(&v));
1630                *last.borrow_mut() = Some(v);
1631            }
1632        }),
1633        0,
1634    );
1635}
1636
1637/// `bind` for payloads without `PartialEq`, applying on every recompute.
1638#[track_caller]
1639pub fn bind_always<V: 'static>(compute: impl Fn() -> V + 'static, apply: impl Fn(V) + 'static) {
1640    create_reaction(
1641        Rc::new(move || {
1642            let v = compute();
1643            untrack(|| apply(v));
1644        }),
1645        0,
1646    );
1647}
1648
1649/// Derive-state without effect-write loops (§4.2): `source` is tracked; `cb` runs untracked
1650/// with (new, old). Does not fire for the initial value: a "load whatever is selected"
1651/// reaction has to run once by hand first, or use [`bind`], which applies the initial value
1652/// and then every change.
1653#[track_caller]
1654pub fn watch<S: Clone + 'static>(
1655    source: impl Fn() -> S + 'static,
1656    cb: impl Fn(&S, Option<&S>) + 'static,
1657) {
1658    let prev: RefCell<Option<S>> = RefCell::new(None);
1659    create_reaction(
1660        Rc::new(move || {
1661            let new = source();
1662            let old = prev.borrow_mut().replace(new.clone());
1663            if old.is_some() {
1664                untrack(|| cb(&new, old.as_ref()));
1665            }
1666        }),
1667        1,
1668    );
1669}
1670
1671/// Data-less invalidation source.
1672#[derive(Clone, Copy)]
1673pub struct Trigger {
1674    signal: Signal<u64>,
1675}
1676
1677impl Trigger {
1678    #[track_caller]
1679    #[must_use]
1680    pub fn new() -> Self {
1681        Trigger {
1682            signal: Signal::new(0),
1683        }
1684    }
1685    pub fn track(self) {
1686        self.signal.track();
1687    }
1688    pub fn notify(self) {
1689        self.signal.update(|v| *v = v.wrapping_add(1));
1690    }
1691}
1692
1693impl Default for Trigger {
1694    fn default() -> Self {
1695        Self::new()
1696    }
1697}
1698
1699// ---------------------------------------------------------------------------
1700// Two-way binding surface (§5.3)
1701// ---------------------------------------------------------------------------
1702
1703/// A readable-writable value a control can bind to two-way: a `Signal`, or any projection that
1704/// knows how to read and write its own slot (day-model's `Field` is the other implementor).
1705///
1706/// The trait lives here rather than in day-pieces so a store crate can implement it without
1707/// depending on the piece vocabulary; day-pieces re-exports it, so piece code sees no move.
1708pub trait Binding<T: 'static>: Clone + 'static {
1709    /// Tracked read: the current value, subscribing the running computation to changes.
1710    fn read(&self) -> T;
1711    /// Untracked read: the current value, subscribing nothing (the reactive world's "peek").
1712    fn peek(&self) -> T;
1713    /// Write the value, waking whatever tracks it.
1714    fn write(&self, v: T);
1715    /// A live write mid-gesture (`Event::ValueChanged`): readers must follow, but nothing
1716    /// durable should key off it. Defaults to [`Binding::write`]: a plain signal has no
1717    /// notion of "durable", and a degraded backend that never commits stays correct.
1718    fn write_preview(&self, v: T) {
1719        self.write(v);
1720    }
1721    /// The settled value that ends a gesture (`Event::ValueCommitted`). Defaults to
1722    /// [`Binding::write`]; a day-model field seals its preview session here: one change
1723    /// record, one undo unit, one UPDATE for the whole drag.
1724    fn write_commit(&self, v: T) {
1725        self.write(v);
1726    }
1727    /// Seal the last preview when its control is disposed. Persistent bindings default to
1728    /// committing; scope-owned signals have already received the preview and may be gone.
1729    fn write_teardown(&self, v: T) {
1730        self.write_commit(v);
1731    }
1732    /// Close an open preview session without recording it: the app wrote a value of its own over
1733    /// what the gesture previewed (a text field's text replaced while being typed in), and that
1734    /// write recorded its own change. The next preview starts a fresh session whose prior is
1735    /// the app's value. Defaults to nothing: a plain signal keeps no session.
1736    fn end_preview(&self) {}
1737}
1738
1739impl<T: Clone + 'static> Binding<T> for Signal<T> {
1740    fn read(&self) -> T {
1741        self.get()
1742    }
1743    fn peek(&self) -> T {
1744        self.get_untracked()
1745    }
1746    fn write(&self, v: T) {
1747        self.set(v);
1748    }
1749    fn write_teardown(&self, _v: T) {}
1750}
1751
1752/// The object-safe half of [`Binding`], behind [`AnyBinding`]. Its methods carry an `erased_`
1753/// prefix so a call on a `Signal` inside this crate never sees two candidates named `read`.
1754trait ErasedBinding<T: 'static> {
1755    fn erased_read(&self) -> T;
1756    fn erased_peek(&self) -> T;
1757    fn erased_write(&self, v: T);
1758    fn erased_write_preview(&self, v: T);
1759    fn erased_write_commit(&self, v: T);
1760    fn erased_write_teardown(&self, v: T);
1761    fn erased_end_preview(&self);
1762}
1763
1764impl<T: 'static, B: Binding<T>> ErasedBinding<T> for B {
1765    fn erased_read(&self) -> T {
1766        Binding::read(self)
1767    }
1768    fn erased_peek(&self) -> T {
1769        Binding::peek(self)
1770    }
1771    fn erased_write(&self, v: T) {
1772        Binding::write(self, v);
1773    }
1774    fn erased_write_preview(&self, v: T) {
1775        Binding::write_preview(self, v);
1776    }
1777    fn erased_write_commit(&self, v: T) {
1778        Binding::write_commit(self, v);
1779    }
1780    fn erased_write_teardown(&self, v: T) {
1781        Binding::write_teardown(self, v);
1782    }
1783    fn erased_end_preview(&self) {
1784        Binding::end_preview(self);
1785    }
1786}
1787
1788/// A type-erased [`Binding`]: what a piece stores when its builder takes `impl Binding<T>`
1789/// (docs/api-style.md "Three input spellings"), so the piece itself needs no type parameter
1790/// per bound value.
1791///
1792/// `Copy`, like [`Signal`], so it captures into closures the same way: the erased binding lives
1793/// in a slot owned by the reactive scope that created it, which is the scope building the
1794/// piece. Reads and writes forward to the binding it wraps, preview and commit included.
1795pub struct AnyBinding<T: 'static> {
1796    slot: Signal<Rc<dyn ErasedBinding<T>>>,
1797}
1798
1799impl<T: 'static> Clone for AnyBinding<T> {
1800    fn clone(&self) -> Self {
1801        *self
1802    }
1803}
1804impl<T: 'static> Copy for AnyBinding<T> {}
1805
1806impl<T: 'static> AnyBinding<T> {
1807    /// Erase `binding`. Call it where the piece is built: the slot belongs to the current scope.
1808    pub fn new(binding: impl Binding<T>) -> Self {
1809        let erased: Rc<dyn ErasedBinding<T>> = Rc::new(binding);
1810        AnyBinding {
1811            slot: Signal::new(erased),
1812        }
1813    }
1814    fn inner(self) -> Rc<dyn ErasedBinding<T>> {
1815        self.slot.get_untracked()
1816    }
1817    /// Tracked read.
1818    #[must_use]
1819    pub fn get(self) -> T {
1820        self.inner().erased_read()
1821    }
1822    /// Tracked read, or `None` once the scope that created the binding is disposed.
1823    #[must_use]
1824    pub fn try_get(self) -> Option<T> {
1825        self.slot.try_get().map(|b| b.erased_read())
1826    }
1827    /// Untracked read.
1828    #[must_use]
1829    pub fn get_untracked(self) -> T {
1830        self.inner().erased_peek()
1831    }
1832    /// Tracked read through a projection.
1833    pub fn with<R>(self, f: impl FnOnce(&T) -> R) -> R {
1834        let v = self.inner().erased_read();
1835        f(&v)
1836    }
1837    /// Write, waking whatever tracks the binding.
1838    pub fn set(self, v: T) {
1839        self.inner().erased_write(v);
1840    }
1841    /// Write only when the value differs from the current one.
1842    pub fn set_if_changed(self, v: T)
1843    where
1844        T: PartialEq,
1845    {
1846        let b = self.inner();
1847        if b.erased_peek() != v {
1848            b.erased_write(v);
1849        }
1850    }
1851    /// Read the current value, let `f` change it, write it back.
1852    pub fn update(self, f: impl FnOnce(&mut T)) {
1853        let b = self.inner();
1854        let mut v = b.erased_peek();
1855        f(&mut v);
1856        b.erased_write(v);
1857    }
1858}
1859
1860impl<T: 'static> Binding<T> for AnyBinding<T> {
1861    fn read(&self) -> T {
1862        self.inner().erased_read()
1863    }
1864    fn peek(&self) -> T {
1865        self.inner().erased_peek()
1866    }
1867    fn write(&self, v: T) {
1868        self.inner().erased_write(v);
1869    }
1870    fn write_preview(&self, v: T) {
1871        self.inner().erased_write_preview(v);
1872    }
1873    fn write_commit(&self, v: T) {
1874        self.inner().erased_write_commit(v);
1875    }
1876    fn write_teardown(&self, v: T) {
1877        self.inner().erased_write_teardown(v);
1878    }
1879    fn end_preview(&self) {
1880        self.inner().erased_end_preview();
1881    }
1882}
1883
1884// ---------------------------------------------------------------------------
1885// Async data loading: Load + Resource (§4.5, docs/async.md)
1886// ---------------------------------------------------------------------------
1887
1888/// The lifecycle of an async-loaded value. `Failed` carries the fetcher's error as a shared
1889/// trait object so `Load` stays `Clone` for signal reads.
1890#[derive(Clone)]
1891pub enum Load<T> {
1892    Loading,
1893    Ready(T),
1894    Failed(Arc<dyn std::error::Error + Send + Sync>),
1895}
1896
1897impl<T> Load<T> {
1898    /// The loaded value, if ready.
1899    pub fn ready(&self) -> Option<&T> {
1900        match self {
1901            Load::Ready(v) => Some(v),
1902            _ => None,
1903        }
1904    }
1905    pub fn is_loading(&self) -> bool {
1906        matches!(self, Load::Loading)
1907    }
1908    pub fn is_ready(&self) -> bool {
1909        matches!(self, Load::Ready(_))
1910    }
1911    /// The failure, if the last fetch failed.
1912    pub fn error(&self) -> Option<&(dyn std::error::Error + Send + Sync + 'static)> {
1913        match self {
1914            Load::Failed(e) => Some(e.as_ref()),
1915            _ => None,
1916        }
1917    }
1918}
1919
1920impl<T: std::fmt::Debug> std::fmt::Debug for Load<T> {
1921    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1922        match self {
1923            Load::Loading => write!(f, "Loading"),
1924            Load::Ready(v) => f.debug_tuple("Ready").field(v).finish(),
1925            Load::Failed(e) => f.debug_tuple("Failed").field(&e.to_string()).finish(),
1926        }
1927    }
1928}
1929
1930/// Latest-wins bookkeeping shared by a Resource's reaction, its spawned futures, and disposal.
1931struct FetchState {
1932    generation: Cell<u64>,
1933    abort: RefCell<Option<Box<dyn FnOnce()>>>,
1934}
1935
1936impl FetchState {
1937    /// Invalidate the in-flight fetch: bump the generation first (so a completion that cannot
1938    /// be aborted still fails its check), then take-and-call the abort outside the borrow
1939    /// (dropping a future can re-enter reactive state).
1940    fn supersede(&self) -> u64 {
1941        let next = self.generation.get() + 1;
1942        self.generation.set(next);
1943        let old = self.abort.borrow_mut().take();
1944        if let Some(abort) = old {
1945            abort();
1946        }
1947        next
1948    }
1949}
1950
1951/// Declarative async data loading (§4.5): a tracked `source` whose value feeds an async
1952/// `fetcher`; the result lands in a `Signal<Load<T>>`. The source re-runs when its tracked
1953/// reads change; an unchanged source value refetches nothing, [`Resource::refetch`] always
1954/// does. Latest wins: a source change supersedes the in-flight fetch (aborting its task;
1955/// dropping any `FetchFuture` inside cancels the platform request) and a stale completion
1956/// writes nothing. Scope disposal aborts the in-flight fetch the same way.
1957///
1958/// ```ignore
1959/// let stations = Resource::new(
1960///     move || region.get(),                              // tracked: refetch on change
1961///     |region| async move { fetch_stations(region).await },
1962/// );
1963/// when(move || stations.ready(), move || station_list(stations));
1964/// ```
1965pub struct Resource<T: 'static> {
1966    state: Signal<Load<T>>,
1967    refetch_count: Signal<u64>,
1968    _not_send: PhantomData<*const T>,
1969}
1970
1971impl<T> Clone for Resource<T> {
1972    fn clone(&self) -> Self {
1973        *self
1974    }
1975}
1976impl<T> Copy for Resource<T> {}
1977
1978impl<T: 'static> Resource<T> {
1979    /// Start loading: `source` runs tracked (its signal reads become dependencies) and its
1980    /// value moves into `fetcher`'s future, which runs on the main-loop executor via the
1981    /// installed spawner, so no `Send` bound anywhere, and the future may read/write signals
1982    /// after its awaits. Infallible fetchers use `E = std::convert::Infallible`.
1983    #[track_caller]
1984    pub fn new<S, Fut, E>(
1985        source: impl Fn() -> S + 'static,
1986        fetcher: impl Fn(S) -> Fut + 'static,
1987    ) -> Resource<T>
1988    where
1989        S: Clone + PartialEq + 'static,
1990        Fut: Future<Output = Result<T, E>> + 'static,
1991        E: std::error::Error + Send + Sync + 'static,
1992    {
1993        let state: Signal<Load<T>> = Signal::new(Load::Loading);
1994        let refetch_count: Signal<u64> = Signal::new(0);
1995        let fs = Rc::new(FetchState {
1996            generation: Cell::new(0),
1997            abort: RefCell::new(None),
1998        });
1999        let reaction_fs = fs.clone();
2000        let prev: RefCell<Option<(S, u64)>> = RefCell::new(None);
2001        create_reaction(
2002            Rc::new(move || {
2003                // Tracked reads first: the refetch counter and the source. Everything else runs
2004                // untracked: the fetcher may read signals without making them dependencies.
2005                let count = refetch_count.get();
2006                let s = source();
2007                let fs = reaction_fs.clone();
2008                untrack(|| {
2009                    // Equality gate on (source value, refetch count): a rerun caused by an
2010                    // unrelated tracked read refetches nothing; refetch() always changes the
2011                    // pair, so it always fetches.
2012                    let same = prev
2013                        .borrow()
2014                        .as_ref()
2015                        .is_some_and(|(ps, pc)| ps == &s && *pc == count);
2016                    if same {
2017                        return;
2018                    }
2019                    *prev.borrow_mut() = Some((s.clone(), count));
2020                    let my_generation = fs.supersede();
2021                    state.set(Load::Loading);
2022                    let fut = fetcher(s);
2023                    let done = fs.clone();
2024                    let abort = spawn_local(Box::pin(async move {
2025                        let result = fut.await;
2026                        if done.generation.get() != my_generation {
2027                            return; // superseded while in flight; latest wins
2028                        }
2029                        done.abort.borrow_mut().take(); // completed: the stored abort is dead
2030                        match result {
2031                            Ok(v) => state.set(Load::Ready(v)),
2032                            Err(e) => state.set(Load::Failed(Arc::new(e))),
2033                        }
2034                    }));
2035                    // Eager-poll ordering: the spawner polls once before returning, so a
2036                    // synchronously-ready fetcher has already completed here; storing its
2037                    // abort is harmless only because the spawner contract makes aborting a
2038                    // finished task a no-op (this line is why that contract exists).
2039                    *fs.abort.borrow_mut() = Some(abort);
2040                });
2041            }),
2042            1,
2043        );
2044        // Disposal: supersede + abort the in-flight task. (A completion that slipped through
2045        // would write to disposed signals, the defined no-op, but aborting frees the platform
2046        // request immediately.)
2047        let cleanup_fs = fs;
2048        Scope::current().on_cleanup(move || {
2049            cleanup_fs.supersede();
2050        });
2051        Resource {
2052            state,
2053            refetch_count,
2054            _not_send: PhantomData,
2055        }
2056    }
2057
2058    /// The underlying state signal (tracked reads, `when(move || …)` guards, `each` sources).
2059    #[must_use]
2060    pub fn signal(self) -> Signal<Load<T>> {
2061        self.state
2062    }
2063
2064    /// The current load state (tracked).
2065    #[must_use]
2066    pub fn get(self) -> Load<T>
2067    where
2068        T: Clone,
2069    {
2070        self.state.get()
2071    }
2072
2073    /// Read the current load state by reference (tracked).
2074    pub fn with<R>(self, f: impl FnOnce(&Load<T>) -> R) -> R {
2075        self.state.with(f)
2076    }
2077
2078    /// Whether a fetch is in flight (tracked).
2079    pub fn loading(self) -> bool {
2080        self.with(Load::is_loading)
2081    }
2082
2083    /// Whether a value is ready (tracked): `when(move || r.ready(), …)`.
2084    pub fn ready(self) -> bool {
2085        self.with(Load::is_ready)
2086    }
2087
2088    /// Force a refetch with the current source value (even if unchanged).
2089    pub fn refetch(self) {
2090        self.refetch_count.update(|c| *c = c.wrapping_add(1));
2091    }
2092}
2093
2094// ---------------------------------------------------------------------------
2095// Tests
2096// ---------------------------------------------------------------------------
2097
2098#[cfg(test)]
2099mod tests {
2100    use super::*;
2101    use std::cell::Cell as StdCell;
2102    use std::rc::Rc;
2103
2104    fn counter() -> (Rc<StdCell<u32>>, impl Fn()) {
2105        let c = Rc::new(StdCell::new(0));
2106        let c2 = c.clone();
2107        (c, move || c2.set(c2.get() + 1))
2108    }
2109
2110    #[test]
2111    fn signal_get_set() {
2112        let s = Signal::new(1);
2113        assert_eq!(s.get(), 1);
2114        s.set(5);
2115        assert_eq!(s.get(), 5);
2116        s.update(|v| *v += 1);
2117        assert_eq!(s.get(), 6);
2118    }
2119
2120    #[test]
2121    fn signal_teardown_does_not_write_after_scope_disposal() {
2122        let scope = Scope::child();
2123        let warned = with_rt(|rt| rt.warned_writes.len());
2124        scope.enter(|| {
2125            let signal = Signal::new(String::new());
2126            signal.write_preview("Fixture final edit".into());
2127            assert_eq!(signal.peek(), "Fixture final edit");
2128            Scope::current().on_cleanup(move || {
2129                signal.write_teardown("Fixture final edit".into());
2130            });
2131        });
2132        scope.dispose();
2133        assert_eq!(with_rt(|rt| rt.warned_writes.len()), warned);
2134    }
2135
2136    #[test]
2137    fn persistent_binding_teardown_seals_preview() {
2138        #[derive(Clone)]
2139        struct FixtureBinding(Rc<RefCell<Vec<String>>>);
2140        impl Binding<String> for FixtureBinding {
2141            fn read(&self) -> String {
2142                String::new()
2143            }
2144            fn peek(&self) -> String {
2145                self.read()
2146            }
2147            fn write(&self, value: String) {
2148                self.0.borrow_mut().push(value);
2149            }
2150            fn write_preview(&self, _value: String) {}
2151        }
2152        let committed = Rc::new(RefCell::new(Vec::new()));
2153        let binding = FixtureBinding(committed.clone());
2154        let scope = Scope::child();
2155        scope.enter(|| {
2156            binding.write_preview("Fixture edit".into());
2157            Scope::current().on_cleanup(move || binding.write_teardown("Fixture edit".into()));
2158        });
2159        assert!(committed.borrow().is_empty());
2160        scope.dispose();
2161        assert_eq!(*committed.borrow(), ["Fixture edit"]);
2162    }
2163
2164    #[test]
2165    fn effect_reruns_on_change() {
2166        let s = Signal::new(1);
2167        let (count, bump) = counter();
2168        Effect::new(move || {
2169            s.track();
2170            bump();
2171        });
2172        assert_eq!(count.get(), 1); // initial run
2173        batch(|| s.set(2));
2174        assert_eq!(count.get(), 2);
2175        batch(|| s.set(3));
2176        assert_eq!(count.get(), 3);
2177    }
2178
2179    #[test]
2180    fn batch_coalesces() {
2181        let s = Signal::new(0);
2182        let (count, bump) = counter();
2183        Effect::new(move || {
2184            s.track();
2185            bump();
2186        });
2187        batch(|| {
2188            s.set(1);
2189            s.set(2);
2190            s.set(3);
2191        });
2192        assert_eq!(count.get(), 2); // initial + one drain
2193        assert_eq!(s.get(), 3);
2194    }
2195
2196    #[test]
2197    fn set_if_changed_no_op() {
2198        let s = Signal::new(7);
2199        let (count, bump) = counter();
2200        Effect::new(move || {
2201            s.track();
2202            bump();
2203        });
2204        batch(|| s.set_if_changed(7));
2205        assert_eq!(count.get(), 1); // no re-run
2206    }
2207
2208    #[test]
2209    fn memo_caches_and_diffs() {
2210        let s = Signal::new(1);
2211        let computes = Rc::new(StdCell::new(0));
2212        let c2 = computes.clone();
2213        let doubled = Memo::new(move || {
2214            c2.set(c2.get() + 1);
2215            s.get() * 2
2216        });
2217        assert_eq!(doubled.get(), 2);
2218        assert_eq!(doubled.get(), 2);
2219        assert_eq!(computes.get(), 1); // cached
2220        let (effect_runs, bump) = counter();
2221        Effect::new(move || {
2222            let _ = doubled.get();
2223            bump();
2224        });
2225        assert_eq!(effect_runs.get(), 1);
2226        batch(|| s.set(1)); // same value → memo recomputes? signal changed, memo recomputes, same output
2227        // memo output unchanged (1*2 == 2)? s was already 1 → set(1) marks dirty (set is not diffed)
2228        assert_eq!(effect_runs.get(), 1); // memo diffing gates the effect
2229        batch(|| s.set(5));
2230        assert_eq!(doubled.get(), 10);
2231        assert_eq!(effect_runs.get(), 2);
2232    }
2233
2234    #[test]
2235    fn bind_applies_on_change_only() {
2236        let s = Signal::new(1);
2237        let applied: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
2238        let a2 = applied.clone();
2239        bind(
2240            move || s.get().to_string(),
2241            move |v| a2.borrow_mut().push(v.clone()),
2242        );
2243        assert_eq!(*applied.borrow(), vec!["1"]);
2244        batch(|| s.set(2));
2245        assert_eq!(*applied.borrow(), vec!["1", "2"]);
2246        batch(|| s.update(|v| *v = 2)); // update always marks; bind's eq gate stops the apply
2247        assert_eq!(*applied.borrow(), vec!["1", "2"]);
2248    }
2249
2250    #[test]
2251    fn watch_skips_initial_and_passes_old() {
2252        type Log = Rc<RefCell<Vec<(i32, Option<i32>)>>>;
2253        let s = Signal::new(10);
2254        let log: Log = Rc::new(RefCell::new(Vec::new()));
2255        let l2 = log.clone();
2256        watch(
2257            move || s.get(),
2258            move |new, old| l2.borrow_mut().push((*new, old.copied())),
2259        );
2260        assert!(log.borrow().is_empty());
2261        batch(|| s.set(11));
2262        assert_eq!(*log.borrow(), vec![(11, Some(10))]);
2263    }
2264
2265    #[test]
2266    fn scope_dispose_stops_effects_and_write_is_noop() {
2267        let s = Signal::new(0);
2268        let (count, bump) = counter();
2269        let scope = Scope::child();
2270        let inner = scope.enter(|| {
2271            let inner = Signal::new(1);
2272            Effect::new(move || {
2273                s.track();
2274                bump();
2275            });
2276            inner
2277        });
2278        assert_eq!(count.get(), 1);
2279        batch(|| s.set(1));
2280        assert_eq!(count.get(), 2);
2281        scope.dispose();
2282        batch(|| s.set(2));
2283        assert_eq!(count.get(), 2); // effect gone
2284        inner.set(9); // silent no-op
2285        assert_eq!(inner.try_get(), None);
2286    }
2287
2288    #[test]
2289    fn dispose_during_drain_skips_pending() {
2290        let s = Signal::new(0);
2291        let scope = Scope::child();
2292        let (count, bump) = counter();
2293        // Owner effect (created first in outer scope) disposes the child scope when s becomes 1.
2294        let scope_cell = Rc::new(StdCell::new(Some(scope)));
2295        let sc = scope_cell.clone();
2296        Effect::new(move || {
2297            if s.get() == 1
2298                && let Some(scope) = sc.take()
2299            {
2300                scope.dispose();
2301            }
2302        });
2303        scope.enter(|| {
2304            Effect::new(move || {
2305                s.track();
2306                bump();
2307            });
2308        });
2309        assert_eq!(count.get(), 1);
2310        batch(|| s.set(1));
2311        // Owner ran first (created earlier, same depth? owner depth 0 < child depth 1) and
2312        // disposed the child → child effect must not run again.
2313        assert_eq!(count.get(), 1);
2314    }
2315
2316    #[test]
2317    fn fixpoint_extends_drain() {
2318        let a = Signal::new(0);
2319        let b = Signal::new(0);
2320        let (count, bump) = counter();
2321        Effect::new(move || {
2322            if a.get() == 1 {
2323                b.set(1); // write during drain extends the drain
2324            }
2325        });
2326        Effect::new(move || {
2327            b.track();
2328            bump();
2329        });
2330        assert_eq!(count.get(), 1);
2331        batch(|| a.set(1));
2332        assert_eq!(count.get(), 2);
2333        assert_eq!(b.get(), 1);
2334    }
2335
2336    // Debug-only: release warns-and-defers instead of panicking (the release
2337    // side is pinned by `unwind_safety_tests::rerun_cap_defers_instead_of_killing_the_binding`).
2338    #[cfg(debug_assertions)]
2339    #[test]
2340    #[should_panic(expected = "re-ran more than")]
2341    fn rerun_cap_panics_in_debug() {
2342        let s = Signal::new(0);
2343        Effect::new(move || {
2344            let v = s.get();
2345            s.set(v + 1); // classic cycle
2346        });
2347        batch(|| s.set(1));
2348    }
2349
2350    #[test]
2351    fn context_provides_down() {
2352        #[derive(Clone, PartialEq, Debug)]
2353        struct Theme(u32);
2354        let scope = Scope::child();
2355        scope.provide(Theme(7));
2356        let child = scope.create_child();
2357        assert_eq!(child.use_context::<Theme>(), Some(Theme(7)));
2358        scope.dispose();
2359    }
2360
2361    #[test]
2362    fn trigger_notifies() {
2363        let t = Trigger::new();
2364        let (count, bump) = counter();
2365        Effect::new(move || {
2366            t.track();
2367            bump();
2368        });
2369        batch(|| t.notify());
2370        assert_eq!(count.get(), 2);
2371    }
2372
2373    #[test]
2374    fn turn_end_runs_after_fixpoint() {
2375        let s = Signal::new(0);
2376        let order: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
2377        let o1 = order.clone();
2378        Effect::new(move || {
2379            s.track();
2380            o1.borrow_mut().push("effect");
2381        });
2382        let o2 = order.clone();
2383        on_turn_end(move || o2.borrow_mut().push("turn-end"));
2384        order.borrow_mut().clear();
2385        batch(|| s.set(1));
2386        assert_eq!(*order.borrow(), vec!["effect", "turn-end"]);
2387    }
2388
2389    #[test]
2390    fn at_turn_end_waits_for_the_turn_and_runs_once() {
2391        let s = Signal::new(0);
2392        let order: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
2393        // Outside a turn: now.
2394        let o = order.clone();
2395        at_turn_end(move || o.borrow_mut().push("now".into()));
2396        assert_eq!(*order.borrow(), vec!["now".to_string()]);
2397        order.borrow_mut().clear();
2398        // Inside a batch: after the drain, and before the standing hooks.
2399        let o1 = order.clone();
2400        Effect::new(move || {
2401            let v = s.get();
2402            o1.borrow_mut().push(format!("effect {v}"));
2403        });
2404        let o2 = order.clone();
2405        on_turn_end(move || o2.borrow_mut().push("standing".into()));
2406        order.borrow_mut().clear();
2407        let o3 = order.clone();
2408        batch(|| {
2409            at_turn_end(move || o3.borrow_mut().push("once".into()));
2410            s.set(1);
2411        });
2412        assert_eq!(*order.borrow(), vec!["effect 1", "once", "standing"]);
2413        // A batch with no reactive work still ends its turn for a deferred callback.
2414        order.borrow_mut().clear();
2415        let o4 = order.clone();
2416        batch(|| at_turn_end(move || o4.borrow_mut().push("quiet".into())));
2417        assert_eq!(*order.borrow(), vec!["quiet", "standing"]);
2418    }
2419
2420    #[test]
2421    fn bindings_run_before_effects() {
2422        let s = Signal::new(0);
2423        let order: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
2424        let o1 = order.clone();
2425        // Plain effect created first (lower seq); priority must still put the bind first.
2426        Effect::new(move || {
2427            s.track();
2428            o1.borrow_mut().push("effect");
2429        });
2430        let o2 = order.clone();
2431        bind(move || s.get(), move |_| o2.borrow_mut().push("bind"));
2432        order.borrow_mut().clear();
2433        batch(|| s.set(1));
2434        assert_eq!(*order.borrow(), vec!["bind", "effect"]);
2435    }
2436}
2437
2438#[cfg(test)]
2439mod resource_tests {
2440    use super::*;
2441    use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
2442
2443    // ---- test executor: mirrors day::task's shape (eager first poll; abort = remove+drop;
2444    // pump() re-polls whatever is still pending). `ABORTED` records aborts of still-pending
2445    // tasks, the probe the latest-wins/disposal tests read. All thread-local: each #[test]
2446    // thread gets a fresh Runtime and a fresh executor.
2447
2448    thread_local! {
2449        static TEST_TASKS: RefCell<Vec<(u64, Option<LocalBoxFuture>)>> =
2450            const { RefCell::new(Vec::new()) };
2451        static NEXT_ID: Cell<u64> = const { Cell::new(1) };
2452        static ABORTED: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
2453        static INSTALLED: Cell<bool> = const { Cell::new(false) };
2454    }
2455
2456    fn noop_waker() -> Waker {
2457        fn raw() -> RawWaker {
2458            RawWaker::new(std::ptr::null(), &VT)
2459        }
2460        static VT: RawWakerVTable = RawWakerVTable::new(|_| raw(), |_| {}, |_| {}, |_| {});
2461        // SAFETY: every vtable entry ignores the data pointer.
2462        unsafe { Waker::from_raw(raw()) }
2463    }
2464
2465    fn poll_one(fut: &mut LocalBoxFuture) -> bool {
2466        let waker = noop_waker();
2467        let mut cx = Context::from_waker(&waker);
2468        fut.as_mut().poll(&mut cx).is_ready()
2469    }
2470
2471    fn install_test_spawner() {
2472        if INSTALLED.with(|c| c.replace(true)) {
2473            return;
2474        }
2475        install_spawner(|mut fut| {
2476            let id = NEXT_ID.with(|c| {
2477                let v = c.get();
2478                c.set(v + 1);
2479                v
2480            });
2481            if !poll_one(&mut fut) {
2482                TEST_TASKS.with(|t| t.borrow_mut().push((id, Some(fut))));
2483            }
2484            Box::new(move || {
2485                let removed = TEST_TASKS.with(|t| {
2486                    let mut t = t.borrow_mut();
2487                    let before = t.len();
2488                    t.retain(|(i, _)| *i != id);
2489                    before != t.len()
2490                });
2491                if removed {
2492                    ABORTED.with(|a| a.borrow_mut().push(id));
2493                }
2494            })
2495        });
2496    }
2497
2498    fn aborted_count() -> usize {
2499        ABORTED.with(|a| a.borrow().len())
2500    }
2501
2502    /// Re-poll every pending task once (completions drop out).
2503    fn pump() {
2504        let ids: Vec<u64> = TEST_TASKS.with(|t| t.borrow().iter().map(|(i, _)| *i).collect());
2505        for id in ids {
2506            let fut = TEST_TASKS.with(|t| {
2507                t.borrow_mut()
2508                    .iter_mut()
2509                    .find(|(i, _)| *i == id)
2510                    .and_then(|(_, s)| s.take())
2511            });
2512            let Some(mut fut) = fut else { continue };
2513            if poll_one(&mut fut) {
2514                TEST_TASKS.with(|t| t.borrow_mut().retain(|(i, _)| *i != id));
2515            } else {
2516                TEST_TASKS.with(|t| {
2517                    if let Some((_, s)) = t.borrow_mut().iter_mut().find(|(i, _)| *i == id) {
2518                        *s = Some(fut);
2519                    }
2520                });
2521            }
2522        }
2523        // Completions wrote signals; with no scheduler installed a test must drain explicitly
2524        // (the production main loop drains via the installed scheduler).
2525        flush_sync();
2526    }
2527
2528    type Slot<T> = Rc<RefCell<Option<Result<T, TestErr>>>>;
2529
2530    /// A future the test resolves by hand (fill the slot, then `pump()`); no waker wiring, since
2531    /// pump re-polls everything.
2532    fn manual_future<T: 'static>(slot: Slot<T>) -> impl Future<Output = Result<T, TestErr>> {
2533        std::future::poll_fn(move |_| match slot.borrow_mut().take() {
2534            Some(r) => Poll::Ready(r),
2535            None => Poll::Pending,
2536        })
2537    }
2538
2539    #[derive(Debug)]
2540    struct TestErr(&'static str);
2541    impl std::fmt::Display for TestErr {
2542        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2543            write!(f, "{}", self.0)
2544        }
2545    }
2546    impl std::error::Error for TestErr {}
2547
2548    #[test]
2549    fn resource_sync_fetcher_is_ready_immediately() {
2550        install_test_spawner();
2551        let r = Resource::new(|| (), |()| async { Ok::<_, std::convert::Infallible>(42) });
2552        assert!(r.ready());
2553        assert_eq!(r.with(|l| l.ready().copied()), Some(42));
2554    }
2555
2556    #[test]
2557    fn resource_loading_then_ready() {
2558        install_test_spawner();
2559        let slot: Slot<i32> = Rc::new(RefCell::new(None));
2560        let s2 = slot.clone();
2561        let r = Resource::new(move || (), move |()| manual_future(s2.clone()));
2562        assert!(r.loading());
2563        *slot.borrow_mut() = Some(Ok(7));
2564        pump();
2565        assert_eq!(r.with(|l| l.ready().copied()), Some(7));
2566    }
2567
2568    #[test]
2569    fn resource_failed_preserves_error() {
2570        install_test_spawner();
2571        let r = Resource::new(|| (), |()| async { Err::<i32, _>(TestErr("boom")) });
2572        assert!(!r.ready());
2573        assert_eq!(
2574            r.with(|l| l.error().map(std::string::ToString::to_string)),
2575            Some("boom".into())
2576        );
2577    }
2578
2579    #[test]
2580    fn resource_refetches_on_source_change() {
2581        install_test_spawner();
2582        let src = Signal::new(1i32);
2583        let fetches = Rc::new(Cell::new(0));
2584        let f = fetches.clone();
2585        let r = Resource::new(
2586            move || src.get(),
2587            move |v| {
2588                f.set(f.get() + 1);
2589                async move { Ok::<_, TestErr>(v * 10) }
2590            },
2591        );
2592        assert_eq!(fetches.get(), 1);
2593        assert_eq!(r.with(|l| l.ready().copied()), Some(10));
2594        batch(|| src.set(2));
2595        assert_eq!(fetches.get(), 2);
2596        assert_eq!(r.with(|l| l.ready().copied()), Some(20));
2597    }
2598
2599    #[test]
2600    fn resource_source_equality_gates() {
2601        install_test_spawner();
2602        let a = Signal::new(1i32);
2603        let b = Signal::new(10i32);
2604        let fetches = Rc::new(Cell::new(0));
2605        let f = fetches.clone();
2606        let r = Resource::new(
2607            move || {
2608                let _ = b.get(); // tracked but not part of the source value
2609                a.get()
2610            },
2611            move |v| {
2612                f.set(f.get() + 1);
2613                async move { Ok::<_, TestErr>(v) }
2614            },
2615        );
2616        assert_eq!(fetches.get(), 1);
2617        batch(|| b.set(20)); // reruns the reaction; the source value is unchanged → no refetch
2618        assert_eq!(fetches.get(), 1);
2619        assert_eq!(r.with(|l| l.ready().copied()), Some(1));
2620        batch(|| a.set(2)); // the value changed → refetch
2621        assert_eq!(fetches.get(), 2);
2622    }
2623
2624    #[test]
2625    fn resource_refetch_forces() {
2626        install_test_spawner();
2627        let fetches = Rc::new(Cell::new(0));
2628        let f = fetches.clone();
2629        let r = Resource::new(
2630            || (),
2631            move |()| {
2632                f.set(f.get() + 1);
2633                async { Ok::<_, TestErr>(0) }
2634            },
2635        );
2636        assert_eq!(fetches.get(), 1);
2637        batch(|| r.refetch()); // same source value; the refetch counter forces it past the gate
2638        assert_eq!(fetches.get(), 2);
2639    }
2640
2641    #[test]
2642    fn resource_latest_wins() {
2643        install_test_spawner();
2644        let src = Signal::new(1i32);
2645        let slots: Rc<RefCell<Vec<Slot<i32>>>> = Rc::new(RefCell::new(Vec::new()));
2646        let sl = slots.clone();
2647        let r = Resource::new(
2648            move || src.get(),
2649            move |_| {
2650                let slot: Slot<i32> = Rc::new(RefCell::new(None));
2651                sl.borrow_mut().push(slot.clone());
2652                manual_future(slot)
2653            },
2654        );
2655        assert!(r.loading());
2656        let before = aborted_count();
2657        batch(|| src.set(2)); // supersede generation 1 while it is in flight
2658        assert_eq!(aborted_count(), before + 1, "the stale task was aborted");
2659        // Resolving generation 1 anyway must change nothing (its future is gone).
2660        *slots.borrow()[0].borrow_mut() = Some(Ok(111));
2661        pump();
2662        assert!(r.loading(), "a stale result writes nothing");
2663        *slots.borrow()[1].borrow_mut() = Some(Ok(222));
2664        pump();
2665        assert_eq!(r.with(|l| l.ready().copied()), Some(222));
2666    }
2667
2668    #[test]
2669    fn resource_scope_disposal_aborts() {
2670        install_test_spawner();
2671        let scope = Scope::child();
2672        let slot: Slot<i32> = Rc::new(RefCell::new(None));
2673        let s2 = slot.clone();
2674        let r = scope.enter(|| Resource::new(move || (), move |()| manual_future(s2.clone())));
2675        assert!(r.loading());
2676        let before = aborted_count();
2677        scope.dispose();
2678        assert_eq!(aborted_count(), before + 1, "disposal aborted the fetch");
2679        // Resolving afterwards is inert: the future is gone; nothing pends; no panic.
2680        *slot.borrow_mut() = Some(Ok(1));
2681        pump();
2682    }
2683
2684    #[test]
2685    fn resource_ready_is_tracked() {
2686        install_test_spawner();
2687        let slot: Slot<i32> = Rc::new(RefCell::new(None));
2688        let s2 = slot.clone();
2689        let r = Resource::new(move || (), move |()| manual_future(s2.clone()));
2690        let runs = Rc::new(Cell::new(0));
2691        let rn = runs.clone();
2692        Effect::new(move || {
2693            let _ = r.ready();
2694            rn.set(rn.get() + 1);
2695        });
2696        assert_eq!(runs.get(), 1);
2697        *slot.borrow_mut() = Some(Ok(1));
2698        pump();
2699        assert!(runs.get() >= 2, "ready() re-ran the effect on completion");
2700    }
2701
2702    #[test]
2703    #[should_panic(expected = "no spawner installed")]
2704    fn spawner_missing_panics() {
2705        // No test spawner installed: this test thread's Runtime has none.
2706        let _r = Resource::new(|| (), |()| async { Ok::<_, std::convert::Infallible>(1) });
2707    }
2708}
2709
2710#[cfg(test)]
2711mod unwind_safety_tests {
2712    use super::*;
2713
2714    /// Run `f`, swallowing a panic, with the panic hook silenced so the test output stays clean.
2715    fn contained(f: impl FnOnce() + std::panic::UnwindSafe) {
2716        let prev = std::panic::take_hook();
2717        std::panic::set_hook(Box::new(|_| {}));
2718        let r = std::panic::catch_unwind(f);
2719        std::panic::set_hook(prev);
2720        assert!(r.is_err(), "expected the closure to panic");
2721    }
2722
2723    /// A panic inside `Scope::enter` must not leave the runtime parented to the transient scope.
2724    /// Before the guard, every later `Signal::new` landed in a disposed scope and its first read
2725    /// panicked with a misleading "read of disposed Signal".
2726    #[test]
2727    fn panic_in_scope_enter_restores_current_scope() {
2728        let before = with_rt(|rt| rt.current_scope);
2729        let scope = Scope::detached();
2730        contained(|| scope.enter(|| panic!("boom in enter")));
2731        assert_eq!(with_rt(|rt| rt.current_scope), before, "scope not restored");
2732        // The real symptom: a signal created afterwards must still be alive and readable.
2733        let s = Signal::new(7u32);
2734        assert_eq!(s.get(), 7);
2735    }
2736
2737    /// A panic inside `untrack` must pop its `None` observer, or dependency tracking stays off
2738    /// for the rest of the process and nothing ever updates again.
2739    /// A panic inside an effect's own closure (contained by a backend trampoline) must pop
2740    /// the effect's observer frame during unwind; a stranded frame would attribute every
2741    /// later read to the dead run, even through a user's own `catch_unwind`, without any
2742    /// call to `recover_from_panic`.
2743    #[test]
2744    fn panic_in_effect_body_pops_its_observer_frame() {
2745        let depth = with_rt(|rt| rt.observers.len());
2746        let boom = Signal::new(false);
2747        Effect::new(move || {
2748            assert!(!boom.get(), "effect boom");
2749        });
2750        assert_eq!(with_rt(|rt| rt.observers.len()), depth);
2751        contained(|| batch(|| boom.set(true)));
2752        assert_eq!(
2753            with_rt(|rt| rt.observers.len()),
2754            depth,
2755            "observer frame stranded by the panicking effect run"
2756        );
2757        recover_from_panic(); // clear draining/pending for the tests that follow
2758    }
2759
2760    #[test]
2761    fn panic_in_untrack_restores_tracking() {
2762        let depth = with_rt(|rt| rt.observers.len());
2763        contained(|| untrack(|| panic!("boom in untrack")));
2764        assert_eq!(with_rt(|rt| rt.observers.len()), depth, "observer stranded");
2765
2766        // Tracking still works: an effect re-runs when its source changes.
2767        let src = Signal::new(0i32);
2768        let runs = Rc::new(RefCell::new(0));
2769        let r2 = runs.clone();
2770        Effect::new(move || {
2771            let _ = src.get();
2772            *r2.borrow_mut() += 1;
2773        });
2774        flush_sync();
2775        let before = *runs.borrow();
2776        src.set(1);
2777        flush_sync();
2778        assert!(
2779            *runs.borrow() > before,
2780            "effect did not re-run — tracking is off"
2781        );
2782    }
2783
2784    /// A panic inside `batch` must not strand `batch_depth`, which would stop every later write
2785    /// from scheduling a drain.
2786    #[test]
2787    fn panic_in_batch_restores_depth() {
2788        let depth = with_rt(|rt| rt.batch_depth);
2789        contained(|| batch(|| panic!("boom in batch")));
2790        assert_eq!(with_rt(|rt| rt.batch_depth), depth, "batch depth stranded");
2791    }
2792
2793    /// A panic inside a `with` closure must not consume the signal's value. Before the value was
2794    /// shared it was taken out for the closure's duration, so an unwind lost it permanently and
2795    /// the signal was dead for the rest of the process.
2796    #[test]
2797    fn panic_in_with_leaves_the_value_intact() {
2798        let s = Signal::new(String::from("intact"));
2799        contained(|| s.with(|_| panic!("boom in with")));
2800        assert_eq!(s.with(std::clone::Clone::clone), "intact");
2801    }
2802
2803    /// Reading a signal from inside its own `with` closure now works. It used to find the hole
2804    /// left by the take and panic with "read of disposed Signal".
2805    #[test]
2806    fn reentrant_read_inside_with_succeeds() {
2807        let s = Signal::new(5u32);
2808        let doubled = s.with(|outer| *outer + s.with(|inner| *inner));
2809        assert_eq!(doubled, 10);
2810        assert_eq!(
2811            s.with(|v| *v),
2812            5,
2813            "value still in place after the nested read"
2814        );
2815    }
2816
2817    /// Two different signals read inside one another's closures: the ordinary case, and the
2818    /// reason the closure must run with the runtime borrow released.
2819    #[test]
2820    fn nested_reads_of_distinct_signals_succeed() {
2821        let a = Signal::new(2u32);
2822        let b = Signal::new(3u32);
2823        assert_eq!(a.with(|x| *x * b.with(|y| *y)), 6);
2824    }
2825
2826    /// Writing a signal while a read of it is in flight is reported instead of silently lost.
2827    #[test]
2828    fn write_during_read_panics_with_a_clear_message() {
2829        let s = Signal::new(1u32);
2830        let prev = std::panic::take_hook();
2831        std::panic::set_hook(Box::new(|_| {}));
2832        let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2833            s.with(|_| s.set(2));
2834        }));
2835        std::panic::set_hook(prev);
2836        let payload = r.unwrap_err();
2837        // A `panic!` with no format arguments carries a `&'static str`, not a `String`.
2838        let msg = payload
2839            .downcast_ref::<&str>()
2840            .map(std::string::ToString::to_string)
2841            .or_else(|| payload.downcast_ref::<String>().cloned())
2842            .expect("panic payload should be a string");
2843        assert!(
2844            msg.contains("in flight") && msg.contains("Signal"),
2845            "message should name the cause, got: {msg}"
2846        );
2847    }
2848
2849    /// Release builds must survive a reactive cycle: the capped effect is skipped for the
2850    /// rest of the drain but re-arms on the next source write; it must not be permanently
2851    /// disabled. Release-only because the same cycle panics under
2852    /// `debug_assertions`; run via `cargo test --release -p day-reactive`.
2853    #[cfg(not(debug_assertions))]
2854    #[test]
2855    fn rerun_cap_defers_instead_of_killing_the_binding() {
2856        let s = Signal::new(0u32);
2857        let runs = std::rc::Rc::new(std::cell::Cell::new(0u32));
2858        let r2 = runs.clone();
2859        Effect::new(move || {
2860            let v = s.get();
2861            r2.set(r2.get() + 1);
2862            if v < 1_000_000 {
2863                s.set(v + 1); // self-sustaining cycle: trips the cap every drain
2864            }
2865        });
2866        flush_sync();
2867        let after_cycle = runs.get();
2868        assert!(
2869            after_cycle <= RERUN_CAP + 1,
2870            "cap did not bound the drain: {after_cycle} runs"
2871        );
2872
2873        // A fresh external write must re-arm the effect with a new per-drain budget.
2874        batch(|| s.set(2_000_000)); // past the cycle threshold: the effect runs once, quietly
2875        assert_eq!(
2876            runs.get(),
2877            after_cycle + 1,
2878            "binding stayed dead after hitting the re-run cap"
2879        );
2880    }
2881}
2882
2883#[cfg(test)]
2884mod owner_scope_tests {
2885    use super::*;
2886
2887    #[test]
2888    fn reactions_and_lazy_memos_keep_their_owner_and_restore_the_caller() {
2889        let outer = Scope::child();
2890        outer.provide("outer fixture");
2891        let first = outer.create_child();
2892        let second = outer.create_child();
2893        first.provide("first fixture");
2894        second.provide("second fixture");
2895        let source = Signal::new(0);
2896        let seen = Rc::new(RefCell::new(Vec::new()));
2897        let lazy = first.enter(|| {
2898            Memo::new(move || {
2899                (
2900                    source.get(),
2901                    Scope::current().use_context::<&str>().unwrap(),
2902                )
2903            })
2904        });
2905        let nested = second.enter(|| {
2906            Memo::new(move || (lazy.get(), Scope::current().use_context::<&str>().unwrap()))
2907        });
2908        second.enter(|| assert_eq!(lazy.get(), (0, "first fixture")));
2909        assert_eq!(nested.get(), ((0, "first fixture"), "second fixture"));
2910        for (scope, name) in [(first, "first fixture"), (second, "second fixture")] {
2911            let seen = seen.clone();
2912            scope.enter(|| {
2913                Effect::new(move || {
2914                    seen.borrow_mut()
2915                        .push((source.get(), Scope::current().use_context::<&str>()));
2916                    assert_eq!(Scope::current().use_context::<&str>(), Some(name));
2917                });
2918            });
2919        }
2920        second.enter(|| {
2921            batch(|| source.set(1));
2922            assert_eq!(
2923                Scope::current().use_context::<&str>(),
2924                Some("second fixture")
2925            );
2926        });
2927        assert_eq!(nested.get(), ((1, "first fixture"), "second fixture"));
2928        assert_eq!(seen.borrow().len(), 4);
2929        outer.dispose();
2930        batch(|| source.set(2));
2931        assert_eq!(seen.borrow().len(), 4, "disposed reactions must not run");
2932    }
2933
2934    #[test]
2935    fn watches_allocate_state_and_cleanup_in_their_owner() {
2936        let owner = Scope::child();
2937        let trigger = Signal::new(0);
2938        let allocated = Rc::new(Cell::new(None::<Signal<i32>>));
2939        let cleaned = Rc::new(Cell::new(0));
2940        owner.enter(|| {
2941            let allocated = allocated.clone();
2942            let cleaned = cleaned.clone();
2943            watch(
2944                move || trigger.get(),
2945                move |value, _| {
2946                    allocated.set(Some(Signal::new(*value)));
2947                    let cleaned = cleaned.clone();
2948                    Scope::current().on_cleanup(move || cleaned.set(cleaned.get() + 1));
2949                },
2950            );
2951        });
2952        batch(|| trigger.set(1));
2953        let state = allocated.get().unwrap();
2954        assert_eq!(state.get(), 1);
2955        owner.dispose();
2956        assert_eq!(cleaned.get(), 1);
2957        assert!(state.try_get().is_none());
2958    }
2959
2960    #[test]
2961    fn panic_in_owned_computations_restores_scope_and_tracking() {
2962        let owner = Scope::child();
2963        owner.provide("owner fixture");
2964        let caller = Scope::child();
2965        caller.provide("caller fixture");
2966        let trigger = Signal::new(false);
2967        let memo = owner.enter(|| {
2968            Memo::new(move || {
2969                assert_eq!(
2970                    Scope::current().use_context::<&str>(),
2971                    Some("owner fixture")
2972                );
2973                assert!(!trigger.get(), "synthetic memo failure");
2974                7
2975            })
2976        });
2977        assert_eq!(memo.get(), 7);
2978        batch(|| trigger.set(true));
2979        caller.enter(|| {
2980            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| memo.get()));
2981            assert!(result.is_err());
2982            assert_eq!(
2983                Scope::current().use_context::<&str>(),
2984                Some("caller fixture")
2985            );
2986            assert!(with_rt(|rt| rt.observers.is_empty()));
2987        });
2988        owner.dispose();
2989        caller.dispose();
2990    }
2991}