Skip to content

Question about cancel safety of request #3142

@hs-vc

Description

@hs-vc

Is it safe to reuse the hyper::Client object created for http2 after a request made by it is cancelled? For example, in the code below, is there any issue with reusing client after the fetch is cancelled by timeout in the test()? I am worried that the HTTP/2 client usually maintains a single connector and that reusing the client object after cancelling a request might result in unexpected behavior or that resources associated with the cancelled request might not be cleaned up properly.

use hyper::{body::HttpBody as _, Client, http, Uri};
use hyper::client::HttpConnector;
use hyper_tls::HttpsConnector;

type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;

async fn fetch(client: &Client<HttpsConnector<HttpConnector>>, url: Uri) -> Result<()> {
    let mut res = client.get(url).await?;

    println!("Response: {}", res.status());
    println!("Headers: {:#?}\n", res.headers());

    // Stream the body, writing each chunk to stdout as we get it
    // (instead of buffering and printing at the end).
    while let Some(next) = res.data().await {
        let chunk = next?;
        println!("{:?}", chunk);
    }
    Ok(())
}


async fn test() {
    let uri: Uri = "https://www.example.com".parse().unwrap();
    let client = Client::builder()
        .http2_only(true)
        .build::<_, hyper::Body>(hyper_tls::HttpsConnector::new());
    
    let _ = tokio::time::timeout(std::time::Duration::from_secs(10), fetch(&client, uri)).await;

    // Reuse the connection after the request may have been timed out
    do_something(client).await
}


async fn do_something(client: Client<HttpsConnector<HttpConnector>>) {
    // Do something with client
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions