1use 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#[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 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#[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
76pub struct Shutdown {
82 semaphore: Arc<Semaphore>,
88 waiting: Option<(Acquire, Waker)>,
91}
92
93type 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 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 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 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#[derive(Debug)]
147pub struct Signal(Arc<Semaphore>);
148
149impl Signal {
150 pub fn fire(self) {
152 drop(self);
153 }
154}
155
156impl Drop for Signal {
157 fn drop(&mut self) {
158 self.0.close();
160 }
161}
162
163pub fn signal() -> (Signal, Shutdown) {
165 let semaphore = Arc::new(Semaphore::new(0));
166 (Signal(Arc::clone(&semaphore)), Shutdown { semaphore, waiting: None })
167}
168
169#[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 #[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 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 assert_eq!(Arc::strong_count(&second), 2);
238 }
239
240 #[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 #[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}