Skip to content

Commit

Permalink
feat(transport): Expose http2 keep-alive support (#307)
Browse files Browse the repository at this point in the history
  • Loading branch information
Michael-J-Ward authored Mar 29, 2020
1 parent 5758b75 commit 012fa3c
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
30 changes: 30 additions & 0 deletions tonic/src/transport/channel/endpoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ pub struct Endpoint {
pub(crate) init_connection_window_size: Option<u32>,
pub(crate) tcp_keepalive: Option<Duration>,
pub(crate) tcp_nodelay: bool,
pub(crate) http2_keep_alive_interval: Option<Duration>,
pub(crate) http2_keep_alive_timeout: Option<Duration>,
pub(crate) http2_keep_alive_while_idle: Option<bool>,
}

impl Endpoint {
Expand Down Expand Up @@ -167,6 +170,30 @@ impl Endpoint {
}
}

/// Set http2 KEEP_ALIVE_INTERVAL. Uses `hyper`'s default otherwise.
pub fn http2_keep_alive_interval(self, interval: Duration) -> Self {
Endpoint {
http2_keep_alive_interval: Some(interval),
..self
}
}

/// Set http2 KEEP_ALIVE_TIMEOUT. Uses `hyper`'s default otherwise.
pub fn keep_alive_timeout(self, duration: Duration) -> Self {
Endpoint {
http2_keep_alive_timeout: Some(duration),
..self
}
}

/// Set http2 KEEP_ALIVE_WHILE_IDLE. Uses `hyper`'s default otherwise.
pub fn keep_alive_while_idle(self, enabled: bool) -> Self {
Endpoint {
http2_keep_alive_while_idle: Some(enabled),
..self
}
}

/// Create a channel from this config.
pub async fn connect(&self) -> Result<Channel, Error> {
let mut http = hyper::client::connect::HttpConnector::new();
Expand Down Expand Up @@ -215,6 +242,9 @@ impl From<Uri> for Endpoint {
init_connection_window_size: None,
tcp_keepalive: None,
tcp_nodelay: true,
http2_keep_alive_interval: None,
http2_keep_alive_timeout: None,
http2_keep_alive_while_idle: None,
}
}
}
Expand Down
13 changes: 12 additions & 1 deletion tonic/src/transport/service/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,23 @@ impl Connection {
C::Future: Unpin + Send,
C::Response: AsyncRead + AsyncWrite + HyperConnection + Unpin + Send + 'static,
{
let settings = Builder::new()
let mut settings = Builder::new()
.http2_initial_stream_window_size(endpoint.init_stream_window_size)
.http2_initial_connection_window_size(endpoint.init_connection_window_size)
.http2_only(true)
.http2_keep_alive_interval(endpoint.http2_keep_alive_interval)
.clone();

if let Some(val) = endpoint.http2_keep_alive_timeout {
settings.http2_keep_alive_timeout(val);
}

if let Some(val) = endpoint.http2_keep_alive_while_idle {
settings.http2_keep_alive_while_idle(val);
}

let settings = settings.clone();

let stack = ServiceBuilder::new()
.layer_fn(|s| AddOrigin::new(s, endpoint.uri.clone()))
.optional_layer(endpoint.timeout.map(TimeoutLayer::new))
Expand Down

0 comments on commit 012fa3c

Please sign in to comment.