Skip to content

Commit a206a90

Browse files
committed
Add timeout to tcp connections
1 parent 29d17c7 commit a206a90

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

src/client.rs

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,18 @@ use byteorder::{BigEndian, ByteOrder};
1919
use retry::{delay::Fixed, retry};
2020
use std::io::{self, BufReader, BufWriter, Read};
2121
use std::net::TcpStream;
22+
use std::time::Duration;
23+
use std::{env, net::ToSocketAddrs};
24+
25+
const DEFAULT_CONNECTION_TIMEOUT: u64 = 20;
26+
27+
/// Get the time clients should try to connect to the server before continuing, in seconds.
28+
pub(crate) fn get_connection_timeout() -> u64 {
29+
env::var("SCCACHE_CONNECTION_TIMEOUT")
30+
.ok()
31+
.and_then(|s| s.parse().ok())
32+
.unwrap_or(DEFAULT_CONNECTION_TIMEOUT)
33+
}
2234

2335
/// A connection to an sccache server.
2436
pub struct ServerConnection {
@@ -65,7 +77,10 @@ impl ServerConnection {
6577
/// Establish a TCP connection to an sccache server listening on `port`.
6678
pub fn connect_to_server(port: u16) -> io::Result<ServerConnection> {
6779
trace!("connect_to_server({})", port);
68-
let stream = TcpStream::connect(("127.0.0.1", port))?;
80+
let stream = TcpStream::connect_timeout(
81+
&("127.0.0.1", port).to_socket_addrs()?.next().unwrap(),
82+
Duration::from_secs(get_connection_timeout()),
83+
)?;
6984
ServerConnection::new(stream)
7085
}
7186

src/dist/client_auth.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ use tokio::runtime::Runtime;
1515
use url::Url;
1616
use uuid::Uuid;
1717

18-
use crate::errors::*;
18+
use crate::{client::get_connection_timeout, errors::*};
1919

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

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

0 commit comments

Comments
 (0)