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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
//! `web-sys` implementation for the fetch service.

use super::Referrer;
use crate::callback::Callback;
use crate::format::{Binary, Format, Text};
use crate::services::Task;
use anyhow::{anyhow, Error};
use http::request::Parts;
use js_sys::{Array, Promise, Uint8Array};
use std::cell::RefCell;
use std::fmt;
use std::iter::FromIterator;
use std::marker::PhantomData;
use std::rc::Rc;
use thiserror::Error as ThisError;
use wasm_bindgen::prelude::wasm_bindgen;
use wasm_bindgen::{JsCast, JsValue};
use wasm_bindgen_futures::{spawn_local, JsFuture};
use web_sys::{
    AbortController, Headers, ReferrerPolicy, Request as WebRequest, RequestInit,
    Response as WebResponse,
};

#[doc(no_inline)]
pub use web_sys::{
    RequestCache as Cache, RequestCredentials as Credentials, RequestMode as Mode,
    RequestRedirect as Redirect, Window, WorkerGlobalScope,
};

#[doc(no_inline)]
pub use http::{HeaderMap, Method, Request, Response, StatusCode, Uri};

trait JsInterop: Sized {
    fn from_js(js_value: JsValue) -> Result<Self, FetchError>;
    fn to_js(self) -> JsValue;
}

impl JsInterop for Vec<u8> {
    fn from_js(js_value: JsValue) -> Result<Self, FetchError> {
        Ok(Uint8Array::new(&js_value).to_vec())
    }

    fn to_js(self) -> JsValue {
        Uint8Array::from(self.as_slice()).into()
    }
}

impl JsInterop for String {
    fn from_js(js_value: JsValue) -> Result<Self, FetchError> {
        js_value.as_string().ok_or(FetchError::InternalError)
    }

    fn to_js(self) -> JsValue {
        self.into()
    }
}

/// Init options for `fetch()` function call.
/// https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
#[derive(Default, Debug)]
pub struct FetchOptions {
    /// Cache of a fetch request.
    pub cache: Option<Cache>,
    /// Credentials of a fetch request.
    pub credentials: Option<Credentials>,
    /// Redirect behaviour of a fetch request.
    pub redirect: Option<Redirect>,
    /// Request mode of a fetch request.
    pub mode: Option<Mode>,
    /// Referrer of a fetch request.
    pub referrer: Option<Referrer>,
    /// Referrer policy of a fetch request.
    pub referrer_policy: Option<ReferrerPolicy>,
    /// Integrity of a fetch request.
    pub integrity: Option<String>,
}

impl Into<RequestInit> for FetchOptions {
    fn into(self) -> RequestInit {
        let mut init = RequestInit::new();

        if let Some(cache) = self.cache {
            init.cache(cache);
        }

        if let Some(credentials) = self.credentials {
            init.credentials(credentials);
        }

        if let Some(redirect) = self.redirect {
            init.redirect(redirect);
        }

        if let Some(mode) = self.mode {
            init.mode(mode);
        }

        if let Some(referrer) = self.referrer {
            match referrer {
                Referrer::SameOriginUrl(referrer) => init.referrer(&referrer),
                Referrer::AboutClient => init.referrer("about:client"),
                Referrer::Empty => init.referrer(""),
            };
        }

        if let Some(referrer_policy) = self.referrer_policy {
            init.referrer_policy(referrer_policy);
        }

        if let Some(integrity) = self.integrity {
            init.integrity(&integrity);
        }

        init
    }
}

// convert `headers` to `Iterator<Item = (String, String)>`
fn header_iter(headers: Headers) -> impl Iterator<Item = (String, String)> {
    js_sys::try_iter(&headers)
        .unwrap()
        .unwrap()
        .map(Result::unwrap)
        .map(|entry| {
            let entry = Array::from(&entry);
            let key = entry.get(0);
            let value = entry.get(1);
            (key.as_string().unwrap(), value.as_string().unwrap())
        })
}

/// Represents errors of a fetch service.
#[derive(Debug, ThisError)]
enum FetchError {
    #[error("canceled")]
    Canceled,
    #[error("{0}")]
    FetchFailed(String),
    #[error("invalid response")]
    InvalidResponse,
    #[error("unexpected error, please report")]
    InternalError,
}

#[derive(Debug)]
struct Handle {
    active: Rc<RefCell<bool>>,
    abort_controller: Option<AbortController>,
}

/// A handle to control sent requests.
#[must_use]
pub struct FetchTask(Handle);

impl fmt::Debug for FetchTask {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("FetchTask")
    }
}

/// A service to fetch resources.
#[derive(Default, Debug)]
pub struct FetchService {}

