aioduct 0.1.6

Async-native HTTP client built directly on hyper 1.x — no hyper-util, no legacy
Documentation
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
use std::time::Duration;

use bytes::Bytes;
use http::{HeaderMap, HeaderValue, Method, StatusCode, Uri};
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::JsFuture;

use crate::error::Error;

/// A browser-based HTTP client using the Fetch API.
///
/// This client is only available on `wasm32` targets with the `wasm` feature.
/// It delegates all networking to the browser's `fetch()` API, which handles
/// connection pooling, TLS, and HTTP/2 automatically.
#[derive(Clone, Debug)]
pub struct WasmClient {
    default_headers: HeaderMap,
    timeout: Option<Duration>,
}

impl WasmClient {
    /// Create a new WASM client with default settings.
    pub fn new() -> Self {
        let mut default_headers = HeaderMap::new();
        let ua = concat!("aioduct/", env!("CARGO_PKG_VERSION"));
        if let Ok(val) = HeaderValue::from_str(ua) {
            default_headers.insert(http::header::USER_AGENT, val);
        }
        Self {
            default_headers,
            timeout: None,
        }
    }

    /// Create a new builder for configuring the WASM client.
    pub fn builder() -> WasmClientBuilder {
        WasmClientBuilder {
            default_headers: HeaderMap::new(),
            timeout: None,
        }
    }

    /// Start a GET request.
    pub fn get(&self, uri: &str) -> Result<WasmRequestBuilder<'_>, Error> {
        let uri: Uri = uri.parse().map_err(|e| Error::InvalidUrl(format!("{e}")))?;
        Ok(WasmRequestBuilder::new(self, Method::GET, uri))
    }

    /// Start a HEAD request.
    pub fn head(&self, uri: &str) -> Result<WasmRequestBuilder<'_>, Error> {
        let uri: Uri = uri.parse().map_err(|e| Error::InvalidUrl(format!("{e}")))?;
        Ok(WasmRequestBuilder::new(self, Method::HEAD, uri))
    }

    /// Start a POST request.
    pub fn post(&self, uri: &str) -> Result<WasmRequestBuilder<'_>, Error> {
        let uri: Uri = uri.parse().map_err(|e| Error::InvalidUrl(format!("{e}")))?;
        Ok(WasmRequestBuilder::new(self, Method::POST, uri))
    }

    /// Start a PUT request.
    pub fn put(&self, uri: &str) -> Result<WasmRequestBuilder<'_>, Error> {
        let uri: Uri = uri.parse().map_err(|e| Error::InvalidUrl(format!("{e}")))?;
        Ok(WasmRequestBuilder::new(self, Method::PUT, uri))
    }

    /// Start a PATCH request.
    pub fn patch(&self, uri: &str) -> Result<WasmRequestBuilder<'_>, Error> {
        let uri: Uri = uri.parse().map_err(|e| Error::InvalidUrl(format!("{e}")))?;
        Ok(WasmRequestBuilder::new(self, Method::PATCH, uri))
    }

    /// Start a DELETE request.
    pub fn delete(&self, uri: &str) -> Result<WasmRequestBuilder<'_>, Error> {
        let uri: Uri = uri.parse().map_err(|e| Error::InvalidUrl(format!("{e}")))?;
        Ok(WasmRequestBuilder::new(self, Method::DELETE, uri))
    }

    /// Start a request with a custom method.
    pub fn request(&self, method: Method, uri: &str) -> Result<WasmRequestBuilder<'_>, Error> {
        let uri: Uri = uri.parse().map_err(|e| Error::InvalidUrl(format!("{e}")))?;
        Ok(WasmRequestBuilder::new(self, method, uri))
    }
}

impl Default for WasmClient {
    fn default() -> Self {
        Self::new()
    }
}

/// Builder for configuring a [`WasmClient`].
pub struct WasmClientBuilder {
    default_headers: HeaderMap,
    timeout: Option<Duration>,
}

impl WasmClientBuilder {
    /// Set default headers for all requests.
    pub fn default_headers(mut self, headers: HeaderMap) -> Self {
        self.default_headers.extend(headers);
        self
    }

    /// Set a default User-Agent header.
    pub fn user_agent(mut self, value: impl AsRef<str>) -> Self {
        if let Ok(val) = HeaderValue::from_str(value.as_ref()) {
            self.default_headers.insert(http::header::USER_AGENT, val);
        }
        self
    }

