4
votes

I would like to compile the following code with cargo-wasi.

// reqwest = { version = "0.11", features = ["json"] }
// tokio = { version = "1", features = ["full"] }

use std::collections::HashMap;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let resp = reqwest::get("https://httpbin.org/ip")
        .await?
        .json::<HashMap<String, String>>()
        .await?;
    println!("{:#?}", resp);
    Ok(())
}

After trying to compile it, I got the following error because mio doesn't currently support WASI

$ cargo wasi run
   Compiling mio v0.7.9
   Compiling parking_lot v0.11.1
   Compiling serde_json v1.0.64
   Compiling idna v0.2.2
error[E0432]: unresolved import `crate::sys::IoSourceState`
  --> /home/ducaale/.cargo/registry/src/github.com-1ecc6299db9ec823/mio-0.7.9/src/io_source.rs:12:5
   |
12 | use crate::sys::IoSourceState;
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^ no `IoSourceState` in `sys`
... errors omitted

I did some research and none of the examples I found so far were utilizing async/await. Is there something I could replace tokio with so my code compiles in WASI?

1

1 Answers

3
votes

I tried running this and it seems the reqwests crate doesn't build correctly with cargo wasi or wasm-pack because it's unable to compile mio (which is used by tokio when compiling natively). There is some mention on github that reqwests can be used with wasm, but it's not yet fully supported, and I couldn't find much on how to make it work. It sounds like there isn't much solution yet for HTTP requests on WASI at this time, but web-sys can be used to make requests through Node.js or a browser.

It appears that tokio requires specific features flags in order to be used with web assembly. This issue mentions the sync and rt flags at the bottom: https://github.com/tokio-rs/tokio/issues/1597 but in order to also use #[tokio:main], you will need the "rt-multi-thread" and "macros" feature flags as well.

It might also be possible to use wasm bindgen to convert the future into a promise, but that might not work with WASI: https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen_futures/