1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
use std::{
borrow::Cow,
error::Error as StdError,
fmt::{self, Display, Formatter},
ops::Not,
task::{Context, Poll},
};
use bytes::{Buf, Bytes, BytesMut};
use futures_util::{future::LocalBoxFuture, Future, FutureExt, Stream, StreamExt};
use http::{header, HeaderMap, HeaderValue, Uri};
use js_sys::Uint8Array;
use prost::Message;
use reqwasm::http::Request as WasmRequest;
use tower::Service;
use wasm_bindgen::{JsCast, UnwrapThrowExt};
use super::{check_uri, map_scheme_to_ws, InvalidServerUrl};
use crate::{
body::Body,
client::{
transport::{is_socket_request, SocketChannels, TransportError},
ClientError,
},
common::transport::{
http::{version_header_name, ws_version, HRPC_VERSION_HEADER},
ws_wasm::WebSocket,
},
proto::Error as HrpcError,
request::{self, BoxRequest},
response::{self, BoxResponse},
BoxError, Response, HRPC_CONTENT_MIMETYPE, HRPC_SPEC_VERSION,
};
#[derive(Debug, Clone)]
pub struct Wasm {
server: Uri,
check_spec_version: bool,
}
impl Wasm {
pub fn new(server: Uri) -> Result<Self, WasmError> {
Ok(Self {
server: check_uri(server).map_err(WasmError::InvalidServerUrl)?,
check_spec_version: true,
})
}
pub fn check_spec_version(mut self, enabled: bool) -> Self {
self.check_spec_version = enabled;
self
}
}
impl Service<BoxRequest> for Wasm {
type Response = BoxResponse;
type Error = TransportError<WasmError>;
type Future = CallFuture;
fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Ok(()).into()
}
fn call(&mut self, req: BoxRequest) -> Self::Future {
if is_socket_request(&req) {
let request::Parts {
mut extensions,
endpoint,
..
} = req.into();
let scheme =
map_scheme_to_ws(self.server.scheme_str().expect_throw("must have scheme"))
.expect_throw("scheme can't be anything other than https or http");
let url = format!(
"{}://{}:{}/{}",
scheme,
self.server
.host()
.expect_throw("expected host on server URI, this is a bug"),
self.server
.port_u16()
.expect_throw("expected port on server URI, this is a bug"),
endpoint.trim_start_matches('/'),
);
let sock_protocols = extensions
.remove::<SocketProtocols>()
.map_or_else(|| vec![Cow::Owned(ws_version())], |s| s.protocols);
let inner = Box::pin(async move {
let protocols = Some(sock_protocols.iter().map(|s| s.as_ref()).collect());
let (_, ws_stream) = ws_stream_wasm::WsMeta::connect(url, protocols)
.await
.map_err(WasmError::SocketInitError)?;
let ws = WebSocket::new(ws_stream);
let (ws_tx, ws_rx) = ws.split();
let chans = SocketChannels::new(ws_tx, ws_rx);
let mut resp = BoxResponse::empty();
resp.extensions_mut().insert(chans);
Ok(resp)
});
CallFuture { inner }
} else {
let request::Parts {
body,
mut extensions,
endpoint,
} = req.into();
let req_url = format!("{}{}", self.server, endpoint.trim_start_matches('/'));
let mut request = WasmRequest::post(req_url.as_str());
request = request
.header(HRPC_VERSION_HEADER, HRPC_SPEC_VERSION)
.header(header::CONTENT_TYPE.as_str(), HRPC_CONTENT_MIMETYPE);
if let Some(header_map) = extensions.remove::<HeaderMap>() {
for (key, value) in header_map.iter() {
if let Ok(value) = value.to_str() {
request = request.header(key.as_str(), value);
}
}
}
let check_spec_version = self.check_spec_version;
let inner = Box::pin(async move {
let mut data = body.aggregate().await.map_err(WasmError::BodyError)?;
request = request.body({
let buf = Uint8Array::new_with_length(
data.remaining()
.try_into()
.expect_throw("can't send data bigger than a u32"),
);
let mut offset = 0;
while data.has_remaining() {
let chunk_len = {
let chunk = data.chunk();
unsafe { buf.set(&Uint8Array::view(chunk), offset) }
chunk.len()
};
let chunk_len_js: u32 = chunk_len
.try_into()
.expect_throw("can't send data bigger than a u32");
offset += chunk_len_js;
data.advance(chunk_len);
}
buf
});
let response = request.send().await.map_err(WasmError::HttpError)?;
let status = http::StatusCode::from_u16(response.status())
.expect_throw("got invalid status code from response");
if status.is_success().not() {
let raw_error = response.binary().await.map_err(WasmError::HttpError)?;
let hrpc_error = HrpcError::decode(raw_error.as_ref())
.unwrap_or_else(|_| HrpcError::invalid_hrpc_error(raw_error));
return Err((ClientError::EndpointError {
hrpc_error,
endpoint,
})
.into());
}
let mut resp = Response::empty();
let content_type = response
.headers()
.get(header::CONTENT_TYPE.as_str())
.expect_throw("header name is valid");
if !content_type
.as_ref()
.and_then(|v| v.split(';').next())
.map_or(false, |v| v == HRPC_CONTENT_MIMETYPE)
{
return Err(ClientError::ContentNotSupported.into());
}
if let Some(value) = content_type.and_then(|v| HeaderValue::from_str(&v).ok()) {
resp.get_or_insert_header_map()
.insert(header::CONTENT_TYPE, value);
}
let hrpc_version = response
.headers()
.get(HRPC_VERSION_HEADER)
.expect_throw("header name is valid");
if check_spec_version
&& hrpc_version
.as_ref()
.map_or(false, |v| v == HRPC_SPEC_VERSION)
.not()
{
return Err(ClientError::IncompatibleSpecVersion.into());
}
if let Some(value) = hrpc_version.and_then(|v| HeaderValue::from_str(&v).ok()) {
resp.get_or_insert_header_map()
.insert(version_header_name(), value);
}
resp.extensions_mut().insert(status);
let body = wasm_streams::ReadableStream::from_raw(
response
.body()
.expect_throw("response body was used before we used it -- this is a bug")
.dyn_into()
.expect_throw("failed to get body from response"),
);
let body = body.into_stream().map(|buf_js| {
let buffer = Uint8Array::new(&buf_js.map_err(|_| {
Box::new(HrpcError::from((
"hrpcrs.wasm.body-error",
"error occured while streaming response body",
)))
})?);
let mut bytes = BytesMut::with_capacity(buffer.length() as usize);
buffer.copy_to(&mut bytes);
Ok(bytes.freeze())
});
let resp = Response::from(response::Parts {
body: Body::new(SendSyncBody { inner: body }),
..response::Parts::from(resp)
});
Ok(resp)
});
CallFuture { inner }
}
}
}
pub struct SocketProtocols {
protocols: Vec<Cow<'static, str>>,
}
impl SocketProtocols {
pub fn new(protocols: impl Into<Vec<Cow<'static, str>>>) -> Self {
Self {
protocols: protocols.into(),
}
}
}
#[derive(Debug)]
pub enum WasmError {
InvalidServerUrl(InvalidServerUrl),
HttpError(reqwasm::Error),
BodyError(BoxError),
SocketInitError(ws_stream_wasm::WsErr),
}
impl From<WasmError> for TransportError<WasmError> {
fn from(err: WasmError) -> Self {
TransportError::Transport(err)
}
}
impl Display for WasmError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
WasmError::InvalidServerUrl(err) => write!(f, "invalid server url passed: {}", err),
WasmError::HttpError(err) => {
write!(f, "HTTP error: {}", err)
}
WasmError::BodyError(err) => write!(f, "error while aggregating body: {}", err),
WasmError::SocketInitError(err) => {
write!(f, "error while initializing socket: {}", err)
}
}
}
}
impl StdError for WasmError {}
struct SendSyncBody<S> {
inner: S,
}
impl<S> Stream for SendSyncBody<S>
where
S: Stream<Item = Result<Bytes, BoxError>> + Unpin,
{
type Item = S::Item;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
self.inner.poll_next_unpin(cx)
}
}
unsafe impl<S> Send for SendSyncBody<S> {}
unsafe impl<S> Sync for SendSyncBody<S> {}
pub struct CallFuture {
inner: LocalBoxFuture<'static, Result<BoxResponse, TransportError<WasmError>>>,
}
impl Future for CallFuture {
type Output = Result<BoxResponse, TransportError<WasmError>>;
fn poll(mut self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.inner.poll_unpin(cx)
}
}
unsafe impl Send for CallFuture {}