Skip to content

Commit

Permalink
feat(client): Add a new config to set TCP_USER_TIMEOUT (#152)
Browse files Browse the repository at this point in the history
Setting TCP keepalive is not enough to prevent dead TCP connections.

See https://blog.cloudflare.com/when-tcp-sockets-refuse-to-die/
  • Loading branch information
guillaumebort authored Oct 1, 2024
1 parent fcb8565 commit 4dda024
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/client/legacy/connect/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ struct Config {
recv_buffer_size: Option<usize>,
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
interface: Option<String>,
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
tcp_user_timeout: Option<Duration>,
}

#[derive(Default, Debug, Clone, Copy)]
Expand Down Expand Up @@ -182,6 +184,8 @@ impl<R> HttpConnector<R> {
recv_buffer_size: None,
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
interface: None,
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
tcp_user_timeout: None,
}),
resolver,
}
Expand Down Expand Up @@ -324,6 +328,13 @@ impl<R> HttpConnector<R> {
self
}

/// Sets the value of the TCP_USER_TIMEOUT option on the socket.
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
#[inline]
pub fn set_tcp_user_timeout(&mut self, time: Option<Duration>) {
self.config_mut().tcp_user_timeout = time;
}

// private

fn config_mut(&mut self) -> &mut Config {
Expand Down Expand Up @@ -728,6 +739,13 @@ fn connect(
.map_err(ConnectError::m("tcp bind interface error"))?;
}

#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
if let Some(tcp_user_timeout) = &config.tcp_user_timeout {
if let Err(e) = socket.set_tcp_user_timeout(Some(*tcp_user_timeout)) {
warn!("tcp set_tcp_user_timeout error: {}", e);
}
}

bind_local_address(
&socket,
addr,
Expand Down Expand Up @@ -1138,6 +1156,12 @@ mod tests {
target_os = "linux"
))]
interface: None,
#[cfg(any(
target_os = "android",
target_os = "fuchsia",
target_os = "linux"
))]
tcp_user_timeout: None,
};
let connecting_tcp = ConnectingTcp::new(dns::SocketAddrs::new(addrs), &cfg);
let start = Instant::now();
Expand Down

0 comments on commit 4dda024

Please sign in to comment.