Skip to main content

coven_sync/
parks.rs

1//! Where a loop parks: each poll that finds nothing the loop waits on
2//! ready, told to a test.
3//!
4//! A loop's `select!` takes `polling` as its first branch and `parked` as
5//! its last, biased: `parked` is polled only after every branch before it
6//! was polled in the same poll and none was ready. Without test-utils both
7//! are never ready and count nothing. The loop holds `running` while it
8//! runs, so a test waiting for a park ends when the loop does.
9
10/// The parks of one loop.
11#[derive(Clone)]
12pub struct Parks {
13    #[cfg(any(test, feature = "test-utils"))]
14    inner: std::sync::Arc<ParkCounts>,
15}
16
17#[cfg(any(test, feature = "test-utils"))]
18struct ParkCounts {
19    /// Polls of the loop's `select!` begun so far.
20    polls: std::sync::atomic::AtomicU64,
21    /// The latest poll that parked, or `u64::MAX` once the loop has ended.
22    parked: tokio::sync::watch::Sender<u64>,
23    /// What polls the loop again.
24    waker: std::sync::Mutex<Option<std::task::Waker>>,
25}
26
27/// Held by the loop while it runs: dropped, it ends every wait for a park.
28pub struct LoopRunning<'a> {
29    #[cfg(any(test, feature = "test-utils"))]
30    parks: &'a Parks,
31    #[cfg(not(any(test, feature = "test-utils")))]
32    parks: std::marker::PhantomData<&'a Parks>,
33}
34
35impl Drop for LoopRunning<'_> {
36    fn drop(&mut self) {
37        #[cfg(any(test, feature = "test-utils"))]
38        self.parks.inner.parked.send_modify(|parked| *parked = u64::MAX);
39    }
40}
41
42impl Parks {
43    /// One loop's parks, none counted yet.
44    pub fn new() -> Self {
45        Self {
46            #[cfg(any(test, feature = "test-utils"))]
47            inner: std::sync::Arc::new(ParkCounts {
48                polls: std::sync::atomic::AtomicU64::new(0),
49                parked: tokio::sync::watch::channel(0).0,
50                waker: std::sync::Mutex::new(None),
51            }),
52        }
53    }
54
55    /// What the loop holds while it runs.
56    pub fn running(&self) -> LoopRunning<'_> {
57        #[cfg(any(test, feature = "test-utils"))]
58        return LoopRunning { parks: self };
59        #[cfg(not(any(test, feature = "test-utils")))]
60        LoopRunning { parks: std::marker::PhantomData }
61    }
62
63    /// The first branch of the loop's `select!`: a poll begins. Never ready.
64    pub fn polling(&self) -> impl std::future::Future<Output = std::convert::Infallible> + '_ {
65        #[cfg(any(test, feature = "test-utils"))]
66        return std::future::poll_fn(|context| {
67            self.inner.polls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
68            let mut waker = coven_foundation::locks::lock_unpoisoned(&self.inner.waker);
69            match &mut *waker {
70                Some(waker) => waker.clone_from(context.waker()),
71                None => *waker = Some(context.waker().clone()),
72            }
73            std::task::Poll::Pending
74        });
75        #[cfg(not(any(test, feature = "test-utils")))]
76        std::future::pending()
77    }
78
79    /// The last branch of the loop's `select!`: no branch before it was
80    /// ready in this poll. Never ready.
81    pub fn parked(&self) -> impl std::future::Future<Output = std::convert::Infallible> + '_ {
82        #[cfg(any(test, feature = "test-utils"))]
83        return std::future::poll_fn(|_| {
84            let poll = self.inner.polls.load(std::sync::atomic::Ordering::SeqCst);
85            self.inner.parked.send_modify(|parked| *parked = (*parked).max(poll));
86            std::task::Poll::Pending
87        });
88        #[cfg(not(any(test, feature = "test-utils")))]
89        std::future::pending()
90    }
91
92    /// Wait until the loop parks in a poll begun after this call, every
93    /// branch it waits on polled after whatever the caller did before and
94    /// none ready, or until it ends. The loop is polled once more for it,
95    /// as a spurious wake would, so a loop nothing has woken parks again.
96    #[cfg(any(test, feature = "test-utils"))]
97    pub fn parked_from_now(&self) -> impl std::future::Future<Output = ()> + Send + 'static {
98        let mut parked = self.inner.parked.subscribe();
99        let now = self.inner.polls.load(std::sync::atomic::Ordering::SeqCst);
100        if let Some(waker) = &*coven_foundation::locks::lock_unpoisoned(&self.inner.waker) {
101            waker.wake_by_ref();
102        }
103        async move {
104            coven_foundation::clock::within(parked.wait_for(|parked| *parked > now))
105                .await
106                .expect("the loop parks")
107                .expect("the loop's parks are kept");
108        }
109    }
110}