    /// Set a default request timeout.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Build the WASM client.
    pub fn build(self) -> WasmClient {
        let mut client = WasmClient::new();
        client.default_headers.extend(self.default_headers);
        client.timeout = self.timeout;
        client
    }
}

/// A request builder for the WASM client.
pub struct WasmRequestBuilder<'a> {
    client: &'a WasmClient,
    method: Method,
    uri: Uri,
    headers: HeaderMap,
    body: Option<Bytes>,
    timeout: Option<Duration>,
}

impl<'a> WasmRequestBuilder<'a> {
    fn new(client: &'a WasmClient, method: Method, uri: Uri) -> Self {
        Self {
            client,
            method,
            uri,
            headers: HeaderMap::new(),
            body: None,
            timeout: None,
        }
    }

    /// Set a request header.
    pub fn header(mut self, name: http::header::HeaderName, value: HeaderValue) -> Self {
        self.headers.insert(name, value);
        self
    }

    /// Set multiple request headers.
    pub fn headers(mut self, headers: HeaderMap) -> Self {
        self.headers.extend(headers);
        self
    }

    /// Set the request body.
    pub fn body(mut self, body: impl Into<Bytes>) -> Self {
        self.body = Some(body.into());
        self
    }

    /// Set a Bearer auth token.
    pub fn bearer_auth(mut self, token: &str) -> Self {
        if let Ok(val) = HeaderValue::from_str(&format!("Bearer {token}")) {
            self.headers.insert(http::header::AUTHORIZATION, val);
        }
        self
    }

    /// Set a per-request timeout.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Set the body as JSON.
    #[cfg(feature = "json")]
    pub fn json<T: serde::Serialize>(mut self, value: &T) -> Result<Self, Error> {
        let json_bytes = serde_json::to_vec(value).map_err(|e| Error::Other(Box::new(e)))?;
        self.body = Some(Bytes::from(json_bytes));
        self.headers
            .entry(http::header::CONTENT_TYPE)
            .or_insert_with(|| HeaderValue::from_static("application/json"));
        Ok(self)
    }

    /// Send the request using the browser's Fetch API.
    pub async fn send(self) -> Result<WasmResponse, Error> {
        let url = self.uri.to_string();

        let opts = web_sys::RequestInit::new();
        opts.set_method(self.method.as_str());

        let headers = web_sys::Headers::new()
            .map_err(|e| Error::Other(format!("Headers::new failed: {e:?}").into()))?;

        for (name, value) in &self.client.default_headers {
            if !self.headers.contains_key(name)
                && let Ok(v) = value.to_str()
            {
                let _ = headers.set(name.as_str(), v);
            }
        }
        for (name, value) in &self.headers {
            if let Ok(v) = value.to_str() {
                let _ = headers.set(name.as_str(), v);
            }
        }

        opts.set_headers(&headers);

        if let Some(body) = &self.body {
            let uint8_array = js_sys::Uint8Array::from(body.as_ref());
            opts.set_body(&uint8_array);
        }

        let timeout = self.timeout.or(self.client.timeout);
        let abort_controller = if timeout.is_some() {
            let controller = web_sys::AbortController::new()
                .map_err(|e| Error::Other(format!("AbortController::new failed: {e:?}").into()))?;
            opts.set_signal(Some(&controller.signal()));
            Some(controller)
        } else {
            None
        };

        let request = web_sys::Request::new_with_str_and_init(&url, &opts)
            .map_err(|e| Error::Other(format!("Request::new failed: {e:?}").into()))?;

        let window: web_sys::Window = js_sys::global()
            .dyn_into()
            .map_err(|_| Error::Other("not in a browser window context".into()))?;

        let resp_promise = window.fetch_with_request(&request);

        let timeout_handle =
            if let (Some(duration), Some(controller)) = (timeout, abort_controller.clone()) {
                let ms = duration.as_millis() as i32;
                Some(
                    window
                        .set_timeout_with_callback_and_timeout_and_arguments_0(
                            &wasm_bindgen::closure::Closure::once_into_js(move || {
                                controller.abort();
                            })
                            .unchecked_into(),
                            ms,
                        )
                        .map_err(|e| Error::Other(format!("setTimeout failed: {e:?}").into()))?,
                )
            } else {
                None
            };

        let resp_value = JsFuture::from(resp_promise).await.map_err(|e| {
            let msg = js_sys::JSON::stringify(&e)
                .map(String::from)
                .unwrap_or_else(|_| format!("{e:?}"));
            if msg.contains("abort") {
                Error::Timeout
            } else {
                Error::Other(format!("fetch failed: {msg}").into())
            }
        })?;

        if let Some(handle) = timeout_handle {
            window.clear_timeout_with_handle(handle);
        }

        let resp: web_sys::Response = resp_value
            .dyn_into()
            .map_err(|_| Error::Other("fetch did not return a Response".into()))?;

        let status = StatusCode::from_u16(resp.status())
            .map_err(|e| Error::Other(format!("invalid status code: {e}").into()))?;

        let mut resp_headers = HeaderMap::new();
        let header_entries = resp.headers();
        let iterator = js_sys::try_iter(&header_entries)
            .map_err(|e| Error::Other(format!("headers iteration failed: {e:?}").into()))?;
        if let Some(iter) = iterator {
            for entry in iter {
                let entry =
                    entry.map_err(|e| Error::Other(format!("header entry error: {e:?}").into()))?;
                let pair = js_sys::Array::from(&entry);
                if pair.length() == 2 {
                    let key: String = pair.get(0).as_string().unwrap_or_default();
                    let val: String = pair.get(1).as_string().unwrap_or_default();
                    if let (Ok(name), Ok(value)) = (
                        key.parse::<http::header::HeaderName>(),
                        val.parse::<HeaderValue>(),
                    ) {
                        resp_headers.insert(name, value);
                    }
                }
            }
        }

        let body_promise = resp
            .array_buffer()
            .map_err(|e| Error::Other(format!("arrayBuffer() failed: {e:?}").into()))?;
        let body_value = JsFuture::from(body_promise)
            .await
            .map_err(|e| Error::Other(format!("body read failed: {e:?}").into()))?;
        let uint8_array = js_sys::Uint8Array::new(&body_value);
        let body = Bytes::from(uint8_array.to_vec());

        Ok(WasmResponse {
            status,
            headers: resp_headers,
            body,
            url: self.uri,
        })
    }
}

