Skip to main content

reth_tasks/
shutdown.rs

1//! Helper for shutdown signals
2
3use futures_util::FutureExt;
4use reth_concurrency::sync::{
5    atomic::{AtomicUsize, Ordering},
6    Arc,
7};
8use std::{
9    fmt,
10    future::Future,
11    pin::Pin,
12    task::{ready, Context, Poll, Waker},
13};
14use tokio::{
15    sync::{AcquireError, OwnedSemaphorePermit, Semaphore},
16    task::coop::unconstrained,
17};
18
19/// A Future that resolves when the shutdown event has been fired.
20#[derive(Debug)]
21pub struct GracefulShutdown {
22    shutdown: Shutdown,
23    guard: Option<GracefulShutdownGuard>,
24}
25
26impl GracefulShutdown {
27    pub(crate) const fn new(shutdown: Shutdown, guard: GracefulShutdownGuard) -> Self {
28        Self { shutdown, guard: Some(guard) }
29    }
30
31    /// Returns a new shutdown future that ignores the returned [`GracefulShutdownGuard`].
32    ///
33    /// This just maps the return value of the future to `()`, it does not drop the guard.
34    pub fn ignore_guard(self) -> impl Future<Output = ()> + Send + Sync + Unpin + 'static {
35        self.map(drop)
36    }
37}
38
39impl Future for GracefulShutdown {
40    type Output = GracefulShutdownGuard;
41
42    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
43        ready!(self.shutdown.poll_unpin(cx));
44        Poll::Ready(self.get_mut().guard.take().expect("Future polled after completion"))
45    }
46}
47
48impl Clone for GracefulShutdown {
49    fn clone(&self) -> Self {
50        Self {
51            shutdown: self.shutdown.clone(),
52            guard: self.guard.as_ref().map(|g| GracefulShutdownGuard::new(Arc::clone(&g.0))),
53        }
54    }
55}
56
57/// A guard that fires once dropped to signal the [`TaskManager`](crate::TaskManager) that the
58/// [`GracefulShutdown`] has completed.
59#[derive(Debug)]
60#[must_use = "if unused the task will not be gracefully shutdown"]
61pub struct GracefulShutdownGuard(Arc<AtomicUsize>);
62
63impl GracefulShutdownGuard {
64    pub(crate) fn new(counter: Arc<AtomicUsize>) -> Self {
65        counter.fetch_add(1, Ordering::SeqCst);
66        Self(counter)
67    }
68}
69
70impl Drop for GracefulShutdownGuard {
71    fn drop(&mut self) {
72        self.0.fetch_sub(1, Ordering::SeqCst);
73    }
74}
75
76/// A Future that resolves when the shutdown event has been fired.
77///
78/// Every task spawned on the runtime polls it before the task itself, so a poll by the task that
79/// is already waiting with the same waker only reads the semaphore's closed flag and takes no
80/// lock, except in `tokio_unstable` builds.
81pub struct Shutdown {
82    /// Closed when the signal fires. It never holds a permit, so a waiter only wakes on close.
83    ///
84    /// A Tokio primitive rather than a [`reth_concurrency::sync`] one: every spawned task polls a
85    /// [`Shutdown`], including tasks on native Tokio runtimes in `--cfg dst` builds, where the
86    /// simulated primitives only work inside a simulation.
87    semaphore: Arc<Semaphore>,
88    /// The pending acquire that keeps this handle's waker queued on the semaphore, and that
89    /// waker, once polled.
90    waiting: Option<(Acquire, Waker)>,
91}
92
93/// An acquire of the signal's semaphore, pending until the signal fires.
94type Acquire =
95    Pin<Box<dyn Future<Output = Result<OwnedSemaphorePermit, AcquireError>> + Send + Sync>>;
96
97impl Future for Shutdown {
98    type Output = ();
99
100    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
101        let this = self.get_mut();
102        if this.semaphore.is_closed() {
103            this.waiting = None;
104            return Poll::Ready(())
105        }
106        // A pending acquire has queued this waker. Under `tokio_unstable`, Tokio's taskdump can
107        // return `Pending` from the acquire without queueing it, so the acquire is polled again.
108        if !cfg!(tokio_unstable) &&
109            this.waiting.as_ref().is_some_and(|(_, waker)| waker.will_wake(cx.waker()))
110        {
111            return Poll::Pending
112        }
113
114        // Queues this handle's waker, or replaces the one it queued. The acquire ignores the coop
115        // budget: with the budget spent, Tokio returns `Pending` without queueing the waker, and
116        // the shortcut above would then never poll it again.
117        let mut acquire = match this.waiting.take() {
118            Some((acquire, _)) => acquire,
119            None => Box::pin(unconstrained(Arc::clone(&this.semaphore).acquire_owned())),
120        };
121        if acquire.as_mut().poll(cx).is_ready() {
122            // The semaphore never holds a permit, so the acquire only completes once closed.
123            return Poll::Ready(())
124        }
125        this.waiting = Some((acquire, cx.waker().clone()));
126        Poll::Pending
127    }
128}
129
130impl Clone for Shutdown {
131    fn clone(&self) -> Self {
132        Self { semaphore: Arc::clone(&self.semaphore), waiting: None }
133    }
134}
135
136impl fmt::Debug for Shutdown {
137    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138        f.debug_struct("Shutdown")
139            .field("fired", &self.semaphore.is_closed())
140            .field("waiting", &self.waiting.is_some())
141            .finish()
142    }
143}
144
145/// Shutdown signal that fires either manually or on drop
146#[derive(Debug)]
147pub struct Signal(Arc<Semaphore>);
148
149impl Signal {
150    /// Fire the signal manually.
151    pub fn fire(self) {
152        drop(self);
153    }
154}
155
156impl Drop for Signal {
157    fn drop(&mut self) {
158        // Wakes every queued handle, after releasing the semaphore's lock.
159        self.0.close();
160    }
161}
162
163/// Create a signal pair that's used to propagate shutdown event
164pub fn signal() -> (Signal, Shutdown) {
165    let semaphore = Arc::new(Semaphore::new(0));
166    (Signal(Arc::clone(&semaphore)), Shutdown { semaphore, waiting: None })
167}
168
169// These tests exercise native Tokio tasks and OS-thread shutdown, not logical workers.
170#[cfg(all(test, not(all(feature = "fuzz", dst))))]
171mod tests {
172    use super::*;
173    use futures_util::future::join_all;
174    use std::time::Duration;
175
176    #[tokio::test(flavor = "multi_thread")]
177    async fn test_shutdown() {
178        let (_signal, _shutdown) = signal();
179    }
180
181    #[tokio::test(flavor = "multi_thread")]
182    async fn test_drop_signal() {
183        let (signal, shutdown) = signal();
184
185        tokio::task::spawn(async move {
186            tokio::time::sleep(Duration::from_millis(500)).await;
187            drop(signal)
188        });
189
190        shutdown.await;
191    }
192
193    #[tokio::test(flavor = "multi_thread")]
194    async fn test_multi_shutdowns() {
195        let (signal, shutdown) = signal();
196
197        let mut tasks = Vec::with_capacity(100);
198        for _ in 0..100 {
199            let shutdown = shutdown.clone();
200            let task = tokio::task::spawn(async move {
201                shutdown.await;
202            });
203            tasks.push(task);
204        }
205
206        drop(signal);
207
208        join_all(tasks).await;
209    }
210
211    /// Counts how often it was woken.
212    #[derive(Default)]
213    struct CountWaker(AtomicUsize);
214
215    impl std::task::Wake for CountWaker {
216        fn wake(self: Arc<Self>) {
217            self.0.fetch_add(1, Ordering::SeqCst);
218        }
219    }
220
221    #[test]
222    fn test_shutdown_wakes_latest_waker() {
223        let (signal, mut shutdown) = signal();
224        let (first, second) = (Arc::new(CountWaker::default()), Arc::new(CountWaker::default()));
225        let second_waker = Waker::from(Arc::clone(&second));
226
227        assert!(shutdown
228            .poll_unpin(&mut Context::from_waker(&Waker::from(Arc::clone(&first))))
229            .is_pending());
230        // A task polled with a new waker replaces the one it registered.
231        assert!(shutdown.poll_unpin(&mut Context::from_waker(&second_waker)).is_pending());
232        signal.fire();
233
234        assert_eq!((first.0.load(Ordering::SeqCst), second.0.load(Ordering::SeqCst)), (0, 1));
235        assert!(shutdown.poll_unpin(&mut Context::from_waker(&second_waker)).is_ready());
236        // The resolved handle no longer holds the waker.
237        assert_eq!(Arc::strong_count(&second), 2);
238    }
239
240    /// A handle first polled after its task spent its coop budget still queues its waker, so the
241    /// signal wakes the task even when nothing else does.
242    #[tokio::test(flavor = "current_thread")]
243    async fn test_shutdown_polled_without_budget_wakes_on_signal() {
244        let (signal, mut shutdown) = signal();
245        let mut first_poll = true;
246        let task = tokio::spawn(std::future::poll_fn(move |cx| {
247            if std::mem::take(&mut first_poll) {
248                while std::pin::pin!(tokio::task::coop::consume_budget()).poll(cx).is_ready() {}
249            }
250            shutdown.poll_unpin(cx)
251        }));
252        for _ in 0..4 {
253            tokio::task::yield_now().await;
254        }
255        assert!(!task.is_finished());
256
257        signal.fire();
258        tokio::time::timeout(Duration::from_secs(5), task)
259            .await
260            .expect("the signal did not wake the task")
261            .unwrap();
262    }
263
264    /// A dropped handle takes its waker out of the semaphore's queue.
265    #[test]
266    fn test_dropped_shutdown_releases_its_waker() {
267        let (_signal, mut handle) = signal();
268        let counter = Arc::new(CountWaker::default());
269        let waker = Waker::from(Arc::clone(&counter));
270        assert!(handle.poll_unpin(&mut Context::from_waker(&waker)).is_pending());
271        assert!(Arc::strong_count(&counter) > 2);
272        drop(handle);
273        assert_eq!(Arc::strong_count(&counter), 2);
274    }
275
276    #[tokio::test(flavor = "multi_thread")]
277    async fn test_drop_signal_from_thread() {
278        let (signal, shutdown) = signal();
279
280        let _thread = std::thread::spawn(|| {
281            std::thread::sleep(Duration::from_millis(500));
282            drop(signal)
283        });
284
285        shutdown.await;
286    }
287}