Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WASM support in client via gloo-net #668

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions core-client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ http = ["jsonrpc-client-transports/http"]
ws = ["jsonrpc-client-transports/ws"]
ipc = ["jsonrpc-client-transports/ipc"]
arbitrary_precision = ["jsonrpc-client-transports/arbitrary_precision"]
wasmhttp = ["jsonrpc-client-transports/wasmhttp"]

[dependencies]
jsonrpc-client-transports = { version = "18.0.0", path = "./transports", default-features = false }
Expand Down
2 changes: 2 additions & 0 deletions core-client/transports/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ ipc = [
"jsonrpc-server-utils",
"tokio",
]
wasmhttp = ["gloo-net"]
arbitrary_precision = ["serde_json/arbitrary_precision", "jsonrpc-core/arbitrary_precision"]

[dependencies]
Expand All @@ -49,6 +50,7 @@ jsonrpc-server-utils = { version = "18.0.0", path = "../../server-utils", option
parity-tokio-ipc = { version = "0.9", optional = true }
tokio = { version = "1", optional = true }
websocket = { version = "0.26", optional = true }
gloo-net = { version = "0.1.0", optional = true, features=["http"] }

[dev-dependencies]
assert_matches = "1.1"
Expand Down
2 changes: 2 additions & 0 deletions core-client/transports/src/transports/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ pub mod ipc;
pub mod local;
#[cfg(feature = "ws")]
pub mod ws;
#[cfg(feature = "wasmhttp")]
pub mod wasmhttp;

pub use duplex::duplex;

Expand Down
80 changes: 80 additions & 0 deletions core-client/transports/src/transports/wasmhttp.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
//! HTTP client for wasm via gloo_net
use super::RequestBuilder;
use gloo_net::http;
use futures::{future, Future, FutureExt, StreamExt, TryFutureExt};
use crate::{RpcChannel, RpcError, RpcMessage, RpcResult};


/// Create a HTTP Client via gloo_net for wasm
pub async fn connect<TClient>(url: &str) -> RpcResult<(TClient, impl Future<Output = ()> + '_)>
where TClient: From<RpcChannel>
{
let max_parallel = 8;
// Keep track of internal request IDs when building subsequent requests
let mut request_builder = RequestBuilder::new();

let (sender, receiver) = futures::channel::mpsc::unbounded();

let fut = receiver
.filter_map(move |msg: RpcMessage| {
future::ready(match msg {
RpcMessage::Call(call) => {
let (_, request) = request_builder.call_request(&call);
Some((request, Some(call.sender)))
}
RpcMessage::Notify(notify) => Some((request_builder.notification(&notify), None)),
RpcMessage::Subscribe(_) => {
log::warn!("Unsupported `RpcMessage` type `Subscribe`.");
None
}
})
})
.map(move |(request, sender)| {
log::info!("got request {:?}", request);
let request = http::Request::post(&url)
.header(
"Content-Type",
"application/json",
)
.header(
"Accept",
"application/json",
)
.body(request);

request.send()
.then(|response| async move { (response, sender) })
})
.buffer_unordered(max_parallel)
.for_each(|(response, sender)| async {
let result = match response {
Ok(ref res) if !res.ok() => {
log::trace!("http result status {}", res.status());
Err(RpcError::Client(format!(
"Unexpected response status code: {}",
res.status()
)))
}
Err(err) => Err(RpcError::Other(Box::new(err))),
Ok(res) => {
res.binary()
.map_err(|e| RpcError::ParseError(e.to_string(), Box::new(e)))
.await
}
};

if let Some(sender) = sender {
let response = result
.and_then(|response| {
let response_str = String::from_utf8_lossy(response.as_ref()).into_owned();
super::parse_response(&response_str)
})
.and_then(|r| r.1);
if let Err(err) = sender.send(response) {
log::warn!("Error resuming asynchronous request: {:?}", err);
}
}
});

Ok((TClient::from(sender.into()), fut))
}