| 62 | |
| 63 | const MAX_REDIRECT_COUNT: u32 = 20; |
| 64 | |
| 65 | pub fn init(global_client: HyperClient, globals: &Object) -> Result<()> { |
| 66 | let connections = Arc::new(Semaphore::new(500)); |
| 67 | |
| 68 | globals.set( |
| 69 | "fetch", |
| 70 | Func::from(Async(move |ctx, resource, args| { |
| 71 | let global_client = global_client.clone(); |
| 72 | let connections = connections.clone(); |
| 73 | let start = Instant::now(); |
| 74 | let options = get_fetch_options(&ctx, resource, args); |
| 75 | |
| 76 | async move { |
| 77 | let _lock = connections.acquire().await; |
| 78 | let options = options?; |
| 79 | |
| 80 | let client = options |
| 81 | .agent |
| 82 | .map(|agent| agent.borrow().client()) |
| 83 | .unwrap_or(global_client); |
| 84 | |
| 85 | // https://fetch.spec.whatwg.org/#scheme-fetch |
| 86 | if let Some((scheme, fragment)) = options.url.split_once(':') { |
| 87 | match scheme { |
| 88 | "http" | "https" => {}, |
| 89 | "data" => return parse_data_url(&ctx, fragment, &options.method), |
| 90 | "about" | "blob" | "file" => { |
| 91 | return Err(Exception::throw_type(&ctx, "Unsupported scheme")); |
| 92 | }, |
| 93 | _ => return Err(Exception::throw_type(&ctx, "Invalid scheme")), |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | let mut uri = options.url.parse::<Uri>().map_err(|_| { |
| 98 | Exception::throw_type(&ctx, &["Invalid URL :", &options.url].concat()) |
| 99 | })?; |
| 100 | let initial_uri: Uri = uri.clone(); |
| 101 | |
| 102 | let method_string = options.method.to_string(); |
| 103 | let method = options.method; |
| 104 | let abort_receiver = options.abort_receiver; |
| 105 | |
| 106 | ensure_url_access(&ctx, &uri)?; |
| 107 | |
| 108 | // For streaming bodies - stream from JS to hyper via channel |
| 109 | if let Some(RequestBody::Stream(stream)) = options.body { |
| 110 | return send_stream( |
| 111 | &ctx, |
| 112 | &client, |
| 113 | stream, |
| 114 | method, |
| 115 | method_string, |
| 116 | uri, |
| 117 | options.headers.as_ref(), |
| 118 | start, |
| 119 | abort_receiver, |
| 120 | ) |
| 121 | .await; |