/// An HTTP response from the WASM/Fetch client.
#[derive(Debug)]
pub struct WasmResponse {
    status: StatusCode,
    headers: HeaderMap,
    body: Bytes,
    url: Uri,
}

impl WasmResponse {
    /// The HTTP status code.
    pub fn status(&self) -> StatusCode {
        self.status
    }

    /// The response headers.
    pub fn headers(&self) -> &HeaderMap {
        &self.headers
    }

    /// The request URL.
    pub fn url(&self) -> &Uri {
        &self.url
    }

    /// Consume the response and return the body as bytes.
    pub fn bytes(self) -> Bytes {
        self.body
    }

    /// Consume the response and return the body as a string.
    pub fn text(self) -> Result<String, Error> {
        String::from_utf8(self.body.to_vec())
            .map_err(|e| Error::Other(format!("invalid UTF-8 in response body: {e}").into()))
    }

    /// Deserialize the response body from JSON.
    #[cfg(feature = "json")]
    pub fn json<T: serde::de::DeserializeOwned>(self) -> Result<T, Error> {
        serde_json::from_slice(&self.body).map_err(|e| Error::Other(Box::new(e)))
    }

    /// Return an error if the status code indicates failure (4xx or 5xx).
    pub fn error_for_status(self) -> Result<Self, Error> {
        let status = self.status;
        if status.is_client_error() || status.is_server_error() {
            Err(Error::Status(status))
        } else {
            Ok(self)
        }
    }
}

#[cfg(all(test, feature = "json"))]
mod tests {
    use super::*;

    #[test]
    fn json_sets_default_content_type() {
        let client = WasmClient::new();
        let req = client
            .post("https://example.com/")
            .unwrap()
            .json(&serde_json::json!({"key": "value"}))
            .unwrap();

        assert_eq!(
            req.headers.get(http::header::CONTENT_TYPE).unwrap(),
            "application/json"
        );
    }

    #[test]
    fn json_preserves_existing_content_type() {
        let client = WasmClient::new();
        let req = client
            .post("https://example.com/")
            .unwrap()
            .header(
                http::header::CONTENT_TYPE,
                HeaderValue::from_static("application/vnd.api+json"),
            )
            .json(&serde_json::json!({"key": "value"}))
            .unwrap();

        assert_eq!(
            req.headers.get(http::header::CONTENT_TYPE).unwrap(),
            "application/vnd.api+json"
        );
    }
}