impl FetchService {
    /// Sends a request to a remote server given a Request object and a callback
    /// function to convert a Response object into a loop's message.
    ///
    /// You may use a Request builder to build your request declaratively as on the
    /// following examples:
    ///
    /// ```
    ///# use yew::format::{Nothing, Json};
    ///# use yew::services::fetch::Request;
    ///# use serde_json::json;
    /// let post_request = Request::post("https://my.api/v1/resource")
    ///     .header("Content-Type", "application/json")
    ///     .body(Json(&json!({"foo": "bar"})))
    ///     .expect("Failed to build request.");
    ///
    /// let get_request = Request::get("https://my.api/v1/resource")
    ///     .body(Nothing)
    ///     .expect("Failed to build request.");
    /// ```
    ///
    /// The callback function can build a loop message by passing or analyzing the
    /// response body and metadata.
    ///
    /// ```
    ///# use yew::{Component, ComponentLink, Html, Renderable};
    ///# use yew::services::FetchService;
    ///# use yew::services::fetch::{Response, Request};
    ///# use anyhow::Error;
    ///# struct Comp;
    ///# impl Component for Comp {
    ///#     type Message = Msg;type Properties = ();
    ///#     fn create(props: Self::Properties,link: ComponentLink<Self>) -> Self {unimplemented!()}
    ///#     fn update(&mut self,msg: Self::Message) -> bool {unimplemented!()}
    ///#     fn change(&mut self, _: Self::Properties) -> bool {unimplemented!()}
    ///#     fn view(&self) -> Html {unimplemented!()}
    ///# }
    ///# enum Msg {
    ///#     Noop,
    ///#     Error
    ///# }
    ///# fn dont_execute() {
    ///# let link: ComponentLink<Comp> = unimplemented!();
    ///# let post_request: Request<Result<String, Error>> = unimplemented!();
    /// let task = FetchService::fetch(
    ///     post_request,
    ///     link.callback(|response: Response<Result<String, Error>>| {
    ///         if response.status().is_success() {
    ///             Msg::Noop
    ///         } else {
    ///             Msg::Error
    ///         }
    ///     }),
    /// );
    ///# }
    /// ```
    ///
    /// For a full example, you can specify that the response must be in the JSON format,
    /// and be a specific serialized data type. If the message isn't JSON, or isn't the specified
    /// data type, then you will get an error message.
    ///
    /// ```
    ///# use yew::format::{Json, Nothing, Format};
    ///# use yew::services::FetchService;
    ///# use http::Request;
    ///# use yew::services::fetch::Response;
    ///# use yew::{Component, ComponentLink, Renderable, Html};
    ///# use serde_derive::Deserialize;
    ///# use anyhow::Error;
    ///# struct Comp;
    ///# impl Component for Comp {
    ///#     type Message = Msg;type Properties = ();
    ///#     fn create(props: Self::Properties,link: ComponentLink<Self>) -> Self {unimplemented!()}
    ///#     fn update(&mut self,msg: Self::Message) -> bool {unimplemented!()}
    ///#     fn change(&mut self, _: Self::Properties) -> bool {unimplemented!()}
    ///#     fn view(&self) -> Html {unimplemented!()}
    ///# }
    ///# enum Msg {
    ///#     FetchResourceComplete(Data),
    ///#     FetchResourceFailed
    ///# }
    /// #[derive(Deserialize)]
    /// struct Data {
    ///    value: String
    /// }
    ///
    ///# fn dont_execute() {
    ///# let link: ComponentLink<Comp> = unimplemented!();
    /// let get_request = Request::get("/thing").body(Nothing).unwrap();
    /// let callback = link.callback(|response: Response<Json<Result<Data, Error>>>| {
    ///     if let (meta, Json(Ok(body))) = response.into_parts() {
    ///         if meta.status.is_success() {
    ///             return Msg::FetchResourceComplete(body);
    ///         }
    ///     }
    ///     Msg::FetchResourceFailed
    /// });
    ///
    /// let task = FetchService::fetch(get_request, callback);
    ///# }
    /// ```
    ///
    pub fn fetch<IN, OUT: 'static>(
        request: Request<IN>,
        callback: Callback<Response<OUT>>,
    ) -> Result<FetchTask, Error>
    where
        IN: Into<Text>,
        OUT: From<Text>,
    {
        fetch_impl::<IN, OUT, String>(false, request, None, callback)
    }

    /// `fetch` with provided `FetchOptions` object.
    /// Use it if you need to send cookies with a request:
    /// ```
    ///# use yew::format::Nothing;
    ///# use yew::services::fetch::{self, FetchOptions, Credentials};
    ///# use yew::{Renderable, Html, Component, ComponentLink};
    ///# use yew::services::FetchService;
    ///# use http::Response;
    ///# use anyhow::Error;
    ///# struct Comp;
    ///# impl Component for Comp {
    ///#     type Message = Msg;
    ///#     type Properties = ();
    ///#     fn create(props: Self::Properties, link: ComponentLink<Self>) -> Self {unimplemented!()}
    ///#     fn update(&mut self, msg: Self::Message) -> bool {unimplemented!()}
    ///#     fn change(&mut self, _: Self::Properties) -> bool {unimplemented!()}
    ///#     fn view(&self) -> Html {unimplemented!()}
    ///# }
    ///# pub enum Msg {}
    ///# fn dont_execute() {
    ///# let link: ComponentLink<Comp> = unimplemented!();
    ///# let callback = link.callback(|response: Response<Result<String, Error>>|  -> Msg { unimplemented!() });
    /// let request = fetch::Request::get("/path/")
    ///     .body(Nothing)
    ///     .unwrap();
    /// let options = FetchOptions {
    ///     credentials: Some(Credentials::SameOrigin),
    ///     ..FetchOptions::default()
    /// };
    /// let task = FetchService::fetch_with_options(request, options, callback);
    ///# }
    /// ```
    pub fn fetch_with_options<IN, OUT: 'static>(
        request: Request<IN>,
        options: FetchOptions,
        callback: Callback<Response<OUT>>,
    ) -> Result<FetchTask, Error>
    where
        IN: Into<Text>,
        OUT: From<Text>,
    {
        fetch_impl::<IN, OUT, String>(false, request, Some(options), callback)
    }

    /// Fetch the data in binary format.
    pub fn fetch_binary<IN, OUT: 'static>(
        request: Request<IN>,
        callback: Callback<Response<OUT>>,
    ) -> Result<FetchTask, Error>
    where
        IN: Into<Binary>,
        OUT: From<Binary>,
    {
        fetch_impl::<IN, OUT, Vec<u8>>(true, request, None, callback)
    }

    /// Fetch the data in binary format with the provided request options.
    pub fn fetch_binary_with_options<IN, OUT: 'static>(
        request: Request<IN>,
        options: FetchOptions,
        callback: Callback<Response<OUT>>,
    ) -> Result<FetchTask, Error>
    where
        IN: Into<Binary>,
        OUT: From<Binary>,
    {
        fetch_impl::<IN, OUT, Vec<u8>>(true, request, Some(options), callback)
    }
}

