Skip to main content

tilo_wake/
lib.rs

1//! Instance-scoped background wake routing, shared by native and headless hosts:
2//! a scope whose owner is woken when work lands for it. No async runtime is
3//! linked, so a document model can route wakes in a sandboxed wasm build.
4use std::cell::RefCell;
5use std::marker::PhantomData;
6use std::rc::Rc;
7use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
8use std::sync::mpsc::{Receiver, Sender, SyncSender, channel};
9use std::sync::{Arc, Condvar, Mutex, PoisonError, Weak};
10use tilo_lock::MutexRecover as _;
11
12type Sink = Arc<dyn Fn(WakeEvent) + Send + Sync>;
13
14#[derive(Default)]
15struct Destination {
16    sink: Option<Sink>,
17    pending: bool,
18    pending_sync: bool,
19    settling: Settling,
20}
21
22#[derive(Default)]
23struct Settling {
24    owed: usize,
25    replied: bool,
26    woken: bool,
27}
28
29struct Route {
30    open: AtomicBool,
31    destination: Mutex<Destination>,
32    changed: Condvar,
33    /// Bumped on every wake and every noted change, never reset, so comparing it
34    /// before and after proves nothing reached the owner in between.
35    revision: AtomicU64,
36    crossed: AtomicU64,
37    thread: std::thread::ThreadId,
38    /// The scope this one was made inside, whose revision it moves as well.
39    parent: Option<Weak<Route>>,
40}
41
42impl Route {
43    fn moved(&self) {
44        let crossed = std::thread::current().id() != self.thread;
45        self.bump(crossed);
46        let mut parent = self.parent.as_ref().and_then(Weak::upgrade);
47        while let Some(route) = parent {
48            route.bump(crossed);
49            parent = route.parent.as_ref().and_then(Weak::upgrade);
50        }
51    }
52
53    fn bump(&self, crossed: bool) {
54        self.revision.fetch_add(1, Ordering::AcqRel);
55        if crossed {
56            self.crossed.fetch_add(1, Ordering::AcqRel);
57        }
58    }
59}
60
61thread_local! {
62    static CURRENT: RefCell<Option<Weak<Route>>> = const { RefCell::new(None) };
63    /// How deep the running passes of a component that wires work off the frame are.
64    static FEEDS_COMPONENT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
65}
66
67/// Marks the running component as one that wires work off the frame, so a debug
68/// build fails where such a wake is made.
69#[doc(hidden)]
70#[must_use]
71pub struct FeedsComponent(());
72
73impl FeedsComponent {
74    pub fn begin() -> Self {
75        FEEDS_COMPONENT.with(|feeds| feeds.set(feeds.get().saturating_add(1)));
76        Self(())
77    }
78}
79
80impl Drop for FeedsComponent {
81    fn drop(&mut self) {
82        FEEDS_COMPONENT.with(|feeds| feeds.set(feeds.get().saturating_sub(1)));
83    }
84}
85
86pub struct WakeScope {
87    route: Arc<Route>,
88}
89
90#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
91pub enum WakeBindError {
92    #[error("wake scope already has a destination")]
93    AlreadyBound,
94    #[error("wake scope is closed")]
95    Closed,
96}
97
98impl Default for WakeScope {
99    fn default() -> Self {
100        Self::new()
101    }
102}
103
104impl WakeScope {
105    pub fn new() -> Self {
106        Self {
107            route: Arc::new(Route {
108                open: AtomicBool::new(true),
109                destination: Mutex::new(Destination::default()),
110                changed: Condvar::new(),
111                revision: AtomicU64::new(0),
112                crossed: AtomicU64::new(0),
113                thread: std::thread::current().id(),
114                parent: CURRENT.with(|current| current.borrow().clone()),
115            }),
116        }
117    }
118
119    pub fn revision(&self) -> u64 {
120        self.route.revision.load(Ordering::Acquire)
121    }
122
123    pub fn handle(&self) -> WakeHandle {
124        WakeHandle {
125            route: Some(Arc::downgrade(&self.route)),
126        }
127    }
128
129    pub fn enter(&self) -> WakeScopeGuard {
130        let previous = CURRENT.with(|current| current.replace(Some(Arc::downgrade(&self.route))));
131        WakeScopeGuard {
132            previous,
133            thread_affinity: PhantomData,
134        }
135    }
136
137    pub fn enter_detached() -> WakeScopeGuard {
138        let previous = CURRENT.with(|current| current.replace(None));
139        WakeScopeGuard {
140            previous,
141            thread_affinity: PhantomData,
142        }
143    }
144
145    /// Bind a destination for this scope's wakes, flushing work that arrived before
146    /// startup. The sink must capture a sender or proxy, never an owning host
147    /// reference.
148    ///
149    /// # Errors
150    ///
151    /// [`WakeBindError::Closed`] once the scope has closed,
152    /// [`WakeBindError::AlreadyBound`] when a destination is already installed.
153    pub fn bind(
154        &mut self,
155        sink: impl Fn(WakeEvent) + Send + Sync + 'static,
156    ) -> Result<(), WakeBindError> {
157        let (pending, requires_sync) = {
158            let mut destination = self.route.destination.lock_recover();
159            if !self.route.open.load(Ordering::Acquire) {
160                return Err(WakeBindError::Closed);
161            }
162            if destination.sink.is_some() {
163                return Err(WakeBindError::AlreadyBound);
164            }
165            destination.sink = Some(Arc::new(sink));
166            (
167                std::mem::take(&mut destination.pending),
168                std::mem::take(&mut destination.pending_sync),
169            )
170        };
171        if pending {
172            self.handle().send_wake(requires_sync, false);
173        }
174        Ok(())
175    }
176
177    /// Wakes recorded while no destination was bound, as `(pending, requires_sync)`.
178    /// `None` when they are not observable here, so a caller must assume a
179    /// model-dirty wake.
180    pub fn take_unbound(&self) -> Option<(bool, bool)> {
181        let mut destination = self.route.destination.lock_recover();
182        if !self.route.open.load(Ordering::Acquire) || destination.sink.is_some() {
183            return None;
184        }
185        Some((
186            std::mem::take(&mut destination.pending),
187            std::mem::take(&mut destination.pending_sync),
188        ))
189    }
190
191    /// Take the owner's coalesced wake flags, including the wakes its event sink
192    /// received; `None` once the scope has closed.
193    pub fn take_pending(&self) -> Option<(bool, bool)> {
194        let mut destination = self.route.destination.lock_recover();
195        if !self.route.open.load(Ordering::Acquire) {
196            return None;
197        }
198        Some((
199            std::mem::take(&mut destination.pending),
200            std::mem::take(&mut destination.pending_sync),
201        ))
202    }
203
204    pub fn is_pending(&self) -> bool {
205        self.route.open.load(Ordering::Acquire) && self.route.destination.lock_recover().pending
206    }
207
208    /// Whether the waiting wake asks for a model pass, without taking it: an owner
209    /// that drains wakes mid-pass keeps it pending.
210    pub fn sync_pending(&self) -> Option<bool> {
211        if !self.route.open.load(Ordering::Acquire) {
212            return None;
213        }
214        Some(self.route.destination.lock_recover().pending_sync)
215    }
216
217    pub fn accepts(&self, event: &WakeEvent) -> bool {
218        self.route.open.load(Ordering::Acquire)
219            && Weak::ptr_eq(&Arc::downgrade(&self.route), &event.route)
220    }
221
222    pub fn close(&mut self) {
223        self.route.open.swap(false, Ordering::AcqRel);
224        drop(self.route.destination.lock_recover());
225        self.route.changed.notify_all();
226    }
227}
228
229impl Drop for WakeScope {
230    fn drop(&mut self) {
231        self.close();
232    }
233}
234
235/// A thread-affine construction and dispatch guard, independent of an App
236/// borrow.
237///
238/// ```compile_fail
239/// let scope = tilo_rt::wake::WakeScope::new();
240/// let guard = scope.enter();
241/// std::thread::spawn(move || drop(guard));
242/// ```
243pub struct WakeScopeGuard {
244    previous: Option<Weak<Route>>,
245    thread_affinity: PhantomData<Rc<()>>,
246}
247
248impl Drop for WakeScopeGuard {
249    fn drop(&mut self) {
250        CURRENT.with(|current| {
251            current.replace(self.previous.take());
252        });
253    }
254}
255
256/// A weak identity for a queued wake; it never owns an app or its scope.
257#[derive(Clone, Debug)]
258pub struct WakeEvent {
259    route: Weak<Route>,
260    requires_sync: bool,
261    save_progress: bool,
262}
263
264impl WakeEvent {
265    #[doc(hidden)]
266    pub const fn requires_sync(&self) -> bool {
267        self.requires_sync
268    }
269
270    /// Says only that a record's save moved on, so an owner may show the new status
271    /// without running its model.
272    #[doc(hidden)]
273    pub const fn save_progress(&self) -> bool {
274        self.save_progress
275    }
276
277    /// Whether the wake also asks for a frame. A save-progress wake does not, so a
278    /// keystroke's write landing draws no second frame.
279    pub const fn asks_for_frame(&self) -> bool {
280        !self.save_progress
281    }
282}
283
284#[derive(Clone, Debug)]
285pub struct WakeHandle {
286    route: Option<Weak<Route>>,
287}
288
289impl Default for WakeHandle {
290    fn default() -> Self {
291        Self::new()
292    }
293}
294
295impl WakeHandle {
296    #[doc(hidden)]
297    pub fn accepts(&self, event: &WakeEvent) -> bool {
298        self.is_active()
299            && self
300                .route
301                .as_ref()
302                .is_some_and(|route| Weak::ptr_eq(route, &event.route))
303    }
304
305    #[doc(hidden)]
306    pub fn enter_if_open(&self) -> Result<WakeScopeGuard, WakeBindError> {
307        let route = self.route.as_ref().ok_or(WakeBindError::Closed)?;
308        if !route
309            .upgrade()
310            .is_some_and(|route| route.open.load(Ordering::Acquire))
311        {
312            return Err(WakeBindError::Closed);
313        }
314        let previous = CURRENT.with(|current| current.replace(Some(route.clone())));
315        Ok(WakeScopeGuard {
316            previous,
317            thread_affinity: PhantomData,
318        })
319    }
320
321    pub fn new() -> Self {
322        let handle = Self {
323            route: CURRENT.with(|current| current.borrow().clone()),
324        };
325        debug_assert!(
326            !(handle.is_detached() && FEEDS_COMPONENT.with(std::cell::Cell::get) > 0),
327            "work a component starts captured a wake that reaches no component: take the wake \
328             from the component that runs now, not from a construction that already ended"
329        );
330        handle
331    }
332
333    pub const fn detached() -> Self {
334        Self { route: None }
335    }
336
337    pub fn scope_key(&self) -> Option<usize> {
338        self.route
339            .as_ref()
340            .map(|route| route.as_ptr().cast::<()>() as usize)
341    }
342
343    pub const fn is_detached(&self) -> bool {
344        self.route.is_none()
345    }
346
347    pub fn is_active(&self) -> bool {
348        match &self.route {
349            None => true,
350            Some(route) => route
351                .upgrade()
352                .is_some_and(|route| route.open.load(Ordering::Acquire)),
353        }
354    }
355
356    /// Compare two original scoped routes while the route is open; detached handles
357    /// never match. Scheduling metadata, not authorization.
358    #[doc(hidden)]
359    pub fn same_open_scope(&self, other: &Self) -> bool {
360        let (Some(route), Some(other_route)) = (&self.route, &other.route) else {
361            return false;
362        };
363        Weak::ptr_eq(route, other_route)
364            && route
365                .upgrade()
366                .is_some_and(|route| route.open.load(Ordering::Acquire))
367    }
368
369    #[doc(hidden)]
370    pub fn authorize_publication(&self) -> bool {
371        match &self.route {
372            None => true,
373            Some(route) => route.upgrade().is_some_and(|route| {
374                route
375                    .open
376                    .compare_exchange(true, true, Ordering::Acquire, Ordering::Relaxed)
377                    .is_ok()
378            }),
379        }
380    }
381
382    pub fn wake(&self) {
383        self.send_wake(true, false);
384    }
385
386    /// Note on the owner's thread that something it reads changed, without waking
387    /// it: a pass that is running or due takes it up.
388    pub fn note_change(&self) {
389        if let Some(route) = self.route.as_ref().and_then(Weak::upgrade)
390            && route.open.load(Ordering::Acquire)
391        {
392            route.moved();
393        }
394    }
395
396    pub fn revision(&self) -> Option<u64> {
397        let route = self.route.as_ref()?.upgrade()?;
398        route
399            .open
400            .load(Ordering::Acquire)
401            .then(|| route.revision.load(Ordering::Acquire))
402    }
403
404    pub fn crossed(&self) -> Option<u64> {
405        let route = self.route.as_ref()?.upgrade()?;
406        route
407            .open
408            .load(Ordering::Acquire)
409            .then(|| route.crossed.load(Ordering::Acquire))
410    }
411
412    /// Wake the owner because a record's save moved on, and for nothing else.
413    pub fn wake_save_progress(&self) {
414        self.send_wake(true, true);
415    }
416
417    #[doc(hidden)]
418    pub fn notify_events(&self) {
419        self.send_wake(false, false);
420    }
421
422    /// Owe the owner a reply: the work holds the [`Owed`] and drops it once its
423    /// answer is queued.
424    pub fn owe(&self) -> Owed {
425        let route = self.route.as_ref().filter(|route| {
426            route.upgrade().is_some_and(|route| {
427                let mut destination = route.destination.lock_recover();
428                let open = route.open.load(Ordering::Acquire);
429                if open {
430                    destination.settling.owed = destination.settling.owed.saturating_add(1);
431                }
432                open
433            })
434        });
435        Owed {
436            route: route.cloned(),
437        }
438    }
439
440    pub fn owes(&self) -> bool {
441        self.route
442            .as_ref()
443            .and_then(Weak::upgrade)
444            .is_some_and(|route| {
445                route.open.load(Ordering::Acquire)
446                    && route.destination.lock_recover().settling.owed > 0
447            })
448    }
449
450    /// Mark where a pass begins, so [`Self::settled`] asks only about replies that
451    /// land after it.
452    pub fn begin_pass(&self) {
453        if let Some(route) = self.route.as_ref().and_then(Weak::upgrade) {
454            let mut destination = route.destination.lock_recover();
455            destination.settling.replied = false;
456            destination.settling.woken = false;
457        }
458    }
459
460    /// Whether nothing is owed and no reply landed since [`Self::begin_pass`].
461    pub fn settled(&self) -> bool {
462        self.route
463            .as_ref()
464            .and_then(Weak::upgrade)
465            .is_none_or(|route| {
466                let destination = route.destination.lock_recover();
467                !route.open.load(Ordering::Acquire)
468                    || (destination.settling.owed == 0 && !destination.settling.replied)
469            })
470    }
471
472    /// Run `pass` until nothing is owed and a pass ran after the last reply landed.
473    /// One pass always runs, then it waits to be woken; it never polls.
474    pub fn settle(&self, mut pass: impl FnMut()) {
475        let Some(route) = self.route.as_ref().and_then(Weak::upgrade) else {
476            pass();
477            return;
478        };
479        loop {
480            self.begin_pass();
481            pass();
482            let mut destination = route.destination.lock_recover();
483            loop {
484                if !route.open.load(Ordering::Acquire) {
485                    return;
486                }
487                if destination.settling.replied {
488                    break;
489                }
490                if destination.settling.owed == 0 {
491                    return;
492                }
493                if destination.settling.woken {
494                    break;
495                }
496                destination = route
497                    .changed
498                    .wait(destination)
499                    .unwrap_or_else(PoisonError::into_inner);
500            }
501        }
502    }
503
504    fn send_wake(&self, requires_sync: bool, save_progress: bool) {
505        if !self.authorize_publication() {
506            return;
507        }
508        let Some(weak) = &self.route else {
509            return;
510        };
511        let Some(route) = weak.upgrade() else {
512            return;
513        };
514        let sink = {
515            let mut destination = route.destination.lock_recover();
516            if !route.open.load(Ordering::Acquire) {
517                return;
518            }
519            destination.pending = true;
520            destination.pending_sync |= requires_sync;
521            destination.settling.woken = true;
522            route.moved();
523            destination.sink.as_ref().map(Arc::clone)
524        };
525        route.changed.notify_all();
526        if let Some(sink) = sink {
527            sink(WakeEvent {
528                route: weak.clone(),
529                requires_sync,
530                save_progress,
531            });
532        }
533    }
534}
535
536#[must_use = "dropping it at once says the reply already landed"]
537pub struct Owed {
538    route: Option<Weak<Route>>,
539}
540
541impl std::fmt::Debug for Owed {
542    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
543        f.debug_struct("Owed").finish_non_exhaustive()
544    }
545}
546
547impl Drop for Owed {
548    fn drop(&mut self) {
549        let Some(weak) = self.route.take() else {
550            return;
551        };
552        let Some(route) = weak.upgrade() else {
553            return;
554        };
555        {
556            let mut destination = route.destination.lock_recover();
557            destination.settling.owed = destination.settling.owed.saturating_sub(1);
558            destination.settling.replied = true;
559        }
560        route.changed.notify_all();
561        WakeHandle { route: Some(weak) }.wake();
562    }
563}
564
565/// The answering end of a request made under a wake scope; sending the answer
566/// wakes that scope's event loop.
567pub struct Reply<T> {
568    sender: Sender<T>,
569    wake: WakeHandle,
570}
571
572pub fn reply<T>() -> (Reply<T>, Receiver<T>) {
573    let (sender, receiver) = channel();
574    (
575        Reply {
576            sender,
577            wake: WakeHandle::new(),
578        },
579        receiver,
580    )
581}
582
583impl<T> Reply<T> {
584    pub fn send(self, answer: T) {
585        if self.sender.send(answer).is_ok() {
586            self.wake.wake();
587        }
588    }
589}
590
591/// Wakes the component that opened a [`waking_channel`] for every message,
592/// before the message can be received and again once it can.
593struct Reporting {
594    wake: WakeHandle,
595}
596
597impl Reporting {
598    fn new() -> Self {
599        Self {
600            wake: WakeHandle::new(),
601        }
602    }
603
604    fn announce<T>(
605        &self,
606        queue: impl FnOnce() -> Result<(), std::sync::mpsc::SendError<T>>,
607    ) -> Result<(), std::sync::mpsc::SendError<T>> {
608        self.wake.wake();
609        let queued = queue();
610        if queued.is_ok() {
611            self.wake.wake();
612        }
613        queued
614    }
615}
616
617impl Clone for Reporting {
618    fn clone(&self) -> Self {
619        Self {
620            wake: self.wake.clone(),
621        }
622    }
623}
624
625/// The worker's end of a [`waking_channel`]: every send wakes the scope that
626/// opened it.
627pub struct WakingSender<T> {
628    sender: Sender<T>,
629    reporting: Reporting,
630}
631
632impl<T> Clone for WakingSender<T> {
633    fn clone(&self) -> Self {
634        Self {
635            sender: self.sender.clone(),
636            reporting: self.reporting.clone(),
637        }
638    }
639}
640
641impl<T> WakingSender<T> {
642    pub fn send(&self, message: T) -> Result<(), std::sync::mpsc::SendError<T>> {
643        let sender = &self.sender;
644        self.reporting.announce(|| sender.send(message))
645    }
646}
647
648impl<T> Drop for WakingSender<T> {
649    /// A worker that ends without replying wakes the owner too, so it sees the
650    /// channel disconnected.
651    fn drop(&mut self) {
652        self.reporting.wake.wake();
653    }
654}
655
656/// The worker's end of a [`waking_sync_channel`], which queues no faster than
657/// its owner takes.
658pub struct WakingSyncSender<T> {
659    sender: SyncSender<T>,
660    reporting: Reporting,
661}
662
663impl<T> Clone for WakingSyncSender<T> {
664    fn clone(&self) -> Self {
665        Self {
666            sender: self.sender.clone(),
667            reporting: self.reporting.clone(),
668        }
669    }
670}
671
672impl<T> WakingSyncSender<T> {
673    pub fn send(&self, message: T) -> Result<(), std::sync::mpsc::SendError<T>> {
674        let sender = &self.sender;
675        self.reporting.announce(|| sender.send(message))
676    }
677}
678
679impl<T> Drop for WakingSyncSender<T> {
680    fn drop(&mut self) {
681        self.reporting.wake.wake();
682    }
683}
684
685/// A channel opened under the current wake scope: every reply a worker sends
686/// wakes the app's loop, which drains it on its next sync.
687#[must_use]
688pub fn waking_channel<T>() -> (WakingSender<T>, Receiver<T>) {
689    let (sender, receiver) = channel();
690    (
691        WakingSender {
692            sender,
693            reporting: Reporting::new(),
694        },
695        receiver,
696    )
697}
698
699/// [`waking_channel`] with room for `bound` messages, so a worker sending costly
700/// replies waits for its owner to take them.
701#[must_use]
702pub fn waking_sync_channel<T>(bound: usize) -> (WakingSyncSender<T>, Receiver<T>) {
703    let (sender, receiver) = std::sync::mpsc::sync_channel(bound);
704    (
705        WakingSyncSender {
706            sender,
707            reporting: Reporting::new(),
708        },
709        receiver,
710    )
711}
712
713#[cfg(test)]
714mod tests {
715    use super::*;
716    use std::sync::mpsc::{self, Receiver, TryRecvError};
717
718    #[test]
719    fn a_bound_owner_observes_model_wakes_without_losing_sink_delivery() {
720        let (mut scope, rx) = bound_scope();
721        assert_eq!(scope.take_pending(), Some((false, false)));
722        scope.handle().notify_events();
723        assert!(!rx.recv().unwrap().requires_sync());
724        assert_eq!(scope.take_pending(), Some((true, false)));
725        scope.handle().wake();
726        scope.handle().notify_events();
727        assert!(rx.recv().unwrap().requires_sync());
728        assert!(!rx.recv().unwrap().requires_sync());
729        assert_eq!(scope.take_pending(), Some((true, true)));
730        assert_eq!(scope.take_pending(), Some((false, false)));
731        assert_eq!(scope.take_unbound(), None);
732        scope.close();
733        scope.handle().wake();
734        assert_eq!(scope.take_pending(), None);
735        assert!(matches!(rx.try_recv(), Err(TryRecvError::Empty)));
736    }
737
738    #[test]
739    fn every_wake_and_noted_change_moves_the_revision_whoever_drains_the_wakes() {
740        let (scope, _rx) = bound_scope();
741        let handle = scope.handle();
742        let start = handle.revision().unwrap();
743        handle.notify_events();
744        let _ = scope.take_pending();
745        assert_ne!(
746            handle.revision(),
747            Some(start),
748            "a drained wake still moved it"
749        );
750        let woken = handle.revision();
751        handle.note_change();
752        assert_ne!(handle.revision(), woken, "a noted change moves it");
753        assert_eq!(scope.take_pending(), Some((false, false)), "without waking");
754        assert_eq!(WakeHandle::detached().revision(), None);
755        let noted = scope.revision();
756        drop(scope);
757        handle.note_change();
758        assert_eq!(handle.revision(), None, "a closed scope has none");
759        assert!(noted >= start + 2);
760    }
761
762    #[test]
763    fn only_a_move_from_another_thread_counts_as_crossed() {
764        let (scope, _rx) = bound_scope();
765        let handle = scope.handle();
766        handle.notify_events();
767        handle.note_change();
768        assert_eq!(handle.crossed(), Some(0), "the owner's own thread");
769        let remote = handle.clone();
770        std::thread::spawn(move || remote.notify_events())
771            .join()
772            .unwrap();
773        assert_eq!(handle.crossed(), Some(1), "a wake from a worker");
774    }
775
776    #[test]
777    fn a_scope_made_inside_another_moves_the_enclosing_revision() {
778        let outer = WakeScope::new();
779        let inner = {
780            let _entry = outer.enter();
781            WakeScope::new()
782        };
783        let sibling = WakeScope::new();
784        let (before, beside) = (outer.revision(), sibling.revision());
785        inner.handle().note_change();
786        assert_ne!(outer.revision(), before, "the enclosing scope moved");
787        assert_eq!(sibling.revision(), beside, "a scope beside it did not");
788        let moved = outer.revision();
789        outer.handle().note_change();
790        assert_eq!(
791            inner.revision(),
792            1,
793            "an enclosing change moves no scope inside it"
794        );
795        assert_ne!(outer.revision(), moved);
796    }
797
798    #[test]
799    fn wakes_coalesce_before_binding_and_bind_only_once() {
800        {
801            for model_changed in [false, true] {
802                let mut scope = WakeScope::new();
803                scope.handle().notify_events();
804                if model_changed {
805                    scope.handle().wake();
806                }
807                scope.handle().notify_events();
808                let (tx, rx) = mpsc::channel();
809                scope
810                    .bind(move |event| {
811                        tx.send(event).unwrap();
812                    })
813                    .unwrap();
814                let event = rx.try_recv().unwrap();
815                assert_eq!(event.requires_sync(), model_changed);
816                assert!(matches!(rx.try_recv(), Err(TryRecvError::Empty)));
817            }
818        }
819
820        {
821            let mut scope = WakeScope::new();
822            let worker = scope.handle();
823            std::thread::spawn(move || {
824                for _ in 0..8 {
825                    worker.wake();
826                }
827            })
828            .join()
829            .unwrap();
830            let (tx, rx) = mpsc::channel();
831            scope
832                .bind(move |event| {
833                    tx.send(event).unwrap();
834                })
835                .unwrap();
836            assert!(scope.accepts(&rx.try_recv().unwrap()));
837            assert!(matches!(rx.try_recv(), Err(TryRecvError::Empty)));
838            scope.handle().wake();
839            assert!(scope.accepts(&rx.try_recv().unwrap()));
840        }
841
842        {
843            let (mut scope, rx) = bound_scope();
844            assert_eq!(
845                scope.bind(|_| panic!("replacement sink called")),
846                Err(WakeBindError::AlreadyBound)
847            );
848            scope.handle().wake();
849            assert!(scope.accepts(&rx.try_recv().unwrap()));
850            scope.close();
851            assert_eq!(scope.bind(|_| {}), Err(WakeBindError::Closed));
852        }
853    }
854
855    fn bound_scope() -> (WakeScope, Receiver<WakeEvent>) {
856        let (tx, rx) = mpsc::channel();
857        let mut scope = WakeScope::new();
858        scope
859            .bind(move |event| {
860                tx.send(event).unwrap();
861            })
862            .unwrap();
863        (scope, rx)
864    }
865
866    fn drain(rx: &Receiver<WakeEvent>) {
867        while rx.try_recv().is_ok() {}
868    }
869
870    #[test]
871    fn a_worker_reply_on_a_waking_channel_wakes_its_owner() {
872        let (scope, rx) = bound_scope();
873        {
874            let (sender, replies) = {
875                let _entry = scope.enter();
876                waking_channel::<u32>()
877            };
878            std::thread::spawn(move || sender.send(7).unwrap())
879                .join()
880                .unwrap();
881            assert!(
882                rx.recv().unwrap().requires_sync(),
883                "the reply woke the owner"
884            );
885            assert_eq!(replies.try_recv().unwrap(), 7);
886            assert!(rx.recv().is_ok());
887            drain(&rx);
888        }
889        {
890            let (sender, replies) = {
891                let _entry = scope.enter();
892                waking_channel::<u32>()
893            };
894            drop(replies);
895            assert!(sender.send(1).is_err(), "the message reaches nobody");
896            assert!(rx.try_recv().is_ok(), "the attempt was announced");
897            assert!(matches!(rx.try_recv(), Err(TryRecvError::Empty)));
898            drop(sender);
899            drain(&rx);
900        }
901        {
902            let (sender, replies) = {
903                let _entry = scope.enter();
904                waking_channel::<u32>()
905            };
906            std::thread::spawn(move || drop(sender)).join().unwrap();
907            assert!(
908                rx.recv().is_ok(),
909                "a worker that ends without a reply wakes too"
910            );
911            assert!(matches!(
912                replies.try_recv(),
913                Err(std::sync::mpsc::TryRecvError::Disconnected)
914            ));
915            drain(&rx);
916        }
917    }
918
919    #[test]
920    fn a_worker_reply_on_a_bounded_waking_channel_wakes_its_owner() {
921        let (scope, rx) = bound_scope();
922        let (sender, replies) = {
923            let _entry = scope.enter();
924            waking_sync_channel::<u32>(1)
925        };
926        std::thread::spawn(move || sender.send(7).unwrap())
927            .join()
928            .unwrap();
929        assert!(
930            rx.recv().unwrap().requires_sync(),
931            "the reply woke its owner before it could be received"
932        );
933        assert_eq!(replies.try_recv().unwrap(), 7);
934        assert!(rx.recv().is_ok());
935    }
936
937    #[test]
938    #[should_panic(expected = "reaches no component")]
939    fn a_wake_wired_for_a_running_component_reaches_its_component() {
940        let _feeds = super::FeedsComponent::begin();
941        let _detached = WakeHandle::new();
942    }
943
944    #[test]
945    fn a_wake_wired_inside_a_scope_reaches_its_component() {
946        let (scope, rx) = bound_scope();
947        let feeds = super::FeedsComponent::begin();
948        let entry = scope.enter();
949        let handle = WakeHandle::new();
950        drop(entry);
951        drop(feeds);
952        handle.wake();
953        assert!(scope.accepts(&rx.try_recv().unwrap()));
954    }
955
956    #[test]
957    fn handles_keep_their_owner_and_never_keep_a_scope_alive() {
958        {
959            let (mut a, a_rx) = bound_scope();
960            let (b, b_rx) = bound_scope();
961            let a_handle = {
962                let _entry = a.enter();
963                WakeHandle::new()
964            };
965            let b_handle = {
966                let _entry = b.enter();
967                WakeHandle::default()
968            };
969            std::thread::spawn(move || a_handle.wake()).join().unwrap();
970            let a_event = a_rx.try_recv().unwrap();
971            assert!(a.accepts(&a_event));
972            assert!(!b.accepts(&a_event));
973            assert!(matches!(b_rx.try_recv(), Err(TryRecvError::Empty)));
974            a.close();
975            b_handle.wake();
976            assert!(b.accepts(&b_rx.try_recv().unwrap()));
977        }
978
979        {
980            let detached = WakeHandle::new();
981            let (scope, rx) = bound_scope();
982            let _entry = scope.enter();
983            let explicit = WakeHandle::detached();
984            assert!(detached.is_active());
985            assert!(detached.authorize_publication());
986            assert!(explicit.authorize_publication());
987            detached.wake();
988            explicit.wake();
989            assert!(matches!(rx.try_recv(), Err(TryRecvError::Empty)));
990            WakeHandle::new().wake();
991            assert!(scope.accepts(&rx.try_recv().unwrap()));
992        }
993
994        {
995            let scope = WakeScope::new();
996            let entry = scope.enter();
997            drop(scope);
998            let captured = WakeHandle::new();
999            assert!(!captured.is_active());
1000            assert!(!captured.authorize_publication());
1001            drop(entry);
1002            assert!(WakeHandle::new().is_active());
1003        }
1004
1005        {
1006            let resource = Arc::new(());
1007            let weak_resource = Arc::downgrade(&resource);
1008            let mut scope = WakeScope::new();
1009            let (tx, rx) = mpsc::channel();
1010            scope
1011                .bind(move |event| {
1012                    std::hint::black_box(&resource);
1013                    tx.send(event).unwrap();
1014                })
1015                .unwrap();
1016            let handle = scope.handle();
1017            handle.wake();
1018            let event = rx.try_recv().unwrap();
1019            drop(scope);
1020            assert!(weak_resource.upgrade().is_none());
1021            assert!(!handle.is_active());
1022            assert!(!handle.authorize_publication());
1023            let replacement = WakeScope::new();
1024            assert!(!replacement.accepts(&event));
1025        }
1026    }
1027
1028    #[test]
1029    fn same_open_scope_matches_only_the_original_open_scoped_route() {
1030        {
1031            let (scope, rx) = bound_scope();
1032            let (other_scope, other_rx) = bound_scope();
1033            let captured = {
1034                let _entry = scope.enter();
1035                WakeHandle::new()
1036            };
1037            let clone = captured.clone();
1038            let same_scope = {
1039                let _entry = scope.enter();
1040                WakeHandle::new()
1041            };
1042            let other = {
1043                let _entry = other_scope.enter();
1044                WakeHandle::new()
1045            };
1046            assert!(captured.same_open_scope(&clone));
1047            assert!(clone.same_open_scope(&captured));
1048            assert!(captured.same_open_scope(&same_scope));
1049            assert!(!captured.same_open_scope(&other));
1050            assert!(!other.same_open_scope(&captured));
1051            assert!(matches!(rx.try_recv(), Err(TryRecvError::Empty)));
1052            assert!(matches!(other_rx.try_recv(), Err(TryRecvError::Empty)));
1053
1054            let outer = {
1055                let _entry = scope.enter();
1056                let outer = WakeHandle::new();
1057                let inner = {
1058                    let _nested = other_scope.enter();
1059                    WakeHandle::new()
1060                };
1061                let restored_outer = WakeHandle::new();
1062                assert!(outer.same_open_scope(&restored_outer));
1063                assert!(!inner.same_open_scope(&outer));
1064                outer
1065            };
1066            assert!(outer.same_open_scope(&captured));
1067            assert!(matches!(rx.try_recv(), Err(TryRecvError::Empty)));
1068            assert!(matches!(other_rx.try_recv(), Err(TryRecvError::Empty)));
1069        }
1070
1071        // Detached handles never correlate, even when captured under detached entry.
1072        {
1073            let explicit = WakeHandle::detached();
1074            let (scope, rx) = bound_scope();
1075            let detached = {
1076                let _entry = scope.enter();
1077                let _mask = WakeScope::enter_detached();
1078                WakeHandle::new()
1079            };
1080            let scoped = {
1081                let _entry = scope.enter();
1082                WakeHandle::new()
1083            };
1084            for handle in [&explicit, &detached] {
1085                assert!(handle.is_active());
1086                assert!(handle.authorize_publication());
1087                assert!(!handle.same_open_scope(handle));
1088                assert!(!handle.same_open_scope(&handle.clone()));
1089                assert!(!handle.same_open_scope(&scoped));
1090            }
1091            assert!(!explicit.same_open_scope(&detached));
1092            assert!(!scoped.same_open_scope(&explicit));
1093            assert!(matches!(rx.try_recv(), Err(TryRecvError::Empty)));
1094        }
1095
1096        {
1097            let (mut scope, _) = bound_scope();
1098            let old = scope.handle();
1099            let old_clone = old.clone();
1100            assert!(old.same_open_scope(&old_clone));
1101            scope.close();
1102            assert!(!old.same_open_scope(&old_clone));
1103            scope.close();
1104            assert!(!old.same_open_scope(&old_clone));
1105            let (replacement, _) = bound_scope();
1106            let fresh = replacement.handle();
1107            assert!(!old.same_open_scope(&fresh));
1108            assert!(!fresh.same_open_scope(&old));
1109        }
1110
1111        {
1112            let resource = Arc::new(());
1113            let weak_resource = Arc::downgrade(&resource);
1114            let (tx, _rx) = mpsc::channel();
1115            let mut scope = WakeScope::new();
1116            scope
1117                .bind(move |event| {
1118                    std::hint::black_box(&resource);
1119                    tx.send(event).unwrap();
1120                })
1121                .unwrap();
1122            let handle = scope.handle();
1123            let clone = handle.clone();
1124            assert!(handle.same_open_scope(&clone));
1125            drop(scope);
1126            assert!(weak_resource.upgrade().is_none());
1127            assert!(!handle.same_open_scope(&clone));
1128            let (replacement, _) = bound_scope();
1129            assert!(!handle.same_open_scope(&replacement.handle()));
1130        }
1131    }
1132
1133    #[test]
1134    fn closing_rejects_stale_events_without_blocking_or_holding_the_lock() {
1135        {
1136            let (mut old, rx) = bound_scope();
1137            let old_handle = old.handle();
1138            old_handle.wake();
1139            let queued = rx.try_recv().unwrap();
1140            assert!(old.accepts(&queued));
1141            old.close();
1142            let replacement = WakeScope::new();
1143            assert!(!old.accepts(&queued));
1144            assert!(!replacement.accepts(&queued));
1145            assert!(!old_handle.is_active());
1146            assert!(!old_handle.authorize_publication());
1147            old_handle.wake();
1148            assert!(matches!(rx.try_recv(), Err(TryRecvError::Empty)));
1149        }
1150
1151        {
1152            let mut scope = WakeScope::new();
1153            let handle = scope.handle();
1154            assert!(handle.authorize_publication());
1155            scope.close();
1156            assert!(!handle.authorize_publication());
1157            assert!(!handle.is_active());
1158            scope.close(); // idempotent
1159        }
1160
1161        {
1162            let mut scope = WakeScope::new();
1163            let reentrant_handle = scope.handle();
1164            let first = Arc::new(AtomicBool::new(true));
1165            let (tx, rx) = mpsc::channel();
1166            scope
1167                .bind(move |event| {
1168                    if first.swap(false, Ordering::AcqRel) {
1169                        reentrant_handle.wake();
1170                    }
1171                    tx.send(event).unwrap();
1172                })
1173                .unwrap();
1174            scope.handle().wake();
1175            assert!(scope.accepts(&rx.try_recv().unwrap()));
1176            assert!(scope.accepts(&rx.try_recv().unwrap()));
1177            assert!(matches!(rx.try_recv(), Err(TryRecvError::Empty)));
1178        }
1179    }
1180
1181    #[test]
1182    fn entry_masks_and_restores_the_outer_context_even_on_unwind() {
1183        {
1184            let (a, a_rx) = bound_scope();
1185            let (b, b_rx) = bound_scope();
1186            {
1187                let _outer = a.enter();
1188                let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1189                    let _inner = b.enter();
1190                    WakeHandle::new().wake();
1191                    panic!("exercise scope restoration");
1192                }));
1193                assert!(result.is_err());
1194                WakeHandle::new().wake();
1195            }
1196            assert!(a.accepts(&a_rx.try_recv().unwrap()));
1197            assert!(b.accepts(&b_rx.try_recv().unwrap()));
1198            WakeHandle::new().wake();
1199            assert!(matches!(a_rx.try_recv(), Err(TryRecvError::Empty)));
1200            assert!(matches!(b_rx.try_recv(), Err(TryRecvError::Empty)));
1201        }
1202
1203        {
1204            let (outer, rx) = bound_scope();
1205            let _outer = outer.enter();
1206            let detached = {
1207                let _detached = WakeScope::enter_detached();
1208                let handle = WakeHandle::new();
1209                handle.wake();
1210                handle
1211            };
1212            assert!(matches!(rx.try_recv(), Err(TryRecvError::Empty)));
1213            assert!(detached.authorize_publication());
1214            detached.wake();
1215            assert!(matches!(rx.try_recv(), Err(TryRecvError::Empty)));
1216            WakeHandle::new().wake();
1217            assert!(outer.accepts(&rx.try_recv().unwrap()));
1218        }
1219
1220        {
1221            let (outer, rx) = bound_scope();
1222            let _outer = outer.enter();
1223            let result = std::panic::catch_unwind(|| {
1224                let _detached = WakeScope::enter_detached();
1225                WakeHandle::new().wake();
1226                panic!("detached callback failed");
1227            });
1228            assert!(result.is_err());
1229            assert!(matches!(rx.try_recv(), Err(TryRecvError::Empty)));
1230            WakeHandle::new().wake();
1231            assert!(outer.accepts(&rx.try_recv().unwrap()));
1232        }
1233    }
1234
1235    #[test]
1236    fn settling_waits_for_every_owed_reply_to_be_taken_up() {
1237        let (scope, _wakes) = bound_scope();
1238        let handle = scope.handle();
1239        let queue = Arc::new(Mutex::new(Vec::new()));
1240        let mut taken = Vec::new();
1241
1242        let owed = handle.owe();
1243        assert!(handle.owes());
1244        let worker = {
1245            let queue = Arc::clone(&queue);
1246            std::thread::spawn(move || {
1247                queue.lock_recover().push(1);
1248                drop(owed);
1249            })
1250        };
1251        handle.settle(|| taken.append(&mut queue.lock_recover()));
1252        worker.join().unwrap();
1253        assert_eq!(taken, [1]);
1254        assert!(!handle.owes());
1255
1256        let mut owed = Some(handle.owe());
1257        let mut passes = 0;
1258        handle.settle(|| {
1259            passes += 1;
1260            taken.append(&mut queue.lock_recover());
1261            if let Some(owed) = owed.take() {
1262                let queue = Arc::clone(&queue);
1263                std::thread::spawn(move || {
1264                    queue.lock_recover().push(2);
1265                    drop(owed);
1266                })
1267                .join()
1268                .unwrap();
1269            }
1270        });
1271        assert_eq!((taken.as_slice(), passes), ([1, 2].as_slice(), 2));
1272
1273        let mut passes = 0;
1274        handle.settle(|| {
1275            passes += 1;
1276            handle.wake();
1277        });
1278        assert_eq!(passes, 1);
1279    }
1280
1281    #[test]
1282    fn an_owner_that_cannot_wait_asks_after_each_pass() {
1283        let (scope, _wakes) = bound_scope();
1284        let handle = scope.handle();
1285        assert!(handle.settled());
1286        let owed = handle.owe();
1287        handle.begin_pass();
1288        assert!(!handle.settled(), "a reply is owed");
1289        drop(owed);
1290        assert!(
1291            !handle.settled(),
1292            "the reply landed after the pass began: the next pass takes it up"
1293        );
1294        handle.begin_pass();
1295        assert!(handle.settled());
1296    }
1297
1298    #[test]
1299    fn a_closed_or_detached_scope_owes_nothing() {
1300        let mut passes = 0;
1301        let detached = WakeHandle::detached();
1302        let owed = detached.owe();
1303        assert!(!detached.owes());
1304        detached.settle(|| passes += 1);
1305        assert_eq!(passes, 1);
1306        drop(owed);
1307
1308        let (mut scope, _wakes) = bound_scope();
1309        let handle = scope.handle();
1310        let owed = handle.owe();
1311        let mut passes = 0;
1312        handle.settle(|| {
1313            passes += 1;
1314            scope.close();
1315        });
1316        assert_eq!(passes, 1);
1317        assert!(!handle.owes());
1318        assert!(scope.handle().owe().route.is_none());
1319        drop(owed);
1320    }
1321
1322    #[test]
1323    fn a_reply_wakes_the_scope_that_asked_once_answered() {
1324        let (scope, wakes) = bound_scope();
1325        let (answer, answers) = {
1326            let _entry = scope.enter();
1327            reply()
1328        };
1329        assert!(matches!(wakes.try_recv(), Err(TryRecvError::Empty)));
1330        std::thread::spawn(move || answer.send("picked"))
1331            .join()
1332            .unwrap();
1333        assert_eq!(answers.try_recv(), Ok("picked"));
1334        let wake = wakes.try_recv().unwrap();
1335        assert!(scope.accepts(&wake));
1336        assert!(wake.requires_sync());
1337
1338        let (answer, answers) = {
1339            let _entry = scope.enter();
1340            reply::<()>()
1341        };
1342        drop(answers);
1343        answer.send(());
1344        assert!(matches!(wakes.try_recv(), Err(TryRecvError::Empty)));
1345    }
1346}