Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(transport): Add server graceful shutdown #169

Merged
merged 8 commits into from
Dec 11, 2019
Merged
35 changes: 30 additions & 5 deletions tonic/src/transport/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ pub struct Server {
init_connection_window_size: Option<u32>,
max_concurrent_streams: Option<u32>,
tcp_keepalive: Option<Duration>,
shutdown: Option<Arc<dyn Future<Output = ()>>>,
tcp_nodelay: bool,
}

Expand Down Expand Up @@ -110,6 +111,26 @@ impl Server {
}
}

/// Prepares the server to handle graceful shutdown when the future completes
///
/// ```
/// # use tonic::transport::Server;
/// # use tower_service::Service;
/// # let mut builder = Server::builder();
/// let (tx, rx) = tokio::sync::oneshot::channel::<()>();
/// builder.graceful_shutdown(async {
/// rx.await.ok();
/// });
///
/// let _ = tx.send(());
/// ```
pub fn graceful_shutdown<F: 'static + Future<Output = ()>>(self, shutdown: F) -> Self {
Server {
shutdown: Some(Arc::new(shutdown)),
..self
}
}

// FIXME: tower-timeout currentlly uses `From` instead of `Into` for the error
// so our services do not align.
// pub fn timeout(&mut self, timeout: Duration) -> &mut Self {
Expand Down Expand Up @@ -268,15 +289,19 @@ impl Server {
concurrency_limit,
// timeout,
};
xd009642 marked this conversation as resolved.
Show resolved Hide resolved

hyper::Server::builder(incoming)
let serve_fut = hyper::server::builder(incoming)
.http2_only(true)
.http2_initial_connection_window_size(init_connection_window_size)
.http2_initial_stream_window_size(init_stream_window_size)
.http2_max_concurrent_streams(max_concurrent_streams)
.serve(svc)
.await
.map_err(map_err)?;
.serve(svc);

let final_fut = match self.shutdown {
Some(rx) => serve_fut.with_graceful_shutdown(rx),
None => serve_fut,
};

final_fut.await.map_err(map_err)?;

Ok(())
}
Expand Down