Awesome
Rust Timeouts
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
Contents
Standard library
Crates
Standard Library
TcpStream
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)))?;
Crates
awc
let client = awc::Client::builder()
.timeout(Duration::from_secs(1))
.finish();
curl
let mut easy = curl::easy::Easy::new();
easy.connect_timeout(Duration::from_secs(1))?;
easy.timeout(Duration::from_secs(1))?;
elasticsearch
let transport = elasticsearch::http::transport::TransportBuilder::new(conn_pool)
.timeout(Duration::from_secs(1))
.build()?;
hyper
tokio::time::timeout(Duration::from_secs(1), client.get(uri)).await?;
postgres
let client = postgres::Config::new()
.connect_timeout(Duration::from_secs(1))
.connect(postgres::NoTls)?;
redis
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)))?;
reqwest
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(1))
.build()?;
or
let resp = client.get(url)
.timeout(Duration::from_secs(1))
.send()
.await?;
sqlx
let pool = sqlx::postgres::PgPoolOptions::new()
.acquire_timeout(Duration::from_secs(1))
.connect(uri)
.await?;
ureq
let agent = ureq::AgentBuilder::new()
.timeout_connect(Duration::from_secs(1))
.timeout_read(Duration::from_secs(1))
.timeout_write(Duration::from_secs(1))
.build();
Don’t see a library you use?
Let us know. Even better, create a pull request for it.
Running the Tests
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