rocket/
shutdown.rs

1use std::future::Future;
2use std::task::{Context, Poll};
3use std::pin::Pin;
4
5use futures::FutureExt;
6
7use crate::request::{FromRequest, Outcome, Request};
8use crate::trip_wire::TripWire;
9
10/// A request guard and future for graceful shutdown.
11///
12/// A server shutdown is manually requested by calling [`Shutdown::notify()`]
13/// or, if enabled, through [automatic triggers] like `Ctrl-C`. Rocket will stop accepting new
14/// requests, finish handling any pending requests, wait a grace period before
15/// cancelling any outstanding I/O, and return `Ok()` to the caller of
16/// [`Rocket::launch()`]. Graceful shutdown is configured via
17/// [`config::Shutdown`](crate::config::Shutdown).
18///
19/// [`Rocket::launch()`]: crate::Rocket::launch()
20/// [automatic triggers]: crate::config::Shutdown#triggers
21///
22/// # Detecting Shutdown
23///
24/// `Shutdown` is also a future that resolves when [`Shutdown::notify()`] is
25/// called. This can be used to detect shutdown in any part of the application:
26///
27/// ```rust
28/// # use rocket::*;
29/// use rocket::Shutdown;
30///
31/// #[get("/wait/for/shutdown")]
32/// async fn wait_for_shutdown(shutdown: Shutdown) -> &'static str {
33///     shutdown.await;
34///     "Somewhere, shutdown was requested."
35/// }
36/// ```
37///
38/// See the [`stream`](crate::response::stream#graceful-shutdown) docs for an
39/// example of detecting shutdown in an infinite responder.
40///
41/// Additionally, a completed shutdown request resolves the future returned from
42/// [`Rocket::launch()`](crate::Rocket::launch()):
43///
44/// ```rust,no_run
45/// # #[macro_use] extern crate rocket;
46/// #
47/// use rocket::Shutdown;
48///
49/// #[get("/shutdown")]
50/// fn shutdown(shutdown: Shutdown) -> &'static str {
51///     shutdown.notify();
52///     "Shutting down..."
53/// }
54///
55/// #[rocket::main]
56/// async fn main() {
57///     let result = rocket::build()
58///         .mount("/", routes![shutdown])
59///         .launch()
60///         .await;
61///
62///     // If the server shut down (by visiting `/shutdown`), `result` is `Ok`.
63///     result.expect("server failed unexpectedly");
64/// }
65/// ```
66#[derive(Debug, Clone)]
67#[must_use = "`Shutdown` does nothing unless polled or `notify`ed"]
68pub struct Shutdown(pub(crate) TripWire);
69
70impl Shutdown {
71    /// Notify the application to shut down gracefully.
72    ///
73    /// This function returns immediately; pending requests will continue to run
74    /// until completion or expiration of the grace period, which ever comes
75    /// first, before the actual shutdown occurs. The grace period can be
76    /// configured via [`Shutdown::grace`](crate::config::Shutdown::grace).
77    ///
78    /// ```rust
79    /// # use rocket::*;
80    /// use rocket::Shutdown;
81    ///
82    /// #[get("/shutdown")]
83    /// fn shutdown(shutdown: Shutdown) -> &'static str {
84    ///     shutdown.notify();
85    ///     "Shutting down..."
86    /// }
87    /// ```
88    #[inline]
89    pub fn notify(self) {
90        self.0.trip();
91    }
92}
93
94#[crate::async_trait]
95impl<'r> FromRequest<'r> for Shutdown {
96    type Error = std::convert::Infallible;
97
98    #[inline]
99    async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
100        Outcome::Success(request.rocket().shutdown())
101    }
102}
103
104impl Future for Shutdown {
105    type Output = ();
106
107    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
108        self.0.poll_unpin(cx)
109    }
110}
111
112#[cfg(test)]
113mod tests {
114    use super::Shutdown;
115
116    #[test]
117    fn ensure_is_send_sync_clone_unpin() {
118        fn is_send_sync_clone_unpin<T: Send + Sync + Clone + Unpin>() {}
119        is_send_sync_clone_unpin::<Shutdown>();
120    }
121}