Skip to content

ankane/rust-timeouts

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

24 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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, Go, and PHP

Build Status

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)))?;

Returns std::io::Error

Crates

awc

let client = awc::Client::builder()
    .timeout(Duration::from_secs(1))
    .finish();

Returns awc::error::SendRequestError

curl

let mut easy = curl::easy::Easy::new();
easy.connect_timeout(Duration::from_secs(1))?;
easy.timeout(Duration::from_secs(1))?;

Returns curl::Error

elasticsearch

let transport = elasticsearch::http::transport::TransportBuilder::new(conn_pool)
    .timeout(Duration::from_secs(1))
    .build()?;

Returns elasticsearch::Error

hyper

tokio::time::timeout(Duration::from_secs(1), client.get(uri)).await?;

Returns tokio::time::error::Elapsed

postgres

let client = postgres::Config::new()
    .connect_timeout(Duration::from_secs(1))
    .connect(postgres::NoTls)?;

Returns postgres::Error

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)))?;

Returns redis::RedisError

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?;

Returns reqwest::Error

sqlx

let pool = sqlx::postgres::PgPoolOptions::new()
    .acquire_timeout(Duration::from_secs(1))
    .connect(uri)
    .await?;

Returns sqlx::Error

ureq

let config = ureq::Agent::config_builder()
    .timeout_global(Some(Duration::from_secs(1)))
    .build();

Returns ureq::Error

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

About

Timeouts for popular Rust crates

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages