Skip to content

Commit

Permalink
Add timeout to tcp connections
Browse files Browse the repository at this point in the history
  • Loading branch information
Systemcluster committed Jul 29, 2024
1 parent 29d17c7 commit a206a90
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
17 changes: 16 additions & 1 deletion src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,18 @@ use byteorder::{BigEndian, ByteOrder};
use retry::{delay::Fixed, retry};
use std::io::{self, BufReader, BufWriter, Read};
use std::net::TcpStream;
use std::time::Duration;
use std::{env, net::ToSocketAddrs};

const DEFAULT_CONNECTION_TIMEOUT: u64 = 20;

/// Get the time clients should try to connect to the server before continuing, in seconds.
pub(crate) fn get_connection_timeout() -> u64 {
env::var("SCCACHE_CONNECTION_TIMEOUT")
.ok()
.and_then(|s| s.parse().ok())
.unwrap_or(DEFAULT_CONNECTION_TIMEOUT)
}

/// A connection to an sccache server.
pub struct ServerConnection {
Expand Down Expand Up @@ -65,7 +77,10 @@ impl ServerConnection {
/// Establish a TCP connection to an sccache server listening on `port`.
pub fn connect_to_server(port: u16) -> io::Result<ServerConnection> {
trace!("connect_to_server({})", port);
let stream = TcpStream::connect(("127.0.0.1", port))?;
let stream = TcpStream::connect_timeout(
&("127.0.0.1", port).to_socket_addrs()?.next().unwrap(),
Duration::from_secs(get_connection_timeout()),
)?;
ServerConnection::new(stream)
}

Expand Down
4 changes: 2 additions & 2 deletions src/dist/client_auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use tokio::runtime::Runtime;
use url::Url;
use uuid::Uuid;

use crate::errors::*;
use crate::{client::get_connection_timeout, errors::*};

// These (arbitrary) ports need to be registered as valid redirect urls in the oauth provider you're using
pub const VALID_PORTS: &[u16] = &[12731, 32492, 56909];
Expand Down Expand Up @@ -503,7 +503,7 @@ async fn try_bind() -> Result<HyperBuilderWrap> {
.expect("Expected at least one address in parsed socket address");

// Hyper binds with reuseaddr and reuseport so binding won't fail as you'd expect on Linux
match TcpStream::connect(addr) {
match TcpStream::connect_timeout(&addr, Duration::from_secs(get_connection_timeout())) {
// Already open
Ok(_) => continue,
// Doesn't seem to be open
Expand Down

0 comments on commit a206a90

Please sign in to comment.