An unresponsive service can be worse than a down one. It can tie up your entire system if not handled properly. All network requests should have a timeout.
Here’s how to add timeouts for popular Rust crates. All have been tested. The default is no timeout, unless otherwise specified. Enjoy!
Also available for Ruby, Python, Node, and Go
Standard library
Crates
let mut stream = std::net::TcpStream::connect_timeout(&addr, Duration::from_secs(1))?;
stream.set_read_timeout(Some(Duration::from_secs(1)))?;
stream.set_write_timeout(Some(Duration::from_secs(1)))?;
let client = awc::Client::builder()
.timeout(Duration::from_secs(1))
.finish();
let mut easy = curl::easy::Easy::new();
easy.connect_timeout(Duration::from_secs(1))?;
easy.timeout(Duration::from_secs(1))?;
let transport = elasticsearch::http::transport::TransportBuilder::new(conn_pool)
.timeout(Duration::from_secs(1))
.build()?;
tokio::time::timeout(Duration::from_secs(1), client.get(uri)).await?;
let client = postgres::Config::new()
.connect_timeout(Duration::from_secs(1))
.connect(postgres::NoTls)?;
let mut con = client.get_connection_with_timeout(Duration::from_secs(1))?;
con.set_read_timeout(Some(Duration::from_secs(1)))?;
con.set_write_timeout(Some(Duration::from_secs(1)))?;
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(1))
.build()?;
or
let resp = client.get(url)
.timeout(Duration::from_secs(1))
.send()
.await?;
let pool = sqlx::postgres::PgPoolOptions::new()
.acquire_timeout(Duration::from_secs(1))
.connect(uri)
.await?;
let agent = ureq::AgentBuilder::new()
.timeout_connect(Duration::from_secs(1))
.timeout_read(Duration::from_secs(1))
.timeout_write(Duration::from_secs(1))
.build();
Let us know. Even better, create a pull request for it.
git clone https://github.com/ankane/rust-timeouts.git
cd rust-timeouts
To run all tests, use:
cargo test
To run individual tests, use:
cargo test redis