1use crate::receipt_wait::{Timer, now};
2use quai_rpc::fetch::{
3 FetchBackend, FetchError, FetchHeaders, FetchRequest, FetchResponse, MAX_FETCH_BYTES,
4};
5use wasm_bindgen::prelude::*;
6#[wasm_bindgen(module = "/src/bridge.js")]
7extern "C" {
8 #[wasm_bindgen(catch,js_name=newAbort)]
9 fn new_abort() -> Result<JsValue, JsValue>;
10 #[wasm_bindgen(js_name=abort)]
11 fn abort(controller: &JsValue);
12 #[wasm_bindgen(js_name=errorKind)]
13 fn error_kind(error: &JsValue) -> String;
14}
15#[wasm_bindgen(module = "/src/resource.js")]
16extern "C" {
17 #[wasm_bindgen(catch,js_name=resourceFetch)]
18 async fn resource_fetch(
19 url: &str,
20 method: &str,
21 headers: &str,
22 body: &JsValue,
23 controller: &JsValue,
24 max_bytes: usize,
25 ) -> Result<JsValue, JsValue>;
26 #[wasm_bindgen(js_name=resourceMeta)]
27 fn resource_meta(result: &JsValue) -> String;
28 #[wasm_bindgen(js_name=resourceBytes)]
29 fn resource_bytes(result: &JsValue) -> js_sys::Uint8Array;
30}
31struct Abort(JsValue);
32impl Drop for Abort {
33 fn drop(&mut self) {
34 abort(&self.0);
35 }
36}
37#[derive(Clone, Copy, Debug, Default)]
41pub struct BrowserResourceFetch;
42impl FetchBackend for BrowserResourceFetch {
43 fn now(&self) -> Result<f64, FetchError> {
44 now().map_err(|_| FetchError::Transport)
45 }
46 async fn sleep(&self, milliseconds: u32) -> Result<(), FetchError> {
47 if milliseconds == 0 {
48 return Ok(());
49 }
50 Timer::new(milliseconds)
51 .map_err(|_| FetchError::Invalid)?
52 .wait()
53 .await
54 .map_err(|_| FetchError::Transport)
55 }
56 async fn execute(
57 &self,
58 request: &FetchRequest,
59 max_bytes: usize,
60 ) -> Result<FetchResponse, FetchError> {
61 request.validate()?;
62 if !matches!(request.scheme(), "http" | "https")
63 || !(1..=MAX_FETCH_BYTES).contains(&max_bytes)
64 {
65 return Err(FetchError::Invalid);
66 }
67 let guard = Abort(new_abort().map_err(|_| FetchError::Transport)?);
68 let headers = request.headers()?;
69 let headers =
70 serde_json::to_string(&headers.iter().collect::<std::collections::BTreeMap<_, _>>())
71 .map_err(|_| FetchError::Invalid)?;
72 let body = request
73 .body()
74 .map(|b| JsValue::from(js_sys::Uint8Array::from(b)))
75 .unwrap_or(JsValue::NULL);
76 let result = resource_fetch(
77 request.url(),
78 request.method(),
79 &headers,
80 &body,
81 &guard.0,
82 max_bytes,
83 )
84 .await
85 .map_err(|e| match error_kind(&e).as_str() {
86 "response_size" => FetchError::Limit,
87 "unsupported" => FetchError::Unsupported,
88 "cancelled" => FetchError::Cancelled,
89 _ => FetchError::Transport,
90 })?;
91 let meta = resource_meta(&result);
92 if meta.len() > MAX_FETCH_BYTES {
93 return Err(FetchError::Limit);
94 }
95 #[derive(serde::Deserialize)]
96 struct Meta {
97 status: u16,
98 message: String,
99 headers: std::collections::BTreeMap<String, String>,
100 }
101 let meta: Meta = serde_json::from_str(&meta).map_err(|_| FetchError::Invalid)?;
102 let mut headers = FetchHeaders::default();
103 for (k, v) in meta.headers {
104 headers.set(&k, &v)?;
105 }
106 let body = resource_bytes(&result);
107 if body.length() as usize > max_bytes {
108 return Err(FetchError::Limit);
109 }
110 FetchResponse::new(meta.status, &meta.message, headers, Some(body.to_vec()))
111 }
112}