From 7e5b82f31a89fd72a1d12259090eb1196fa9ebe3 Mon Sep 17 00:00:00 2001 From: Radu M Date: Fri, 5 Mar 2021 23:17:23 -0800 Subject: [PATCH] Spawn new blocking executor for sending the HTTP request in Tokio Signed-off-by: Radu M --- .../src/lib.rs | 41 ++++++++++++------- 1 file changed, 26 insertions(+), 15 deletions(-) diff --git a/crates/wasi-experimental-http-wasmtime/src/lib.rs b/crates/wasi-experimental-http-wasmtime/src/lib.rs index c2f2b4e..79430c5 100644 --- a/crates/wasi-experimental-http-wasmtime/src/lib.rs +++ b/crates/wasi-experimental-http-wasmtime/src/lib.rs @@ -174,22 +174,33 @@ fn request( body: Vec, ) -> Result<(u16, HeaderMap, Bytes), Error> { match Handle::try_current() { - Ok(_) => { + Ok(r) => { + // If running in a Tokio runtime, spawn a new blocking executor + // that will send the HTTP request, and block on its execution. + // This attempts to avoid any deadlocks from other operations + // already executing on the same executor (compared with just + // blocking on the current one). + // + // This should only be a temporary workaround, until we take + // advantage of async functions in Wasmtime. + println!("wasi_experimental_http::request: tokio runtime available"); - let client = Client::builder().build().unwrap(); - let res = block_on( - client - .request(method, &url) - .headers(headers) - .body(body) - .send(), - )?; + block_on(r.spawn_blocking(move || { + let client = Client::builder().build().unwrap(); + let res = block_on( + client + .request(method, &url) + .headers(headers) + .body(body) + .send(), + )?; - return Ok(( - res.status().as_u16(), - res.headers().clone(), - block_on(res.bytes())?, - )); + return Ok(( + res.status().as_u16(), + res.headers().clone(), + block_on(res.bytes())?, + )); + }))? } Err(_) => { println!("wasi_experimental_http::request: no Tokio runtime available"); @@ -200,7 +211,7 @@ fn request( .send()?; return Ok((res.status().as_u16(), res.headers().clone(), res.bytes()?)); } - }; + } } /// Get the URL, method, request body, and headers from the