fn fetch_impl<IN, OUT: 'static, DATA: 'static>(
    binary: bool,
    request: Request<IN>,
    options: Option<FetchOptions>,
    callback: Callback<Response<OUT>>,
) -> Result<FetchTask, Error>
where
    DATA: JsInterop,
    IN: Into<Format<DATA>>,
    OUT: From<Format<DATA>>,
{
    // Transform http::Request into WebRequest.
    let (parts, body) = request.into_parts();
    let body = match body.into() {
        Ok(b) => b.to_js(),
        Err(_) => JsValue::NULL,
    };
    let request = build_request(parts, &body)?;

    // Transform FetchOptions into RequestInit.
    let abort_controller = AbortController::new().ok();
    let mut init = options.map_or_else(RequestInit::new, Into::into);
    if let Some(abort_controller) = &abort_controller {
        init.signal(Some(&abort_controller.signal()));
    }

    // Start fetch
    let promise = GLOBAL.with(|global| global.fetch_with_request_and_init(&request, &init));

    // Spawn future to resolve fetch
    let active = Rc::new(RefCell::new(true));
    let data_fetcher = DataFetcher::new(binary, callback, active.clone());
    spawn_local(DataFetcher::fetch_data(data_fetcher, promise));

    Ok(FetchTask(Handle {
        active,
        abort_controller,
    }))
}

struct DataFetcher<OUT: 'static, DATA>
where
    DATA: JsInterop,
    OUT: From<Format<DATA>>,
{
    binary: bool,
    active: Rc<RefCell<bool>>,
    callback: Callback<Response<OUT>>,
    _marker: PhantomData<DATA>,
}

