Guarantee return value of serve, Pt. 2 (#3166)

This commit is contained in:
Sabrina Jewson 2025-01-10 21:02:31 +00:00 committed by GitHub
parent d07d129baf
commit 28c6be74ae
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -80,6 +80,12 @@ pub use self::listener::{Listener, ListenerExt, TapIo};
/// See also [`HandlerWithoutStateExt::into_make_service_with_connect_info`] and
/// [`HandlerService::into_make_service_with_connect_info`].
///
/// # Return Value
///
/// Although this future resolves to `io::Result<()>`, it will never actually complete or return an
/// error. Errors on the TCP socket will be handled by sleeping for a short while (currently, one
/// second).
///
/// [`Router`]: crate::Router
/// [`Router::into_make_service_with_connect_info`]: crate::Router::into_make_service_with_connect_info
/// [`MethodRouter`]: crate::routing::MethodRouter
@ -137,6 +143,11 @@ where
/// // ...
/// }
/// ```
///
/// # Return Value
///
/// Similarly to [`serve`], although this future resolves to `io::Result<()>`, it will never
/// error. It returns `Ok(())` only after the `signal` future completes.
pub fn with_graceful_shutdown<F>(self, signal: F) -> WithGracefulShutdown<L, M, S, F>
where
F: Future<Output = ()> + Send + 'static,
@ -255,6 +266,25 @@ where
type IntoFuture = private::ServeFuture;
fn into_future(self) -> Self::IntoFuture {
private::ServeFuture(Box::pin(async move {
self.run().await;
Ok(())
}))
}
}
#[cfg(all(feature = "tokio", any(feature = "http1", feature = "http2")))]
impl<L, M, S, F> WithGracefulShutdown<L, M, S, F>
where
L: Listener,
L::Addr: Debug,
M: for<'a> Service<IncomingStream<'a, L>, Error = Infallible, Response = S> + Send + 'static,
for<'a> <M as Service<IncomingStream<'a, L>>>::Future: Send,
S: Service<Request, Response = Response, Error = Infallible> + Clone + Send + 'static,
S::Future: Send,
F: Future<Output = ()> + Send + 'static,
{
async fn run(self) {
let Self {
mut listener,
mut make_service,
@ -262,7 +292,6 @@ where
_marker: _,
} = self;
private::ServeFuture(Box::pin(async move {
let (signal_tx, signal_rx) = watch::channel(());
let signal_tx = Arc::new(signal_tx);
tokio::spawn(async move {
@ -344,9 +373,6 @@ where
close_tx.receiver_count()
);
close_tx.closed().await;
Ok(())
}))
}
}