Skip to main content

yse_model/
lib.rs

1//! `yse-model` is the pure-Rust reactive runtime at the core of Yse.
2//!
3//! The design is inspired by [Airstream](https://github.com/raquo/Airstream):
4//!
5//! - [`EventStream`] has no current value; it carries discrete events.
6//! - [`Signal`] always has a current value; it carries state.
7//! - Propagation is transactional and glitch-free: inside one transaction,
8//!   derived values are recomputed in topological order, so a diamond-shaped
9//!   graph never observes inconsistent intermediate state.
10//! - Every observation is owned by a [`Subscription`]; dropping it (directly
11//!   or through an [`Owner`]) unsubscribes.
12//!
13//! The crate is pure Rust: no Qt and no `unsafe`. The reactive graph itself is
14//! single-threaded; background work must return to it through a [`Scheduler`]
15//! (see [`spawn_task`]).
16
17#![forbid(unsafe_code)]
18#![warn(missing_docs)]
19// The typed operator nodes store nested closure types (e.g.
20// `RefCell<Box<dyn FnMut(&A, &B) -> R>>`) by design; the complexity is
21// inherent to the API, not accidental.
22#![allow(clippy::type_complexity)]
23
24mod diagnostics;
25mod graph;
26mod list;
27mod nodes;
28mod timing;
29mod undo;
30
31#[cfg(test)]
32mod tests {
33    use super::*;
34
35    #[test]
36    fn var_default_matches_new_of_default() {
37        let a = Var::<Vec<u32>>::default();
38        let b = Var::new(Vec::<u32>::new());
39        assert_eq!(*a.value(), *b.value());
40
41        let flag = Var::<bool>::default();
42        assert!(!*flag.value());
43    }
44}
45
46pub use diagnostics::{DiagnosticEvent, Diagnostics, LogLevel, LogRecord, Logger};
47pub use diagnostics::{log, log_debug, log_error, log_info, log_warn};
48use graph::{Node, connect, resync_signal_ancestors, write_node};
49pub use graph::{Subscription, transaction};
50pub use list::{ListChange, ListModel};
51use nodes::{
52    ChangesNode, Combine3Node, Combine4Node, CombineNode, DistinctSignalNode, DistinctStreamNode,
53    FilterMapStreamNode, FilterStreamNode, FlatMapSwitchNode, FoldStreamNode, MapSignalNode,
54    MapStreamNode, MergeStreamNode, ObserverNode, SampleStreamNode, SignalSourceNode,
55    StartWithNode, StreamSourceNode,
56};
57use std::any::Any;
58use std::cell::RefCell;
59use std::collections::HashMap;
60use std::rc::Rc;
61use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
62use std::sync::{Arc, Mutex};
63use std::thread::JoinHandle;
64use std::time::{Duration, Instant};
65pub use timing::{ManualTimer, Timer};
66pub use undo::{Command, UndoStack};
67
68/// Executes deferred work. Yse's reactive graph is synchronous and
69/// single-threaded; this trait is the boundary where background work returns
70/// to the UI thread. A scheduler must run scheduled tasks on the thread that
71/// owns the reactive graph (the UI thread in a Qt application).
72pub trait Scheduler {
73    /// Schedule `task` for execution.
74    fn schedule(&self, task: Box<dyn FnOnce() + Send>);
75
76    /// Schedule a closure, boxing it for you.
77    fn schedule_fn<F>(&self, f: F)
78    where
79        Self: Sized,
80        F: FnOnce() + Send + 'static,
81    {
82        self.schedule(Box::new(f));
83    }
84}
85
86/// A scheduler that runs tasks immediately on the current thread.
87///
88/// This is only useful when scheduling happens on the graph's own thread; a
89/// background worker must use a queue- or GUI-thread-based scheduler instead.
90pub struct SyncScheduler;
91
92impl Scheduler for SyncScheduler {
93    fn schedule(&self, task: Box<dyn FnOnce() + Send>) {
94        task();
95    }
96}
97
98/// A scheduler that queues tasks and runs them on demand on the calling
99/// thread. Useful for deterministic tests and for wiring background results
100/// into the reactive graph.
101pub struct QueueScheduler {
102    queue: Mutex<Vec<Box<dyn FnOnce() + Send>>>,
103}
104
105impl QueueScheduler {
106    /// Create an empty scheduler.
107    pub fn new() -> Self {
108        Self {
109            queue: Mutex::new(Vec::new()),
110        }
111    }
112
113    /// Number of tasks waiting to run.
114    pub fn pending(&self) -> usize {
115        self.queue.lock().unwrap().len()
116    }
117
118    /// Run every queued task on the calling thread, in FIFO order.
119    pub fn drain(&self) {
120        let tasks = std::mem::take(&mut *self.queue.lock().unwrap());
121        for task in tasks {
122            task();
123        }
124    }
125}
126
127impl Default for QueueScheduler {
128    fn default() -> Self {
129        Self::new()
130    }
131}
132
133impl Scheduler for QueueScheduler {
134    fn schedule(&self, task: Box<dyn FnOnce() + Send>) {
135        self.queue.lock().unwrap().push(task);
136    }
137}
138
139/// A writable source of signal state.
140pub struct Var<T> {
141    node: Rc<SignalSourceNode<T>>,
142}
143
144impl<T> Clone for Var<T> {
145    fn clone(&self) -> Self {
146        Self {
147            node: self.node.clone(),
148        }
149    }
150}
151
152impl<T: Default + 'static + PartialEq> Default for Var<T> {
153    fn default() -> Self {
154        Self::new(T::default())
155    }
156}
157
158impl<T> Var<T>
159where
160    T: 'static + PartialEq,
161{
162    /// Create a new `Var` holding `value`.
163    pub fn new(value: T) -> Self {
164        Self {
165            node: Rc::new(SignalSourceNode::new(value)),
166        }
167    }
168
169    /// Write `value`, propagating through the graph inside a transaction.
170    pub fn set(&self, value: T) {
171        let node: Rc<dyn Node> = self.node.clone();
172        write_node(node, Rc::new(value));
173    }
174
175    /// The current value.
176    pub fn value(&self) -> Rc<T> {
177        self.node.value.borrow().clone()
178    }
179
180    /// This `Var` as a [`Signal`].
181    pub fn signal(&self) -> Signal<T> {
182        Signal::new(self.node.clone())
183    }
184}
185
186/// A read-only signal with a current value.
187pub struct Signal<T> {
188    node: Rc<dyn Node>,
189    _marker: std::marker::PhantomData<T>,
190}
191
192impl<T: 'static> Clone for Signal<T> {
193    fn clone(&self) -> Self {
194        Self::new(self.node.clone())
195    }
196}
197
198impl<T> Signal<T>
199where
200    T: 'static,
201{
202    fn new(node: Rc<dyn Node>) -> Self {
203        Self {
204            node,
205            _marker: std::marker::PhantomData,
206        }
207    }
208
209    /// The current value.
210    pub fn value(&self) -> Rc<T> {
211        self.node
212            .current_any()
213            .expect("signal has a value")
214            .downcast::<T>()
215            .expect("signal type mismatch")
216    }
217
218    /// Number of observers currently attached to this signal. Useful for
219    /// lifecycle tests: dropping the owning component must return this to
220    /// zero.
221    pub fn observer_count(&self) -> usize {
222        self.node
223            .dependents()
224            .iter()
225            .filter(|dependent| dependent.is_observer())
226            .count()
227    }
228
229    /// Observe this signal. The callback fires immediately with the current
230    /// value and then on every change, in topological order.
231    pub fn observe<F>(&self, f: F) -> Subscription
232    where
233        F: FnMut(&T) + 'static,
234    {
235        let callback: Rc<RefCell<dyn FnMut(&T)>> = Rc::new(RefCell::new(f));
236        self.observe_callback(callback)
237    }
238
239    /// Observe this signal with a shared [`Observer`].
240    pub fn observe_with(&self, observer: &Observer<T>) -> Subscription {
241        self.observe_callback(observer.callback.clone())
242    }
243
244    fn observe_callback(&self, callback: Rc<RefCell<dyn FnMut(&T)>>) -> Subscription {
245        let node =
246            Rc::new_cyclic(|weak| ObserverNode::new(self.node.clone(), callback, weak.clone()));
247        let node_any: Rc<dyn Node> = node.clone();
248        connect(self.node.clone(), node_any.clone());
249        if let Some(value) = self.node.current_any() {
250            node.fire(value);
251        }
252        Subscription { node: node_any }
253    }
254
255    /// Map this signal's value.
256    pub fn map<U, F>(&self, f: F) -> Signal<U>
257    where
258        U: 'static + PartialEq,
259        F: FnMut(&T) -> U + 'static,
260    {
261        let node = Rc::new(MapSignalNode::<T, U>::new(self.node.clone(), Box::new(f)));
262        let node_any: Rc<dyn Node> = node.clone();
263        connect(self.node.clone(), node_any.clone());
264        node.recompute();
265        Signal::new(node_any)
266    }
267
268    /// Only propagate when the value actually changes.
269    pub fn distinct(&self) -> Signal<T>
270    where
271        T: PartialEq,
272    {
273        let node = Rc::new(DistinctSignalNode::<T>::new(self.node.clone()));
274        let node_any: Rc<dyn Node> = node.clone();
275        connect(self.node.clone(), node_any.clone());
276        node.recompute();
277        Signal::new(node_any)
278    }
279
280    /// Combine two signals. Recomputes only after every input has settled.
281    pub fn combine<U, R, F>(&self, other: &Signal<U>, f: F) -> Signal<R>
282    where
283        U: 'static,
284        R: 'static + PartialEq,
285        F: FnMut(&T, &U) -> R + 'static,
286    {
287        let node = Rc::new(CombineNode::<T, U, R>::new(
288            self.node.clone(),
289            other.node.clone(),
290            Box::new(f),
291        ));
292        let node_any: Rc<dyn Node> = node.clone();
293        connect(self.node.clone(), node_any.clone());
294        connect(other.node.clone(), node_any.clone());
295        node.recompute();
296        Signal::new(node_any)
297    }
298
299    /// Combine three signals.
300    pub fn combine3<U, V, R, F>(&self, b: &Signal<U>, c: &Signal<V>, f: F) -> Signal<R>
301    where
302        U: 'static,
303        V: 'static,
304        R: 'static + PartialEq,
305        F: FnMut(&T, &U, &V) -> R + 'static,
306    {
307        let node = Rc::new(Combine3Node::<T, U, V, R>::new(
308            self.node.clone(),
309            b.node.clone(),
310            c.node.clone(),
311            Box::new(f),
312        ));
313        let node_any: Rc<dyn Node> = node.clone();
314        connect(self.node.clone(), node_any.clone());
315        connect(b.node.clone(), node_any.clone());
316        connect(c.node.clone(), node_any.clone());
317        node.recompute();
318        Signal::new(node_any)
319    }
320
321    /// Combine four signals.
322    pub fn combine4<U, V, W, R, F>(
323        &self,
324        b: &Signal<U>,
325        c: &Signal<V>,
326        d: &Signal<W>,
327        f: F,
328    ) -> Signal<R>
329    where
330        U: 'static,
331        V: 'static,
332        W: 'static,
333        R: 'static + PartialEq,
334        F: FnMut(&T, &U, &V, &W) -> R + 'static,
335    {
336        let node = Rc::new(Combine4Node::<T, U, V, W, R>::new(
337            self.node.clone(),
338            b.node.clone(),
339            c.node.clone(),
340            d.node.clone(),
341            Box::new(f),
342        ));
343        let node_any: Rc<dyn Node> = node.clone();
344        connect(self.node.clone(), node_any.clone());
345        connect(b.node.clone(), node_any.clone());
346        connect(c.node.clone(), node_any.clone());
347        connect(d.node.clone(), node_any.clone());
348        node.recompute();
349        Signal::new(node_any)
350    }
351
352    /// A stream of change events: emits this signal's new value whenever it
353    /// changes. Restarting an observation re-synchronises with the current
354    /// value.
355    pub fn changes(&self) -> EventStream<T> {
356        let node = Rc::new(ChangesNode::<T>::new(self.node.clone()));
357        let node_any: Rc<dyn Node> = node.clone();
358        connect(self.node.clone(), node_any.clone());
359        EventStream::new(node_any)
360    }
361}
362
363/// A writable source of stream events.
364pub struct Sink<T> {
365    node: Rc<StreamSourceNode<T>>,
366}
367
368impl<T> Clone for Sink<T> {
369    fn clone(&self) -> Self {
370        Self {
371            node: self.node.clone(),
372        }
373    }
374}
375
376impl<T> Sink<T>
377where
378    T: 'static,
379{
380    /// Create a new `Sink`.
381    pub fn new() -> Self {
382        Self {
383            node: Rc::new(StreamSourceNode::new()),
384        }
385    }
386
387    /// Emit `value` to every current observer, inside a transaction.
388    pub fn send(&self, value: T) {
389        let node: Rc<dyn Node> = self.node.clone();
390        write_node(node, Rc::new(value));
391    }
392
393    /// This `Sink` as an [`EventStream`].
394    pub fn stream(&self) -> EventStream<T> {
395        EventStream::new(self.node.clone())
396    }
397}
398
399impl<T> Default for Sink<T>
400where
401    T: 'static,
402{
403    fn default() -> Self {
404        Self::new()
405    }
406}
407
408/// A stream of discrete events. It has no current value.
409pub struct EventStream<T> {
410    node: Rc<dyn Node>,
411    _marker: std::marker::PhantomData<T>,
412}
413
414impl<T: 'static> Clone for EventStream<T> {
415    fn clone(&self) -> Self {
416        Self::new(self.node.clone())
417    }
418}
419
420impl<T> EventStream<T>
421where
422    T: 'static,
423{
424    fn new(node: Rc<dyn Node>) -> Self {
425        Self {
426            node,
427            _marker: std::marker::PhantomData,
428        }
429    }
430
431    /// Observe this stream. The callback fires for every event while the
432    /// returned [`Subscription`] is alive. Streams are started by their first
433    /// observer and stopped when the last observer is removed.
434    pub fn observe<F>(&self, f: F) -> Subscription
435    where
436        F: FnMut(&T) + 'static,
437    {
438        let callback: Rc<RefCell<dyn FnMut(&T)>> = Rc::new(RefCell::new(f));
439        self.observe_callback(callback)
440    }
441
442    /// Observe this stream with a shared [`Observer`].
443    pub fn observe_with(&self, observer: &Observer<T>) -> Subscription {
444        self.observe_callback(observer.callback.clone())
445    }
446
447    fn observe_callback(&self, callback: Rc<RefCell<dyn FnMut(&T)>>) -> Subscription {
448        let node =
449            Rc::new_cyclic(|weak| ObserverNode::new(self.node.clone(), callback, weak.clone()));
450        let node_any: Rc<dyn Node> = node.clone();
451        connect(self.node.clone(), node_any.clone());
452        if self.node.is_signal_backed() {
453            resync_signal_ancestors(&self.node);
454            if self.node.ever_observed()
455                && let Some(value) = self.node.pull_output()
456            {
457                node.fire(value);
458            }
459            self.node.mark_observed();
460        }
461        Subscription { node: node_any }
462    }
463
464    /// Map every event.
465    pub fn map<U, F>(&self, f: F) -> EventStream<U>
466    where
467        U: 'static,
468        F: FnMut(&T) -> U + 'static,
469    {
470        let node = Rc::new(MapStreamNode::<T, U>::new(self.node.clone(), Box::new(f)));
471        let node_any: Rc<dyn Node> = node.clone();
472        connect(self.node.clone(), node_any.clone());
473        EventStream::new(node_any)
474    }
475
476    /// Keep only events that satisfy the predicate.
477    pub fn filter<F>(&self, f: F) -> EventStream<T>
478    where
479        F: FnMut(&T) -> bool + 'static,
480    {
481        let node = Rc::new(FilterStreamNode::<T>::new(self.node.clone(), Box::new(f)));
482        let node_any: Rc<dyn Node> = node.clone();
483        connect(self.node.clone(), node_any.clone());
484        EventStream::new(node_any)
485    }
486
487    /// Map and filter in one step.
488    pub fn filter_map<U, F>(&self, f: F) -> EventStream<U>
489    where
490        U: 'static,
491        F: FnMut(&T) -> Option<U> + 'static,
492    {
493        let node = Rc::new(FilterMapStreamNode::<T, U>::new(
494            self.node.clone(),
495            Box::new(f),
496        ));
497        let node_any: Rc<dyn Node> = node.clone();
498        connect(self.node.clone(), node_any.clone());
499        EventStream::new(node_any)
500    }
501
502    /// Emit the running fold of every event.
503    pub fn fold<U, F>(&self, init: U, f: F) -> EventStream<U>
504    where
505        U: 'static,
506        F: FnMut(&U, &T) -> U + 'static,
507    {
508        let node = Rc::new(FoldStreamNode::<T, U>::new(init, Box::new(f)));
509        let node_any: Rc<dyn Node> = node.clone();
510        connect(self.node.clone(), node_any.clone());
511        EventStream::new(node_any)
512    }
513
514    /// Drop consecutive duplicates.
515    pub fn distinct(&self) -> EventStream<T>
516    where
517        T: PartialEq,
518    {
519        let node = Rc::new(DistinctStreamNode::<T>::new(self.node.clone()));
520        let node_any: Rc<dyn Node> = node.clone();
521        connect(self.node.clone(), node_any.clone());
522        EventStream::new(node_any)
523    }
524
525    /// Merge events from two streams, preserving arrival order.
526    pub fn merge(&self, other: &EventStream<T>) -> EventStream<T> {
527        Self::merge_all(vec![self.clone(), other.clone()])
528    }
529
530    /// Merge events from many streams, preserving arrival order.
531    pub fn merge_all(streams: Vec<EventStream<T>>) -> EventStream<T> {
532        assert!(
533            !streams.is_empty(),
534            "merge_all requires at least one stream"
535        );
536        let node = Rc::new(MergeStreamNode::<T>::new());
537        let node_any: Rc<dyn Node> = node.clone();
538        for stream in streams {
539            connect(stream.node.clone(), node_any.clone());
540        }
541        EventStream::new(node_any)
542    }
543
544    /// Emit the sampled signal's current value whenever this stream fires.
545    pub fn sample<S>(&self, signal: &Signal<S>) -> EventStream<S>
546    where
547        S: 'static,
548    {
549        let node = Rc::new(SampleStreamNode::<T, S>::new(&signal.node));
550        let node_any: Rc<dyn Node> = node.clone();
551        connect(self.node.clone(), node_any.clone());
552        EventStream::new(node_any)
553    }
554
555    /// Turn this stream into a signal that starts with `initial` and holds the
556    /// latest event.
557    pub fn start_with(&self, initial: T) -> Signal<T>
558    where
559        T: PartialEq,
560    {
561        let node = Rc::new(StartWithNode::new(initial));
562        let node_any: Rc<dyn Node> = node.clone();
563        connect(self.node.clone(), node_any.clone());
564        Signal::new(node_any)
565    }
566
567    /// Switch to the latest inner stream produced by `f`; only the current
568    /// inner stream's events are emitted.
569    pub fn flat_map_switch<U, F>(&self, mut f: F) -> EventStream<U>
570    where
571        U: 'static,
572        F: FnMut(&T) -> EventStream<U> + 'static,
573    {
574        let node = Rc::new_cyclic(|weak| {
575            FlatMapSwitchNode::<T, U>::new(
576                Box::new(move |value: &T| f(value).node.clone()),
577                weak.clone(),
578            )
579        });
580        let node_any: Rc<dyn Node> = node.clone();
581        connect(self.node.clone(), node_any.clone());
582        EventStream::new(node_any)
583    }
584}
585
586/// A reusable callback handle that can observe several observables at once.
587pub struct Observer<T> {
588    callback: Rc<RefCell<dyn FnMut(&T)>>,
589}
590
591impl<T> Observer<T> {
592    /// Create an observer from a callback.
593    pub fn new<F>(f: F) -> Self
594    where
595        F: FnMut(&T) + 'static,
596    {
597        Self {
598            callback: Rc::new(RefCell::new(f)),
599        }
600    }
601
602    /// Invoke the callback directly with `value`.
603    pub fn on_next(&self, value: &T) {
604        (self.callback.borrow_mut())(value);
605    }
606}
607
608impl Subscription {
609    /// Register this subscription with `owner`; dropping the owner unsubscribes.
610    pub fn owned_by(self, owner: &mut Owner) {
611        owner.add(self);
612    }
613}
614
615/// Owns a set of subscriptions and unsubscribes all of them when dropped.
616pub struct Owner {
617    subscriptions: Vec<Subscription>,
618}
619
620impl Owner {
621    /// Create an empty owner.
622    pub fn new() -> Self {
623        Self {
624            subscriptions: Vec::new(),
625        }
626    }
627
628    /// Take ownership of `subscription`.
629    pub fn add(&mut self, subscription: Subscription) {
630        self.subscriptions.push(subscription);
631    }
632
633    /// Take ownership of `subscription` and return `self` for chaining.
634    pub fn track(&mut self, subscription: Subscription) -> &mut Self {
635        self.subscriptions.push(subscription);
636        self
637    }
638
639    /// Unsubscribe and drop every subscription, leaving the owner empty.
640    pub fn clear(&mut self) {
641        self.subscriptions.clear();
642    }
643}
644
645impl Default for Owner {
646    fn default() -> Self {
647        Self::new()
648    }
649}
650
651impl Drop for Owner {
652    fn drop(&mut self) {
653        self.subscriptions.clear();
654    }
655}
656
657/// Cooperative cancellation token shared with a running [`Task`].
658#[derive(Clone)]
659pub struct CancellationToken(Arc<AtomicBool>);
660
661impl CancellationToken {
662    /// Create an uncancelled token.
663    pub fn new() -> Self {
664        Self(Arc::new(AtomicBool::new(false)))
665    }
666
667    /// Request cancellation. Best-effort: the worker should check
668    /// [`CancellationToken::is_cancelled`] regularly.
669    pub fn cancel(&self) {
670        self.0.store(true, Ordering::Relaxed);
671    }
672
673    /// Whether cancellation has been requested.
674    pub fn is_cancelled(&self) -> bool {
675        self.0.load(Ordering::Relaxed)
676    }
677}
678
679impl Default for CancellationToken {
680    fn default() -> Self {
681        Self::new()
682    }
683}
684
685type DeliverySlot = Box<dyn FnMut(Box<dyn Any + Send>)>;
686
687thread_local! {
688    static DELIVERY_SLOTS: RefCell<HashMap<u64, DeliverySlot>> = RefCell::new(HashMap::new());
689}
690
691/// Handle to a background task. The result is delivered to the thread that
692/// spawned the task through the given [`Scheduler`]; subscribe with
693/// [`Task::results`].
694pub struct Task<T> {
695    id: u64,
696    token: CancellationToken,
697    sink: Rc<Sink<T>>,
698    handle: RefCell<Option<JoinHandle<()>>>,
699}
700
701impl<T> Task<T>
702where
703    T: 'static,
704{
705    /// Request cancellation of the background work.
706    pub fn cancel(&self) {
707        self.token.cancel();
708    }
709
710    /// Whether cancellation has been requested.
711    pub fn is_cancelled(&self) -> bool {
712        self.token.is_cancelled()
713    }
714
715    /// A stream of task results, delivered on the graph's thread.
716    pub fn results(&self) -> EventStream<T> {
717        self.sink.stream()
718    }
719}
720
721impl<T> Drop for Task<T> {
722    fn drop(&mut self) {
723        // Drop the delivery slot so a queued delivery is discarded safely if
724        // the task is dropped before it runs.
725        DELIVERY_SLOTS.with(|slots| {
726            slots.borrow_mut().remove(&self.id);
727        });
728        self.token.cancel();
729        // Detach the worker: it runs to completion, but cancellation is
730        // cooperative and its result will not be delivered.
731        self.handle.borrow_mut().take();
732    }
733}
734
735/// Run `f` on a background thread and deliver its result onto the thread that
736/// owns the reactive graph via `scheduler`.
737///
738/// `f` receives a [`CancellationToken`] so it can abort cooperatively. If the
739/// task is cancelled (or the [`Task`] handle is dropped) before completion,
740/// the result is never delivered. The scheduler must run tasks on the
741/// spawning thread; otherwise delivery is safely discarded.
742pub fn spawn_task<F, T>(scheduler: Arc<dyn Scheduler + Send + Sync>, f: F) -> Task<T>
743where
744    T: 'static + Send,
745    F: FnOnce(&CancellationToken) -> T + Send + 'static,
746{
747    static NEXT_TASK_ID: AtomicU64 = AtomicU64::new(1);
748    let id = NEXT_TASK_ID.fetch_add(1, Ordering::Relaxed);
749
750    let sink = Rc::new(Sink::new());
751    let slot: DeliverySlot = {
752        let sink = sink.clone();
753        Box::new(move |value: Box<dyn Any + Send>| {
754            let value = value.downcast::<T>().expect("task result type mismatch");
755            sink.send(*value);
756        })
757    };
758    DELIVERY_SLOTS.with(|slots| {
759        slots.borrow_mut().insert(id, slot);
760    });
761
762    let token = CancellationToken::new();
763    let worker_token = token.clone();
764    let handle = std::thread::spawn(move || {
765        let value = f(&worker_token);
766        if worker_token.is_cancelled() {
767            return;
768        }
769        scheduler.schedule(Box::new(move || {
770            let value: Box<dyn Any + Send> = Box::new(value);
771            DELIVERY_SLOTS.with(|slots| {
772                if let Some(mut slot) = slots.borrow_mut().remove(&id) {
773                    slot(value);
774                }
775            });
776        }));
777    });
778
779    Task {
780        id,
781        token,
782        sink,
783        handle: RefCell::new(Some(handle)),
784    }
785}
786
787/// Handle to a repeating background sampler started by [`spawn_interval`].
788/// Each sample is delivered to the thread that spawned it through the given
789/// [`Scheduler`]; subscribe with [`Interval::results`].
790pub struct Interval<T> {
791    id: u64,
792    token: CancellationToken,
793    stop: Arc<AtomicBool>,
794    sink: Rc<Sink<T>>,
795    handle: RefCell<Option<JoinHandle<()>>>,
796}
797
798impl<T> Interval<T>
799where
800    T: 'static,
801{
802    /// Request cancellation; the worker stops at the next tick boundary.
803    pub fn stop(&self) {
804        self.stop.store(true, Ordering::Relaxed);
805        self.token.cancel();
806    }
807
808    /// A stream of samples, delivered on the graph's thread.
809    pub fn results(&self) -> EventStream<T> {
810        self.sink.stream()
811    }
812}
813
814impl<T> Drop for Interval<T> {
815    fn drop(&mut self) {
816        self.stop.store(true, Ordering::Relaxed);
817        self.token.cancel();
818        DELIVERY_SLOTS.with(|slots| {
819            slots.borrow_mut().remove(&self.id);
820        });
821        // Detach the worker: it observes the stop flag within one tick.
822        self.handle.borrow_mut().take();
823    }
824}
825
826/// Run `f` on a background thread every `interval`, delivering each sample
827/// onto the thread that owns the reactive graph via `scheduler`.
828///
829/// `f` receives a [`CancellationToken`] so it can abort cooperatively.
830/// Deliveries are coalesced: if the previous sample is still pending on the
831/// graph thread when the next one is ready, the pending one is dropped rather
832/// than queueing an unbounded backlog. The scheduler must run tasks on the
833/// spawning thread; otherwise delivery is safely discarded.
834pub fn spawn_interval<F, T>(
835    scheduler: Arc<dyn Scheduler + Send + Sync>,
836    interval: Duration,
837    mut f: F,
838) -> Interval<T>
839where
840    T: 'static + Send,
841    F: FnMut(&CancellationToken) -> T + Send + 'static,
842{
843    static NEXT_INTERVAL_ID: AtomicU64 = AtomicU64::new(1);
844    let id = NEXT_INTERVAL_ID.fetch_add(1, Ordering::Relaxed);
845
846    let sink = Rc::new(Sink::new());
847    let slot: DeliverySlot = {
848        let sink = sink.clone();
849        Box::new(move |value: Box<dyn Any + Send>| {
850            let value = value
851                .downcast::<T>()
852                .expect("interval sample type mismatch");
853            sink.send(*value);
854        })
855    };
856    DELIVERY_SLOTS.with(|slots| {
857        slots.borrow_mut().insert(id, slot);
858    });
859
860    let token = CancellationToken::new();
861    let worker_token = token.clone();
862    let stop = Arc::new(AtomicBool::new(false));
863    let worker_stop = stop.clone();
864    let pending = Arc::new(AtomicUsize::new(0));
865    let handle = std::thread::spawn(move || {
866        loop {
867            if worker_stop.load(Ordering::Relaxed) || worker_token.is_cancelled() {
868                break;
869            }
870            let value = f(&worker_token);
871            if worker_token.is_cancelled() {
872                break;
873            }
874            // Coalesce bursts: skip delivery when the previous sample has not
875            // been consumed by the graph thread yet.
876            if pending.load(Ordering::Relaxed) == 0 {
877                pending.store(1, Ordering::Relaxed);
878                let pending = pending.clone();
879                let id = id;
880                scheduler.schedule(Box::new(move || {
881                    let value: Box<dyn Any + Send> = Box::new(value);
882                    DELIVERY_SLOTS.with(|slots| {
883                        if let Some(slot) = slots.borrow_mut().get_mut(&id) {
884                            slot(value);
885                        }
886                    });
887                    pending.store(0, Ordering::Relaxed);
888                }));
889            }
890            // Sleep in small chunks so stop() is honoured within ~20 ms.
891            let deadline = Instant::now() + interval;
892            while Instant::now() < deadline {
893                if worker_stop.load(Ordering::Relaxed) {
894                    break;
895                }
896                std::thread::sleep(Duration::from_millis(20));
897            }
898        }
899        DELIVERY_SLOTS.with(|slots| {
900            slots.borrow_mut().remove(&id);
901        });
902    });
903
904    Interval {
905        id,
906        token,
907        stop,
908        sink,
909        handle: RefCell::new(Some(handle)),
910    }
911}