impl<OUT: 'static, DATA> DataFetcher<OUT, DATA>
where
    DATA: JsInterop,
    OUT: From<Format<DATA>>,
{
    fn new(binary: bool, callback: Callback<Response<OUT>>, active: Rc<RefCell<bool>>) -> Self {
        Self {
            binary,
            callback,
            active,
            _marker: PhantomData::default(),
        }
    }

    async fn fetch_data(self, promise: Promise) {
        let result = self.fetch_data_impl(promise).await;
        let (data, status, headers) = match result {
            Ok((data, response)) => (Ok(data), response.status(), Some(response.headers())),
            Err(err) => (Err(err), 408, None),
        };
        self.callback(data, status, headers);
    }

    async fn fetch_data_impl(&self, promise: Promise) -> Result<(DATA, WebResponse), Error> {
        let response = self.get_response(promise).await?;
        let data = self.get_data(&response).await?;
        Ok((data, response))
    }

    // Prepare the response callback.
    // Notice that the callback signature must match the call from the javascript
    // side. There is no static check at this point.
    fn callback(&self, data: Result<DATA, Error>, status: u16, headers: Option<Headers>) {
        let mut response_builder = Response::builder();
        if let Ok(status) = StatusCode::from_u16(status) {
            response_builder = response_builder.status(status);
        }

        if let Some(headers) = headers {
            for (key, value) in header_iter(headers) {
                response_builder = response_builder.header(key.as_str(), value.as_str());
            }
        }

        // Deserialize and wrap response data into a Text or Binary object.
        let response = response_builder
            .body(OUT::from(data))
            .expect("failed to build response, please report");
        *self.active.borrow_mut() = false;
        self.callback.emit(response);
    }

    async fn get_response(&self, fetch_promise: Promise) -> Result<WebResponse, FetchError> {
        let response = JsFuture::from(fetch_promise)
            .await
            .map_err(|err| err.unchecked_into::<js_sys::Error>())
            .map_err(|err| FetchError::FetchFailed(err.to_string().as_string().unwrap()))?;
        if *self.active.borrow() {
            Ok(WebResponse::from(response))
        } else {
            Err(FetchError::Canceled)
        }
    }

    async fn get_data(&self, response: &WebResponse) -> Result<DATA, FetchError> {
        let data_promise = if self.binary {
            response.array_buffer()
        } else {
            response.text()
        }
        .map_err(|_| FetchError::InvalidResponse)?;

        let data_result = JsFuture::from(data_promise).await;
        if *self.active.borrow() {
            data_result
                .map_err(|_| FetchError::InvalidResponse)
                .and_then(DATA::from_js)
        } else {
            Err(FetchError::Canceled)
        }
    }
}

fn build_request(parts: Parts, body: &JsValue) -> Result<WebRequest, Error> {
    // Map headers into a Js `Header` type.
    let header_list = parts
        .headers
        .iter()
        .map(|(k, v)| {
            Ok(Array::from_iter(&[
                JsValue::from_str(k.as_str()),
                JsValue::from_str(
                    v.to_str()
                        .map_err(|_| anyhow!("Unparsable request header"))?,
                ),
            ]))
        })
        .collect::<Result<Array, Error>>()?;

    let header_map = Headers::new_with_str_sequence_sequence(&header_list)
        .map_err(|_| anyhow!("couldn't build headers"))?;

    // Formats URI.
    let uri = parts.uri.to_string();
    let method = parts.method.as_str();
    let mut init = RequestInit::new();
    init.method(method).body(Some(body)).headers(&header_map);
    WebRequest::new_with_str_and_init(&uri, &init).map_err(|_| anyhow!("failed to build request"))
}

impl Task for FetchTask {
    fn is_active(&self) -> bool {
        *self.0.active.borrow()
    }
}

impl Drop for FetchTask {
    fn drop(&mut self) {
        if self.is_active() {
            // Fetch API doesn't support request cancelling in all browsers
            // and we should use this workaround with a flag.
            // In that case, request not canceled, but callback won't be called.
            *self.0.active.borrow_mut() = false;
            if let Some(abort_controller) = &self.0.abort_controller {
                abort_controller.abort();
            }
        }
    }
}

thread_local! {
    static GLOBAL: WindowOrWorker = WindowOrWorker::new();
}

enum WindowOrWorker {
    Window(Window),
    Worker(WorkerGlobalScope),
}

impl WindowOrWorker {
    fn new() -> Self {
        #[wasm_bindgen]
        extern "C" {
            type Global;

            #[wasm_bindgen(method, getter, js_name = Window)]
            fn window(this: &Global) -> JsValue;

            #[wasm_bindgen(method, getter, js_name = WorkerGlobalScope)]
            fn worker(this: &Global) -> JsValue;
        }

        let global: Global = js_sys::global().unchecked_into();

        if !global.window().is_undefined() {
            Self::Window(global.unchecked_into())
        } else if !global.worker().is_undefined() {
            Self::Worker(global.unchecked_into())
        } else {
            panic!(
                "Yew's `FetchService` only works when a `window` or `worker` object is available."
            );
        }
    }
}

impl WindowOrWorker {
    fn fetch_with_request_and_init(&self, input: &WebRequest, init: &RequestInit) -> Promise {
        match self {
            Self::Window(window) => window.fetch_with_request_and_init(input, init),
            Self::Worker(worker) => worker.fetch_with_request_and_init(input, init),
        }
    }
}