r/rust•
CrystalDev

HTTP2 request using the await syntax

Hello everyone,

I am going to apologize for the amount of code I am going to post in advance. I have been struggling for the past 2 weeks on setting up an HTTP2 connection using h2. I tried to follow the Akamai example in the h2 folder and I could get the example working. But I'd like to try the new async syntax so I tried my best on converting the example:

My code so far:

#![feature(async_await)]

use tokio::net::TcpStream;
use std::sync::Arc;
use webpki::DNSNameRef;
use futures::compat::Future01CompatExt;
use futures::future::{FutureExt, TryFutureExt};
use h2::client;
use rustls::ClientConfig;
use tokio_rustls::ClientConfigExt;

use rustls::Session;

use std::net::ToSocketAddrs;
use hyper::{Method, Request};

pub fn setup_config() -> Arc<ClientConfig>
{
    std::sync::Arc::new({
        let mut c = rustls::ClientConfig::new();
        c.root_store
            .add_server_trust_anchors(&webpki_roots::TLS_SERVER_ROOTS);
        c.alpn_protocols.push("h2".to_owned());
        c
    })
}

pub async fn worker()
{
    // Set the address to run our socket on.
    let address = "http2.akamai.com:443"
        .to_socket_addrs()
        .unwrap()
        .next()
        .unwrap();

    let config = setup_config();

    let dns_name = DNSNameRef::try_from_ascii_str("http2.akamai.com").unwrap();

    // Open a TCP connection.
    let tcp = TcpStream::connect(&address).compat().await.unwrap();
    ;

    let tls = config.connect_async(dns_name, tcp).compat().await.unwrap();

    let (_, session) = tls.get_ref();
    let negotiated_protocol = session.get_alpn_protocol();
    assert_eq!(Some("h2"), negotiated_protocol.as_ref().map(|x| &**x));

    let res = client::handshake(tls).compat().await;

    let (client, h2) = res.unwrap();

    println!("Test5");
    let request = Request::builder()
        .method(Method::GET)
        .uri("https://http2.akamai.com/")
        .body(())
        .unwrap();

    println!("Test6");

    let (response, x) = client.ready().compat().await.unwrap().send_request(request, true).unwrap();
    println!("Test7");

    let response = response.compat().await;
    println!("Test8");
}

fn main()
{
    // Call our `run_server` function, which returns a future.
    // As with every `async fn`, for `run_server` to do anything,
    // the returned future needs to be run. Additionally,
    // we need to convert the returned future from a futures 0.3 future into a
    // futures 0.1 future.
    let futures_03_future = worker();
    let futures_01_future = futures_03_future.unit_error().boxed().compat();

    // Finally, we can run the future to completion using the `run` function
    // provided by Hyper.
    tokio::run(futures_01_future);
}

Cargo.toml

[dependencies]
# The latest version of the "futures" library, which has lots of utilities
# for writing async code. Enable the "compat" feature to include the
# functions for using futures 0.3 and async/await with the Hyper library,
# which use futures 0.1.
futures-preview = { version = "=0.3.0-alpha.16", features = ["compat"] }

# Hyper is an asynchronous HTTP library. We'll use it to power our HTTP
# server and to make HTTP requests.
hyper = "0.12.9"

# Tokio
tokio = "0.1.22"
h2 = "0.1.26"

# RustTLS
rustls = "0.12"
tokio-rustls = "0.5.0"
webpki = "0.18"
webpki-roots = "0.14"

For some reason my code does not get past Test7, but I just fail to understand why.

I hope you guys can give me some pointers!

​

EDIT:

I received a response at the h2 repository: https://github.com/hyperium/h2/issues/390

I was able to get a working example but was unable to process larger request bodies back. I filed a new issue for that: https://github.com/hyperium/h2/issues/391

Posted Jul 31, 2019, 3:00 PM UTC · edited

2718
RustDragon•

I tried playing around with it a bit, and I agree that it seems like this should work when it doesn't.

I interpret the h2 docs as requiring you drop x before awaiting on the response, but dropping it doesn't change the behavior.

2
CrystalDevOP•

I glad I am not the only one :) The strange part is that I feel like this should do exactly what the example does.

I checked Wireshark but no request has been sent. So it's definitly something client side

1
WellMakeItSomehow•

Yup, I haven't used h2, but your code looks legit. Maybe you can try to minimize it, then file an issue?

3
CrystalDevOP•

I just did today! Thanks for the suggestion!

2
WellMakeItSomehow•

<3

1
davemilter•

I just did today! Thanks for the suggestion!

link for issue would be great

1
CrystalDevOP•

https://github.com/hyperium/h2/issues/390

I didn't receive any reply so far however :)

3
CrystalDevOP•

In meanwhile I was able to get answers to both issues filed! And I was able to get some working code. Might anyone be interested I can post it here. (not sure what the standard procedure is for that? Edit the original question or do it inside a reply?) The only trouble I am working on right now is getting tokio to not skip old tasks when spawning many tasks :) (I am working on a Certificate Transparancy Log scraper)

1
[deleted]•

[removed]

-21
RustDragon•

This isn't really a helpful response to someone who is frustrated with code not working.

Anyways, you missed the only two things in the current language that are handled in the "ptr" module... *mut T and *const T. Also the best box syntax, box T.

7
nawfel_bgh•

Thanks! I wasn't sure about *const and didn't know *mut is a thing. box T doesn't count because it doesn't name a pointer type.

1
RustDragon•

~T changed to box T changed to Box<T> as I recall my rust history...

1
nawfel_bgh•

The purpous of the box (or placement new) syntax is to allocate an instance of some smart pointer type, supplied or inferred from the context, and to write the object value directly to the allocated memory without an intermediary move.

I don't know if this is still planned or abondonned.

2
Sirflankalot•

Excuse me what?

1
nawfel_bgh•

Some pointers... POINTERS!

-7