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