2023-01-02 16:00:42 -05:00
|
|
|
|
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
|
2020-09-18 09:20:55 -04:00
|
|
|
|
|
2022-12-19 06:49:00 -05:00
|
|
|
|
mod byte_stream;
|
2021-11-01 00:29:46 -04:00
|
|
|
|
mod fs_fetch_handler;
|
|
|
|
|
|
2023-05-01 16:42:05 -04:00
|
|
|
|
use std::borrow::Cow;
|
|
|
|
|
use std::cell::RefCell;
|
|
|
|
|
use std::cmp::min;
|
|
|
|
|
use std::convert::From;
|
|
|
|
|
use std::path::Path;
|
|
|
|
|
use std::path::PathBuf;
|
|
|
|
|
use std::pin::Pin;
|
|
|
|
|
use std::rc::Rc;
|
|
|
|
|
use std::sync::Arc;
|
|
|
|
|
|
2020-09-18 09:20:55 -04:00
|
|
|
|
use deno_core::error::type_error;
|
|
|
|
|
use deno_core::error::AnyError;
|
2022-10-09 10:49:25 -04:00
|
|
|
|
use deno_core::futures::stream::Peekable;
|
2021-01-10 14:54:29 -05:00
|
|
|
|
use deno_core::futures::Future;
|
|
|
|
|
use deno_core::futures::Stream;
|
|
|
|
|
use deno_core::futures::StreamExt;
|
2022-03-14 13:44:15 -04:00
|
|
|
|
use deno_core::op;
|
2022-10-09 10:49:25 -04:00
|
|
|
|
use deno_core::BufView;
|
|
|
|
|
use deno_core::WriteOutcome;
|
2022-03-14 13:44:15 -04:00
|
|
|
|
|
2020-09-18 09:20:55 -04:00
|
|
|
|
use deno_core::url::Url;
|
2020-12-16 11:14:12 -05:00
|
|
|
|
use deno_core::AsyncRefCell;
|
2021-11-09 13:26:17 -05:00
|
|
|
|
use deno_core::AsyncResult;
|
2021-06-26 11:34:24 -04:00
|
|
|
|
use deno_core::ByteString;
|
2020-12-16 11:14:12 -05:00
|
|
|
|
use deno_core::CancelFuture;
|
|
|
|
|
use deno_core::CancelHandle;
|
2021-01-12 02:50:02 -05:00
|
|
|
|
use deno_core::CancelTryFuture;
|
2021-06-06 09:37:17 -04:00
|
|
|
|
use deno_core::Canceled;
|
2020-09-18 09:20:55 -04:00
|
|
|
|
use deno_core::OpState;
|
2020-12-16 11:14:12 -05:00
|
|
|
|
use deno_core::RcRef;
|
|
|
|
|
use deno_core::Resource;
|
2021-03-19 13:25:37 -04:00
|
|
|
|
use deno_core::ResourceId;
|
2020-09-18 09:20:55 -04:00
|
|
|
|
use deno_core::ZeroCopyBuf;
|
2021-08-07 08:49:38 -04:00
|
|
|
|
use deno_tls::rustls::RootCertStore;
|
|
|
|
|
use deno_tls::Proxy;
|
2023-05-01 16:42:05 -04:00
|
|
|
|
use deno_tls::RootCertStoreProvider;
|
|
|
|
|
|
|
|
|
|
use data_url::DataUrl;
|
2023-01-14 23:18:58 -05:00
|
|
|
|
use http::header::CONTENT_LENGTH;
|
|
|
|
|
use http::Uri;
|
2021-12-01 11:13:11 -05:00
|
|
|
|
use reqwest::header::HeaderMap;
|
2020-09-18 09:20:55 -04:00
|
|
|
|
use reqwest::header::HeaderName;
|
|
|
|
|
use reqwest::header::HeaderValue;
|
2022-10-17 09:39:41 -04:00
|
|
|
|
use reqwest::header::ACCEPT_ENCODING;
|
2021-06-21 23:42:04 -04:00
|
|
|
|
use reqwest::header::HOST;
|
2022-10-17 09:39:41 -04:00
|
|
|
|
use reqwest::header::RANGE;
|
2021-12-01 11:13:11 -05:00
|
|
|
|
use reqwest::header::USER_AGENT;
|
|
|
|
|
use reqwest::redirect::Policy;
|
2021-01-10 14:54:29 -05:00
|
|
|
|
use reqwest::Body;
|
2020-09-18 09:20:55 -04:00
|
|
|
|
use reqwest::Client;
|
|
|
|
|
use reqwest::Method;
|
2021-07-29 11:29:16 -04:00
|
|
|
|
use reqwest::RequestBuilder;
|
2020-09-18 09:20:55 -04:00
|
|
|
|
use reqwest::Response;
|
|
|
|
|
use serde::Deserialize;
|
2021-04-05 12:40:24 -04:00
|
|
|
|
use serde::Serialize;
|
2021-01-10 14:54:29 -05:00
|
|
|
|
use tokio::sync::mpsc;
|
2020-09-18 09:20:55 -04:00
|
|
|
|
|
2021-08-16 08:29:54 -04:00
|
|
|
|
// Re-export reqwest and data_url
|
|
|
|
|
pub use data_url;
|
|
|
|
|
pub use reqwest;
|
2020-09-18 12:31:30 -04:00
|
|
|
|
|
2021-11-01 00:29:46 -04:00
|
|
|
|
pub use fs_fetch_handler::FsFetchHandler;
|
|
|
|
|
|
2023-05-16 19:20:32 -04:00
|
|
|
|
pub use crate::byte_stream::MpscByteStream;
|
2022-12-19 06:49:00 -05:00
|
|
|
|
|
2021-11-29 10:29:41 -05:00
|
|
|
|
#[derive(Clone)]
|
2021-11-28 13:07:03 -05:00
|
|
|
|
pub struct Options {
|
|
|
|
|
pub user_agent: String,
|
2023-05-01 16:42:05 -04:00
|
|
|
|
pub root_cert_store_provider: Option<Arc<dyn RootCertStoreProvider>>,
|
2021-11-28 13:07:03 -05:00
|
|
|
|
pub proxy: Option<Proxy>,
|
2023-03-13 06:29:05 -04:00
|
|
|
|
pub request_builder_hook:
|
|
|
|
|
Option<fn(RequestBuilder) -> Result<RequestBuilder, AnyError>>,
|
2021-11-28 13:07:03 -05:00
|
|
|
|
pub unsafely_ignore_certificate_errors: Option<Vec<String>>,
|
|
|
|
|
pub client_cert_chain_and_key: Option<(String, String)>,
|
2021-12-03 08:25:16 -05:00
|
|
|
|
pub file_fetch_handler: Rc<dyn FetchHandler>,
|
2021-11-28 13:07:03 -05:00
|
|
|
|
}
|
|
|
|
|
|
2023-05-01 16:42:05 -04:00
|
|
|
|
impl Options {
|
|
|
|
|
pub fn root_cert_store(&self) -> Result<Option<RootCertStore>, AnyError> {
|
|
|
|
|
Ok(match &self.root_cert_store_provider {
|
|
|
|
|
Some(provider) => Some(provider.get_or_try_init()?.clone()),
|
|
|
|
|
None => None,
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2021-11-28 13:07:03 -05:00
|
|
|
|
impl Default for Options {
|
|
|
|
|
fn default() -> Self {
|
|
|
|
|
Self {
|
|
|
|
|
user_agent: "".to_string(),
|
2023-05-01 16:42:05 -04:00
|
|
|
|
root_cert_store_provider: None,
|
2021-11-28 13:07:03 -05:00
|
|
|
|
proxy: None,
|
|
|
|
|
request_builder_hook: None,
|
|
|
|
|
unsafely_ignore_certificate_errors: None,
|
|
|
|
|
client_cert_chain_and_key: None,
|
2021-12-03 08:25:16 -05:00
|
|
|
|
file_fetch_handler: Rc::new(DefaultFileFetchHandler),
|
2021-11-28 13:07:03 -05:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2023-03-17 14:22:15 -04:00
|
|
|
|
deno_core::extension!(deno_fetch,
|
|
|
|
|
deps = [ deno_webidl, deno_web, deno_url, deno_console ],
|
|
|
|
|
parameters = [FP: FetchPermissions],
|
|
|
|
|
ops = [
|
|
|
|
|
op_fetch<FP>,
|
|
|
|
|
op_fetch_send,
|
|
|
|
|
op_fetch_custom_client<FP>,
|
|
|
|
|
],
|
|
|
|
|
esm = [
|
|
|
|
|
"20_headers.js",
|
|
|
|
|
"21_formdata.js",
|
|
|
|
|
"22_body.js",
|
|
|
|
|
"22_http_client.js",
|
|
|
|
|
"23_request.js",
|
|
|
|
|
"23_response.js",
|
|
|
|
|
"26_fetch.js"
|
|
|
|
|
],
|
2023-03-17 18:15:27 -04:00
|
|
|
|
options = {
|
2023-03-17 14:22:15 -04:00
|
|
|
|
options: Options,
|
|
|
|
|
},
|
|
|
|
|
state = |state, options| {
|
2023-05-01 16:42:05 -04:00
|
|
|
|
state.put::<Options>(options.options);
|
2023-03-17 14:22:15 -04:00
|
|
|
|
},
|
|
|
|
|
);
|
2020-09-18 09:20:55 -04:00
|
|
|
|
|
2021-11-01 00:29:46 -04:00
|
|
|
|
pub type CancelableResponseFuture =
|
|
|
|
|
Pin<Box<dyn Future<Output = CancelableResponseResult>>>;
|
|
|
|
|
|
2021-11-28 13:07:03 -05:00
|
|
|
|
pub trait FetchHandler: dyn_clone::DynClone {
|
2021-11-01 00:29:46 -04:00
|
|
|
|
// Return the result of the fetch request consisting of a tuple of the
|
|
|
|
|
// cancelable response result, the optional fetch body resource and the
|
|
|
|
|
// optional cancel handle.
|
|
|
|
|
fn fetch_file(
|
2021-12-03 08:25:16 -05:00
|
|
|
|
&self,
|
|
|
|
|
state: &mut OpState,
|
2021-11-01 00:29:46 -04:00
|
|
|
|
url: Url,
|
|
|
|
|
) -> (
|
|
|
|
|
CancelableResponseFuture,
|
|
|
|
|
Option<FetchRequestBodyResource>,
|
|
|
|
|
Option<Rc<CancelHandle>>,
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
2021-11-28 13:07:03 -05:00
|
|
|
|
dyn_clone::clone_trait_object!(FetchHandler);
|
|
|
|
|
|
2021-11-01 00:29:46 -04:00
|
|
|
|
/// A default implementation which will error for every request.
|
|
|
|
|
#[derive(Clone)]
|
|
|
|
|
pub struct DefaultFileFetchHandler;
|
|
|
|
|
|
|
|
|
|
impl FetchHandler for DefaultFileFetchHandler {
|
|
|
|
|
fn fetch_file(
|
2021-12-03 08:25:16 -05:00
|
|
|
|
&self,
|
|
|
|
|
_state: &mut OpState,
|
2021-11-01 00:29:46 -04:00
|
|
|
|
_url: Url,
|
|
|
|
|
) -> (
|
|
|
|
|
CancelableResponseFuture,
|
|
|
|
|
Option<FetchRequestBodyResource>,
|
|
|
|
|
Option<Rc<CancelHandle>>,
|
|
|
|
|
) {
|
|
|
|
|
let fut = async move {
|
|
|
|
|
Ok(Err(type_error(
|
|
|
|
|
"NetworkError when attempting to fetch resource.",
|
|
|
|
|
)))
|
|
|
|
|
};
|
|
|
|
|
(Box::pin(fut), None, None)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-09-18 09:20:55 -04:00
|
|
|
|
pub trait FetchPermissions {
|
2022-09-27 16:36:33 -04:00
|
|
|
|
fn check_net_url(
|
|
|
|
|
&mut self,
|
|
|
|
|
_url: &Url,
|
|
|
|
|
api_name: &str,
|
|
|
|
|
) -> Result<(), AnyError>;
|
|
|
|
|
fn check_read(&mut self, _p: &Path, api_name: &str) -> Result<(), AnyError>;
|
2020-09-30 10:51:01 -04:00
|
|
|
|
}
|
|
|
|
|
|
2022-03-16 20:25:44 -04:00
|
|
|
|
pub fn get_declaration() -> PathBuf {
|
|
|
|
|
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("lib.deno_fetch.d.ts")
|
|
|
|
|
}
|
2021-04-05 12:40:24 -04:00
|
|
|
|
#[derive(Serialize)]
|
|
|
|
|
#[serde(rename_all = "camelCase")]
|
|
|
|
|
pub struct FetchReturn {
|
2023-05-16 19:20:32 -04:00
|
|
|
|
pub request_rid: ResourceId,
|
|
|
|
|
pub request_body_rid: Option<ResourceId>,
|
|
|
|
|
pub cancel_handle_rid: Option<ResourceId>,
|
2021-04-05 12:40:24 -04:00
|
|
|
|
}
|
|
|
|
|
|
2023-05-01 16:42:05 -04:00
|
|
|
|
pub fn get_or_create_client_from_state(
|
|
|
|
|
state: &mut OpState,
|
|
|
|
|
) -> Result<reqwest::Client, AnyError> {
|
|
|
|
|
if let Some(client) = state.try_borrow::<reqwest::Client>() {
|
|
|
|
|
Ok(client.clone())
|
|
|
|
|
} else {
|
|
|
|
|
let options = state.borrow::<Options>();
|
|
|
|
|
let client = create_http_client(
|
|
|
|
|
&options.user_agent,
|
2023-05-20 21:43:54 -04:00
|
|
|
|
CreateHttpClientOptions {
|
|
|
|
|
root_cert_store: options.root_cert_store()?,
|
|
|
|
|
ca_certs: vec![],
|
|
|
|
|
proxy: options.proxy.clone(),
|
|
|
|
|
unsafely_ignore_certificate_errors: options
|
|
|
|
|
.unsafely_ignore_certificate_errors
|
|
|
|
|
.clone(),
|
|
|
|
|
client_cert_chain_and_key: options.client_cert_chain_and_key.clone(),
|
|
|
|
|
pool_max_idle_per_host: None,
|
|
|
|
|
pool_idle_timeout: None,
|
|
|
|
|
http1: true,
|
|
|
|
|
http2: true,
|
|
|
|
|
},
|
2023-05-01 16:42:05 -04:00
|
|
|
|
)?;
|
|
|
|
|
state.put::<reqwest::Client>(client.clone());
|
|
|
|
|
Ok(client)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2022-03-14 13:44:15 -04:00
|
|
|
|
#[op]
|
2021-11-28 13:07:03 -05:00
|
|
|
|
pub fn op_fetch<FP>(
|
2021-01-10 14:54:29 -05:00
|
|
|
|
state: &mut OpState,
|
2022-04-23 12:49:06 -04:00
|
|
|
|
method: ByteString,
|
|
|
|
|
url: String,
|
|
|
|
|
headers: Vec<(ByteString, ByteString)>,
|
|
|
|
|
client_rid: Option<u32>,
|
|
|
|
|
has_body: bool,
|
|
|
|
|
body_length: Option<u64>,
|
2021-04-02 09:47:57 -04:00
|
|
|
|
data: Option<ZeroCopyBuf>,
|
2021-04-05 12:40:24 -04:00
|
|
|
|
) -> Result<FetchReturn, AnyError>
|
2020-09-18 09:20:55 -04:00
|
|
|
|
where
|
|
|
|
|
FP: FetchPermissions + 'static,
|
|
|
|
|
{
|
2022-04-23 12:49:06 -04:00
|
|
|
|
let client = if let Some(rid) = client_rid {
|
2021-08-15 07:29:19 -04:00
|
|
|
|
let r = state.resource_table.get::<HttpClientResource>(rid)?;
|
2020-09-18 09:20:55 -04:00
|
|
|
|
r.client.clone()
|
|
|
|
|
} else {
|
2023-05-01 16:42:05 -04:00
|
|
|
|
get_or_create_client_from_state(state)?
|
2020-09-18 09:20:55 -04:00
|
|
|
|
};
|
|
|
|
|
|
2022-04-23 12:49:06 -04:00
|
|
|
|
let method = Method::from_bytes(&method)?;
|
|
|
|
|
let url = Url::parse(&url)?;
|
2020-09-18 09:20:55 -04:00
|
|
|
|
|
|
|
|
|
// Check scheme before asking for net permission
|
2021-01-07 13:06:08 -05:00
|
|
|
|
let scheme = url.scheme();
|
2021-06-06 09:37:17 -04:00
|
|
|
|
let (request_rid, request_body_rid, cancel_handle_rid) = match scheme {
|
2021-11-01 00:29:46 -04:00
|
|
|
|
"file" => {
|
|
|
|
|
let path = url.to_file_path().map_err(|_| {
|
|
|
|
|
type_error("NetworkError when attempting to fetch resource.")
|
|
|
|
|
})?;
|
|
|
|
|
let permissions = state.borrow_mut::<FP>();
|
2022-09-27 16:36:33 -04:00
|
|
|
|
permissions.check_read(&path, "fetch()")?;
|
2021-11-01 00:29:46 -04:00
|
|
|
|
|
|
|
|
|
if method != Method::GET {
|
|
|
|
|
return Err(type_error(format!(
|
2023-01-27 10:43:16 -05:00
|
|
|
|
"Fetching files only supports the GET method. Received {method}."
|
2021-11-01 00:29:46 -04:00
|
|
|
|
)));
|
|
|
|
|
}
|
|
|
|
|
|
2021-11-29 10:29:41 -05:00
|
|
|
|
let Options {
|
|
|
|
|
file_fetch_handler, ..
|
|
|
|
|
} = state.borrow_mut::<Options>();
|
2021-12-03 08:25:16 -05:00
|
|
|
|
let file_fetch_handler = file_fetch_handler.clone();
|
2021-11-01 00:29:46 -04:00
|
|
|
|
let (request, maybe_request_body, maybe_cancel_handle) =
|
2021-12-03 08:25:16 -05:00
|
|
|
|
file_fetch_handler.fetch_file(state, url);
|
2021-11-01 00:29:46 -04:00
|
|
|
|
let request_rid = state.resource_table.add(FetchRequestResource(request));
|
|
|
|
|
let maybe_request_body_rid =
|
|
|
|
|
maybe_request_body.map(|r| state.resource_table.add(r));
|
|
|
|
|
let maybe_cancel_handle_rid = maybe_cancel_handle
|
|
|
|
|
.map(|ch| state.resource_table.add(FetchCancelHandle(ch)));
|
|
|
|
|
|
|
|
|
|
(request_rid, maybe_request_body_rid, maybe_cancel_handle_rid)
|
|
|
|
|
}
|
2021-04-10 17:38:15 -04:00
|
|
|
|
"http" | "https" => {
|
2021-04-11 22:15:43 -04:00
|
|
|
|
let permissions = state.borrow_mut::<FP>();
|
2022-09-27 16:36:33 -04:00
|
|
|
|
permissions.check_net_url(&url, "fetch()")?;
|
2020-09-18 09:20:55 -04:00
|
|
|
|
|
2022-12-23 11:39:14 -05:00
|
|
|
|
// Make sure that we have a valid URI early, as reqwest's `RequestBuilder::send`
|
|
|
|
|
// internally uses `expect_uri`, which panics instead of returning a usable `Result`.
|
|
|
|
|
if url.as_str().parse::<Uri>().is_err() {
|
|
|
|
|
return Err(type_error("Invalid URL"));
|
|
|
|
|
}
|
|
|
|
|
|
2021-11-09 06:10:40 -05:00
|
|
|
|
let mut request = client.request(method.clone(), url);
|
2020-09-18 09:20:55 -04:00
|
|
|
|
|
2022-04-23 12:49:06 -04:00
|
|
|
|
let request_body_rid = if has_body {
|
2021-04-10 17:38:15 -04:00
|
|
|
|
match data {
|
|
|
|
|
None => {
|
|
|
|
|
// If no body is passed, we return a writer for streaming the body.
|
2022-12-19 06:49:00 -05:00
|
|
|
|
let (stream, tx) = MpscByteStream::new();
|
2021-07-05 09:34:37 -04:00
|
|
|
|
|
|
|
|
|
// If the size of the body is known, we include a content-length
|
|
|
|
|
// header explicitly.
|
2022-04-23 12:49:06 -04:00
|
|
|
|
if let Some(body_size) = body_length {
|
2021-07-05 09:34:37 -04:00
|
|
|
|
request =
|
|
|
|
|
request.header(CONTENT_LENGTH, HeaderValue::from(body_size))
|
|
|
|
|
}
|
|
|
|
|
|
2022-12-19 06:49:00 -05:00
|
|
|
|
request = request.body(Body::wrap_stream(stream));
|
2021-01-10 14:54:29 -05:00
|
|
|
|
|
2021-04-10 17:38:15 -04:00
|
|
|
|
let request_body_rid =
|
|
|
|
|
state.resource_table.add(FetchRequestBodyResource {
|
|
|
|
|
body: AsyncRefCell::new(tx),
|
|
|
|
|
cancel: CancelHandle::default(),
|
|
|
|
|
});
|
2021-01-10 14:54:29 -05:00
|
|
|
|
|
2021-04-10 17:38:15 -04:00
|
|
|
|
Some(request_body_rid)
|
|
|
|
|
}
|
|
|
|
|
Some(data) => {
|
|
|
|
|
// If a body is passed, we use it, and don't return a body for streaming.
|
2023-05-16 19:20:32 -04:00
|
|
|
|
request = request.body(data.to_vec());
|
2021-04-10 17:38:15 -04:00
|
|
|
|
None
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
} else {
|
2021-11-09 06:10:40 -05:00
|
|
|
|
// POST and PUT requests should always have a 0 length content-length,
|
|
|
|
|
// if there is no body. https://fetch.spec.whatwg.org/#http-network-or-cache-fetch
|
|
|
|
|
if matches!(method, Method::POST | Method::PUT) {
|
|
|
|
|
request = request.header(CONTENT_LENGTH, HeaderValue::from(0));
|
|
|
|
|
}
|
2021-01-10 14:54:29 -05:00
|
|
|
|
None
|
2021-04-10 17:38:15 -04:00
|
|
|
|
};
|
|
|
|
|
|
2022-10-17 09:39:41 -04:00
|
|
|
|
let mut header_map = HeaderMap::new();
|
2022-04-23 12:49:06 -04:00
|
|
|
|
for (key, value) in headers {
|
2021-09-29 12:42:06 -04:00
|
|
|
|
let name = HeaderName::from_bytes(&key)
|
|
|
|
|
.map_err(|err| type_error(err.to_string()))?;
|
|
|
|
|
let v = HeaderValue::from_bytes(&value)
|
|
|
|
|
.map_err(|err| type_error(err.to_string()))?;
|
2022-10-17 09:39:41 -04:00
|
|
|
|
|
2022-08-23 06:43:04 -04:00
|
|
|
|
if !matches!(name, HOST | CONTENT_LENGTH) {
|
2022-10-17 09:39:41 -04:00
|
|
|
|
header_map.append(name, v);
|
2021-06-21 23:42:04 -04:00
|
|
|
|
}
|
2021-01-10 14:54:29 -05:00
|
|
|
|
}
|
2021-04-10 17:38:15 -04:00
|
|
|
|
|
2022-10-17 09:39:41 -04:00
|
|
|
|
if header_map.contains_key(RANGE) {
|
|
|
|
|
// https://fetch.spec.whatwg.org/#http-network-or-cache-fetch step 18
|
|
|
|
|
// If httpRequest’s header list contains `Range`, then append (`Accept-Encoding`, `identity`)
|
|
|
|
|
header_map
|
|
|
|
|
.insert(ACCEPT_ENCODING, HeaderValue::from_static("identity"));
|
|
|
|
|
}
|
|
|
|
|
request = request.headers(header_map);
|
|
|
|
|
|
2021-11-29 10:29:41 -05:00
|
|
|
|
let options = state.borrow::<Options>();
|
|
|
|
|
if let Some(request_builder_hook) = options.request_builder_hook {
|
2023-03-13 06:29:05 -04:00
|
|
|
|
request = request_builder_hook(request)
|
|
|
|
|
.map_err(|err| type_error(err.to_string()))?;
|
2021-07-27 19:04:08 -04:00
|
|
|
|
}
|
|
|
|
|
|
2021-06-06 09:37:17 -04:00
|
|
|
|
let cancel_handle = CancelHandle::new_rc();
|
|
|
|
|
let cancel_handle_ = cancel_handle.clone();
|
|
|
|
|
|
2021-07-05 09:34:37 -04:00
|
|
|
|
let fut = async move {
|
|
|
|
|
request
|
|
|
|
|
.send()
|
|
|
|
|
.or_cancel(cancel_handle_)
|
|
|
|
|
.await
|
|
|
|
|
.map(|res| res.map_err(|err| type_error(err.to_string())))
|
|
|
|
|
};
|
2021-04-10 17:38:15 -04:00
|
|
|
|
|
|
|
|
|
let request_rid = state
|
|
|
|
|
.resource_table
|
|
|
|
|
.add(FetchRequestResource(Box::pin(fut)));
|
|
|
|
|
|
2021-06-06 09:37:17 -04:00
|
|
|
|
let cancel_handle_rid =
|
|
|
|
|
state.resource_table.add(FetchCancelHandle(cancel_handle));
|
|
|
|
|
|
|
|
|
|
(request_rid, request_body_rid, Some(cancel_handle_rid))
|
2021-01-10 14:54:29 -05:00
|
|
|
|
}
|
2021-04-10 17:38:15 -04:00
|
|
|
|
"data" => {
|
|
|
|
|
let data_url = DataUrl::process(url.as_str())
|
2023-01-27 10:43:16 -05:00
|
|
|
|
.map_err(|e| type_error(format!("{e:?}")))?;
|
2020-09-18 09:20:55 -04:00
|
|
|
|
|
2021-04-10 17:38:15 -04:00
|
|
|
|
let (body, _) = data_url
|
|
|
|
|
.decode_to_vec()
|
2023-01-27 10:43:16 -05:00
|
|
|
|
.map_err(|e| type_error(format!("{e:?}")))?;
|
2020-09-18 09:20:55 -04:00
|
|
|
|
|
2021-04-10 17:38:15 -04:00
|
|
|
|
let response = http::Response::builder()
|
|
|
|
|
.status(http::StatusCode::OK)
|
|
|
|
|
.header(http::header::CONTENT_TYPE, data_url.mime_type().to_string())
|
|
|
|
|
.body(reqwest::Body::from(body))?;
|
2021-01-10 14:54:29 -05:00
|
|
|
|
|
2021-06-06 09:37:17 -04:00
|
|
|
|
let fut = async move { Ok(Ok(Response::from(response))) };
|
2021-04-10 17:38:15 -04:00
|
|
|
|
|
2021-04-11 08:09:10 -04:00
|
|
|
|
let request_rid = state
|
|
|
|
|
.resource_table
|
|
|
|
|
.add(FetchRequestResource(Box::pin(fut)));
|
|
|
|
|
|
2021-06-06 09:37:17 -04:00
|
|
|
|
(request_rid, None, None)
|
2021-04-11 08:09:10 -04:00
|
|
|
|
}
|
|
|
|
|
"blob" => {
|
fix: a `Request` whose URL is a revoked blob URL should still fetch (#11947)
In the spec, a URL record has an associated "blob URL entry", which for
`blob:` URLs is populated during parsing to contain a reference to the
`Blob` object that backs that object URL. It is this blob URL entry that
the `fetch` API uses to resolve an object URL.
Therefore, since the `Request` constructor parses URL inputs, it will
have an associated blob URL entry which will be used when fetching, even
if the object URL has been revoked since the construction of the
`Request` object. (The `Request` constructor takes the URL as a string
and parses it, so the object URL must be live at the time it is called.)
This PR adds a new `blobFromObjectUrl` JS function (backed by a new
`op_blob_from_object_url` op) that, if the URL is a valid object URL,
returns a new `Blob` object whose parts are references to the same Rust
`BlobPart`s used by the original `Blob` object. It uses this function to
add a new `blobUrlEntry` field to inner requests, which will be `null`
or such a `Blob`, and then uses `Blob.prototype.stream()` as the
response's body. As a result of this, the `blob:` URL resolution from
`op_fetch` is now useless, and has been removed.
2021-09-08 05:29:21 -04:00
|
|
|
|
// Blob URL resolution happens in the JS side of fetch. If we got here is
|
|
|
|
|
// because the URL isn't an object URL.
|
|
|
|
|
return Err(type_error("Blob for the given URL not found."));
|
2021-04-10 17:38:15 -04:00
|
|
|
|
}
|
2023-01-27 10:43:16 -05:00
|
|
|
|
_ => return Err(type_error(format!("scheme '{scheme}' not supported"))),
|
2021-04-10 17:38:15 -04:00
|
|
|
|
};
|
2021-01-10 14:54:29 -05:00
|
|
|
|
|
2021-04-05 12:40:24 -04:00
|
|
|
|
Ok(FetchReturn {
|
|
|
|
|
request_rid,
|
|
|
|
|
request_body_rid,
|
2021-06-06 09:37:17 -04:00
|
|
|
|
cancel_handle_rid,
|
2021-04-05 12:40:24 -04:00
|
|
|
|
})
|
2021-01-10 14:54:29 -05:00
|
|
|
|
}
|
|
|
|
|
|
2021-04-05 12:40:24 -04:00
|
|
|
|
#[derive(Serialize)]
|
2021-03-17 17:33:29 -04:00
|
|
|
|
#[serde(rename_all = "camelCase")]
|
2021-04-05 12:40:24 -04:00
|
|
|
|
pub struct FetchResponse {
|
2023-05-16 19:20:32 -04:00
|
|
|
|
pub status: u16,
|
|
|
|
|
pub status_text: String,
|
|
|
|
|
pub headers: Vec<(ByteString, ByteString)>,
|
|
|
|
|
pub url: String,
|
|
|
|
|
pub response_rid: ResourceId,
|
|
|
|
|
pub content_length: Option<u64>,
|
2021-03-17 17:33:29 -04:00
|
|
|
|
}
|
|
|
|
|
|
2022-03-14 13:44:15 -04:00
|
|
|
|
#[op]
|
2021-01-10 14:54:29 -05:00
|
|
|
|
pub async fn op_fetch_send(
|
|
|
|
|
state: Rc<RefCell<OpState>>,
|
2021-04-05 12:40:24 -04:00
|
|
|
|
rid: ResourceId,
|
|
|
|
|
) -> Result<FetchResponse, AnyError> {
|
2021-01-10 14:54:29 -05:00
|
|
|
|
let request = state
|
|
|
|
|
.borrow_mut()
|
|
|
|
|
.resource_table
|
2021-08-15 07:29:19 -04:00
|
|
|
|
.take::<FetchRequestResource>(rid)?;
|
2021-01-10 14:54:29 -05:00
|
|
|
|
|
|
|
|
|
let request = Rc::try_unwrap(request)
|
|
|
|
|
.ok()
|
|
|
|
|
.expect("multiple op_fetch_send ongoing");
|
|
|
|
|
|
|
|
|
|
let res = match request.0.await {
|
2021-06-06 09:37:17 -04:00
|
|
|
|
Ok(Ok(res)) => res,
|
|
|
|
|
Ok(Err(err)) => return Err(type_error(err.to_string())),
|
|
|
|
|
Err(_) => return Err(type_error("request was cancelled")),
|
2020-12-26 08:06:00 -05:00
|
|
|
|
};
|
2020-09-18 09:20:55 -04:00
|
|
|
|
|
|
|
|
|
//debug!("Fetch response {}", url);
|
|
|
|
|
let status = res.status();
|
2021-01-18 07:59:29 -05:00
|
|
|
|
let url = res.url().to_string();
|
2020-09-18 09:20:55 -04:00
|
|
|
|
let mut res_headers = Vec::new();
|
|
|
|
|
for (key, val) in res.headers().iter() {
|
2022-04-02 08:37:11 -04:00
|
|
|
|
res_headers.push((key.as_str().into(), val.as_bytes().into()));
|
2020-09-18 09:20:55 -04:00
|
|
|
|
}
|
|
|
|
|
|
2022-09-26 14:27:50 -04:00
|
|
|
|
let content_length = res.content_length();
|
|
|
|
|
|
2021-01-10 14:54:29 -05:00
|
|
|
|
let stream: BytesStream = Box::pin(res.bytes_stream().map(|r| {
|
|
|
|
|
r.map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err))
|
|
|
|
|
}));
|
|
|
|
|
let rid = state
|
|
|
|
|
.borrow_mut()
|
|
|
|
|
.resource_table
|
|
|
|
|
.add(FetchResponseBodyResource {
|
2022-10-09 10:49:25 -04:00
|
|
|
|
reader: AsyncRefCell::new(stream.peekable()),
|
2021-01-10 14:54:29 -05:00
|
|
|
|
cancel: CancelHandle::default(),
|
2022-10-04 09:48:50 -04:00
|
|
|
|
size: content_length,
|
2021-01-10 14:54:29 -05:00
|
|
|
|
});
|
2020-09-18 09:20:55 -04:00
|
|
|
|
|
2021-04-05 12:40:24 -04:00
|
|
|
|
Ok(FetchResponse {
|
|
|
|
|
status: status.as_u16(),
|
|
|
|
|
status_text: status.canonical_reason().unwrap_or("").to_string(),
|
|
|
|
|
headers: res_headers,
|
|
|
|
|
url,
|
|
|
|
|
response_rid: rid,
|
2022-09-26 14:27:50 -04:00
|
|
|
|
content_length,
|
2021-04-05 12:40:24 -04:00
|
|
|
|
})
|
2021-03-17 17:33:29 -04:00
|
|
|
|
}
|
|
|
|
|
|
2021-07-05 09:34:37 -04:00
|
|
|
|
type CancelableResponseResult = Result<Result<Response, AnyError>, Canceled>;
|
2021-06-06 09:37:17 -04:00
|
|
|
|
|
2023-05-16 19:20:32 -04:00
|
|
|
|
pub struct FetchRequestResource(
|
|
|
|
|
pub Pin<Box<dyn Future<Output = CancelableResponseResult>>>,
|
2021-01-10 14:54:29 -05:00
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
impl Resource for FetchRequestResource {
|
|
|
|
|
fn name(&self) -> Cow<str> {
|
|
|
|
|
"fetchRequest".into()
|
2020-12-16 11:14:12 -05:00
|
|
|
|
}
|
|
|
|
|
}
|
2020-09-18 09:20:55 -04:00
|
|
|
|
|
2023-05-16 19:20:32 -04:00
|
|
|
|
pub struct FetchCancelHandle(pub Rc<CancelHandle>);
|
2021-06-06 09:37:17 -04:00
|
|
|
|
|
|
|
|
|
impl Resource for FetchCancelHandle {
|
|
|
|
|
fn name(&self) -> Cow<str> {
|
|
|
|
|
"fetchCancelHandle".into()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn close(self: Rc<Self>) {
|
|
|
|
|
self.0.cancel()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2021-11-01 00:29:46 -04:00
|
|
|
|
pub struct FetchRequestBodyResource {
|
2023-05-16 19:20:32 -04:00
|
|
|
|
pub body: AsyncRefCell<mpsc::Sender<Option<bytes::Bytes>>>,
|
|
|
|
|
pub cancel: CancelHandle,
|
2021-01-10 14:54:29 -05:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl Resource for FetchRequestBodyResource {
|
|
|
|
|
fn name(&self) -> Cow<str> {
|
|
|
|
|
"fetchRequestBody".into()
|
|
|
|
|
}
|
2021-06-06 09:37:17 -04:00
|
|
|
|
|
2022-10-09 10:49:25 -04:00
|
|
|
|
fn write(self: Rc<Self>, buf: BufView) -> AsyncResult<WriteOutcome> {
|
2021-11-09 13:26:17 -05:00
|
|
|
|
Box::pin(async move {
|
2022-10-09 10:49:25 -04:00
|
|
|
|
let bytes: bytes::Bytes = buf.into();
|
|
|
|
|
let nwritten = bytes.len();
|
2021-11-09 13:26:17 -05:00
|
|
|
|
let body = RcRef::map(&self, |r| &r.body).borrow_mut().await;
|
|
|
|
|
let cancel = RcRef::map(self, |r| &r.cancel);
|
2022-12-19 06:49:00 -05:00
|
|
|
|
body
|
|
|
|
|
.send(Some(bytes))
|
|
|
|
|
.or_cancel(cancel)
|
|
|
|
|
.await?
|
|
|
|
|
.map_err(|_| {
|
|
|
|
|
type_error("request body receiver not connected (request closed)")
|
|
|
|
|
})?;
|
2022-10-09 10:49:25 -04:00
|
|
|
|
Ok(WriteOutcome::Full { nwritten })
|
2021-11-09 13:26:17 -05:00
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
2022-12-19 06:49:00 -05:00
|
|
|
|
fn shutdown(self: Rc<Self>) -> AsyncResult<()> {
|
|
|
|
|
Box::pin(async move {
|
|
|
|
|
let body = RcRef::map(&self, |r| &r.body).borrow_mut().await;
|
|
|
|
|
let cancel = RcRef::map(self, |r| &r.cancel);
|
|
|
|
|
// There is a case where hyper knows the size of the response body up
|
|
|
|
|
// front (through content-length header on the resp), where it will drop
|
|
|
|
|
// the body once that content length has been reached, regardless of if
|
|
|
|
|
// the stream is complete or not. This is expected behaviour, but it means
|
|
|
|
|
// that if you stream a body with an up front known size (eg a Blob),
|
|
|
|
|
// explicit shutdown can never succeed because the body (and by extension
|
|
|
|
|
// the receiver) will have dropped by the time we try to shutdown. As such
|
|
|
|
|
// we ignore if the receiver is closed, because we know that the request
|
|
|
|
|
// is complete in good health in that case.
|
|
|
|
|
body.send(None).or_cancel(cancel).await?.ok();
|
|
|
|
|
Ok(())
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
2021-06-06 09:37:17 -04:00
|
|
|
|
fn close(self: Rc<Self>) {
|
|
|
|
|
self.cancel.cancel()
|
|
|
|
|
}
|
2021-01-10 14:54:29 -05:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type BytesStream =
|
|
|
|
|
Pin<Box<dyn Stream<Item = Result<bytes::Bytes, std::io::Error>> + Unpin>>;
|
|
|
|
|
|
2023-05-16 19:20:32 -04:00
|
|
|
|
pub struct FetchResponseBodyResource {
|
|
|
|
|
pub reader: AsyncRefCell<Peekable<BytesStream>>,
|
|
|
|
|
pub cancel: CancelHandle,
|
|
|
|
|
pub size: Option<u64>,
|
2020-12-16 11:14:12 -05:00
|
|
|
|
}
|
|
|
|
|
|
2021-01-10 14:54:29 -05:00
|
|
|
|
impl Resource for FetchResponseBodyResource {
|
2020-12-16 11:14:12 -05:00
|
|
|
|
fn name(&self) -> Cow<str> {
|
2021-01-10 14:54:29 -05:00
|
|
|
|
"fetchResponseBody".into()
|
2020-12-16 11:14:12 -05:00
|
|
|
|
}
|
2021-06-06 09:37:17 -04:00
|
|
|
|
|
2022-10-09 10:49:25 -04:00
|
|
|
|
fn read(self: Rc<Self>, limit: usize) -> AsyncResult<BufView> {
|
2021-11-09 13:26:17 -05:00
|
|
|
|
Box::pin(async move {
|
2022-10-09 10:49:25 -04:00
|
|
|
|
let reader = RcRef::map(&self, |r| &r.reader).borrow_mut().await;
|
|
|
|
|
|
|
|
|
|
let fut = async move {
|
|
|
|
|
let mut reader = Pin::new(reader);
|
|
|
|
|
loop {
|
|
|
|
|
match reader.as_mut().peek_mut().await {
|
|
|
|
|
Some(Ok(chunk)) if !chunk.is_empty() => {
|
|
|
|
|
let len = min(limit, chunk.len());
|
|
|
|
|
let chunk = chunk.split_to(len);
|
|
|
|
|
break Ok(chunk.into());
|
|
|
|
|
}
|
|
|
|
|
// This unwrap is safe because `peek_mut()` returned `Some`, and thus
|
|
|
|
|
// currently has a peeked value that can be synchronously returned
|
|
|
|
|
// from `next()`.
|
|
|
|
|
//
|
|
|
|
|
// The future returned from `next()` is always ready, so we can
|
|
|
|
|
// safely call `await` on it without creating a race condition.
|
|
|
|
|
Some(_) => match reader.as_mut().next().await.unwrap() {
|
|
|
|
|
Ok(chunk) => assert!(chunk.is_empty()),
|
2022-10-12 03:23:33 -04:00
|
|
|
|
Err(err) => break Err(type_error(err.to_string())),
|
2022-10-09 10:49:25 -04:00
|
|
|
|
},
|
|
|
|
|
None => break Ok(BufView::empty()),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
let cancel_handle = RcRef::map(self, |r| &r.cancel);
|
|
|
|
|
fut.try_or_cancel(cancel_handle).await
|
2021-11-09 13:26:17 -05:00
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
2022-10-04 09:48:50 -04:00
|
|
|
|
fn size_hint(&self) -> (u64, Option<u64>) {
|
2022-10-24 07:26:41 -04:00
|
|
|
|
(self.size.unwrap_or(0), self.size)
|
2022-10-04 09:48:50 -04:00
|
|
|
|
}
|
|
|
|
|
|
2021-06-06 09:37:17 -04:00
|
|
|
|
fn close(self: Rc<Self>) {
|
|
|
|
|
self.cancel.cancel()
|
|
|
|
|
}
|
2020-09-18 09:20:55 -04:00
|
|
|
|
}
|
|
|
|
|
|
2023-05-16 19:20:32 -04:00
|
|
|
|
pub struct HttpClientResource {
|
|
|
|
|
pub client: Client,
|
2020-09-18 09:20:55 -04:00
|
|
|
|
}
|
|
|
|
|
|
2020-12-16 11:14:12 -05:00
|
|
|
|
impl Resource for HttpClientResource {
|
|
|
|
|
fn name(&self) -> Cow<str> {
|
|
|
|
|
"httpClient".into()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-09-18 09:20:55 -04:00
|
|
|
|
impl HttpClientResource {
|
|
|
|
|
fn new(client: Client) -> Self {
|
|
|
|
|
Self { client }
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2023-05-20 21:43:54 -04:00
|
|
|
|
#[derive(Deserialize, Debug, Clone)]
|
|
|
|
|
#[serde(rename_all = "camelCase")]
|
|
|
|
|
pub enum PoolIdleTimeout {
|
|
|
|
|
State(bool),
|
|
|
|
|
Specify(u64),
|
|
|
|
|
}
|
|
|
|
|
|
2021-09-30 03:26:15 -04:00
|
|
|
|
#[derive(Deserialize, Debug)]
|
2021-03-17 17:33:29 -04:00
|
|
|
|
#[serde(rename_all = "camelCase")]
|
2023-05-20 21:43:54 -04:00
|
|
|
|
pub struct CreateHttpClientArgs {
|
2021-09-30 03:26:15 -04:00
|
|
|
|
ca_certs: Vec<String>,
|
2021-06-21 23:21:57 -04:00
|
|
|
|
proxy: Option<Proxy>,
|
2021-08-25 08:25:12 -04:00
|
|
|
|
cert_chain: Option<String>,
|
|
|
|
|
private_key: Option<String>,
|
2023-05-20 21:43:54 -04:00
|
|
|
|
pool_max_idle_per_host: Option<usize>,
|
|
|
|
|
pool_idle_timeout: Option<PoolIdleTimeout>,
|
|
|
|
|
#[serde(default = "default_true")]
|
|
|
|
|
http1: bool,
|
|
|
|
|
#[serde(default = "default_true")]
|
|
|
|
|
http2: bool,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn default_true() -> bool {
|
|
|
|
|
true
|
2021-06-21 23:21:57 -04:00
|
|
|
|
}
|
|
|
|
|
|
2022-03-14 13:44:15 -04:00
|
|
|
|
#[op]
|
2021-10-31 14:14:22 -04:00
|
|
|
|
pub fn op_fetch_custom_client<FP>(
|
2020-09-18 09:20:55 -04:00
|
|
|
|
state: &mut OpState,
|
2023-05-20 21:43:54 -04:00
|
|
|
|
args: CreateHttpClientArgs,
|
2021-04-05 12:40:24 -04:00
|
|
|
|
) -> Result<ResourceId, AnyError>
|
2020-09-18 09:20:55 -04:00
|
|
|
|
where
|
|
|
|
|
FP: FetchPermissions + 'static,
|
|
|
|
|
{
|
2021-06-21 23:21:57 -04:00
|
|
|
|
if let Some(proxy) = args.proxy.clone() {
|
|
|
|
|
let permissions = state.borrow_mut::<FP>();
|
|
|
|
|
let url = Url::parse(&proxy.url)?;
|
2022-09-27 16:36:33 -04:00
|
|
|
|
permissions.check_net_url(&url, "Deno.createHttpClient()")?;
|
2021-06-21 23:21:57 -04:00
|
|
|
|
}
|
|
|
|
|
|
2021-08-25 08:25:12 -04:00
|
|
|
|
let client_cert_chain_and_key = {
|
|
|
|
|
if args.cert_chain.is_some() || args.private_key.is_some() {
|
|
|
|
|
let cert_chain = args
|
|
|
|
|
.cert_chain
|
|
|
|
|
.ok_or_else(|| type_error("No certificate chain provided"))?;
|
|
|
|
|
let private_key = args
|
|
|
|
|
.private_key
|
|
|
|
|
.ok_or_else(|| type_error("No private key provided"))?;
|
|
|
|
|
|
|
|
|
|
Some((cert_chain, private_key))
|
|
|
|
|
} else {
|
|
|
|
|
None
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
2021-11-29 10:29:41 -05:00
|
|
|
|
let options = state.borrow::<Options>();
|
2021-09-30 03:26:15 -04:00
|
|
|
|
let ca_certs = args
|
|
|
|
|
.ca_certs
|
|
|
|
|
.into_iter()
|
|
|
|
|
.map(|cert| cert.into_bytes())
|
|
|
|
|
.collect::<Vec<_>>();
|
2021-08-09 10:53:21 -04:00
|
|
|
|
|
2021-03-18 18:54:26 -04:00
|
|
|
|
let client = create_http_client(
|
2023-03-23 18:27:58 -04:00
|
|
|
|
&options.user_agent,
|
2023-05-20 21:43:54 -04:00
|
|
|
|
CreateHttpClientOptions {
|
|
|
|
|
root_cert_store: options.root_cert_store()?,
|
|
|
|
|
ca_certs,
|
|
|
|
|
proxy: args.proxy,
|
|
|
|
|
unsafely_ignore_certificate_errors: options
|
|
|
|
|
.unsafely_ignore_certificate_errors
|
|
|
|
|
.clone(),
|
|
|
|
|
client_cert_chain_and_key,
|
|
|
|
|
pool_max_idle_per_host: args.pool_max_idle_per_host,
|
|
|
|
|
pool_idle_timeout: args.pool_idle_timeout.and_then(
|
|
|
|
|
|timeout| match timeout {
|
|
|
|
|
PoolIdleTimeout::State(true) => None,
|
|
|
|
|
PoolIdleTimeout::State(false) => Some(None),
|
|
|
|
|
PoolIdleTimeout::Specify(specify) => Some(Some(specify)),
|
|
|
|
|
},
|
|
|
|
|
),
|
|
|
|
|
http1: args.http1,
|
|
|
|
|
http2: args.http2,
|
|
|
|
|
},
|
2021-08-25 08:25:12 -04:00
|
|
|
|
)?;
|
2020-09-18 09:20:55 -04:00
|
|
|
|
|
2020-12-16 11:14:12 -05:00
|
|
|
|
let rid = state.resource_table.add(HttpClientResource::new(client));
|
2021-04-05 12:40:24 -04:00
|
|
|
|
Ok(rid)
|
2020-09-18 09:20:55 -04:00
|
|
|
|
}
|
2021-12-01 11:13:11 -05:00
|
|
|
|
|
2023-05-20 21:43:54 -04:00
|
|
|
|
#[derive(Debug, Clone)]
|
|
|
|
|
pub struct CreateHttpClientOptions {
|
|
|
|
|
pub root_cert_store: Option<RootCertStore>,
|
|
|
|
|
pub ca_certs: Vec<Vec<u8>>,
|
|
|
|
|
pub proxy: Option<Proxy>,
|
|
|
|
|
pub unsafely_ignore_certificate_errors: Option<Vec<String>>,
|
|
|
|
|
pub client_cert_chain_and_key: Option<(String, String)>,
|
|
|
|
|
pub pool_max_idle_per_host: Option<usize>,
|
|
|
|
|
pub pool_idle_timeout: Option<Option<u64>>,
|
|
|
|
|
pub http1: bool,
|
|
|
|
|
pub http2: bool,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl Default for CreateHttpClientOptions {
|
|
|
|
|
fn default() -> Self {
|
|
|
|
|
CreateHttpClientOptions {
|
|
|
|
|
root_cert_store: None,
|
|
|
|
|
ca_certs: vec![],
|
|
|
|
|
proxy: None,
|
|
|
|
|
unsafely_ignore_certificate_errors: None,
|
|
|
|
|
client_cert_chain_and_key: None,
|
|
|
|
|
pool_max_idle_per_host: None,
|
|
|
|
|
pool_idle_timeout: None,
|
|
|
|
|
http1: true,
|
|
|
|
|
http2: true,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2021-12-01 11:13:11 -05:00
|
|
|
|
/// Create new instance of async reqwest::Client. This client supports
|
|
|
|
|
/// proxies and doesn't follow redirects.
|
|
|
|
|
pub fn create_http_client(
|
2023-03-23 18:27:58 -04:00
|
|
|
|
user_agent: &str,
|
2023-05-20 21:43:54 -04:00
|
|
|
|
options: CreateHttpClientOptions,
|
2021-12-01 11:13:11 -05:00
|
|
|
|
) -> Result<Client, AnyError> {
|
|
|
|
|
let mut tls_config = deno_tls::create_client_config(
|
2023-05-20 21:43:54 -04:00
|
|
|
|
options.root_cert_store,
|
|
|
|
|
options.ca_certs,
|
|
|
|
|
options.unsafely_ignore_certificate_errors,
|
|
|
|
|
options.client_cert_chain_and_key,
|
2021-12-01 11:13:11 -05:00
|
|
|
|
)?;
|
|
|
|
|
|
2023-05-29 17:05:45 -04:00
|
|
|
|
let mut alpn_protocols = vec![];
|
|
|
|
|
if options.http2 {
|
|
|
|
|
alpn_protocols.push("h2".into());
|
|
|
|
|
}
|
|
|
|
|
if options.http1 {
|
|
|
|
|
alpn_protocols.push("http/1.1".into());
|
|
|
|
|
}
|
|
|
|
|
tls_config.alpn_protocols = alpn_protocols;
|
2021-12-01 11:13:11 -05:00
|
|
|
|
|
|
|
|
|
let mut headers = HeaderMap::new();
|
|
|
|
|
headers.insert(USER_AGENT, user_agent.parse().unwrap());
|
|
|
|
|
let mut builder = Client::builder()
|
|
|
|
|
.redirect(Policy::none())
|
|
|
|
|
.default_headers(headers)
|
|
|
|
|
.use_preconfigured_tls(tls_config);
|
|
|
|
|
|
2023-05-20 21:43:54 -04:00
|
|
|
|
if let Some(proxy) = options.proxy {
|
2021-12-01 11:13:11 -05:00
|
|
|
|
let mut reqwest_proxy = reqwest::Proxy::all(&proxy.url)?;
|
|
|
|
|
if let Some(basic_auth) = &proxy.basic_auth {
|
|
|
|
|
reqwest_proxy =
|
|
|
|
|
reqwest_proxy.basic_auth(&basic_auth.username, &basic_auth.password);
|
|
|
|
|
}
|
|
|
|
|
builder = builder.proxy(reqwest_proxy);
|
|
|
|
|
}
|
|
|
|
|
|
2023-05-20 21:43:54 -04:00
|
|
|
|
if let Some(pool_max_idle_per_host) = options.pool_max_idle_per_host {
|
|
|
|
|
builder = builder.pool_max_idle_per_host(pool_max_idle_per_host);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if let Some(pool_idle_timeout) = options.pool_idle_timeout {
|
|
|
|
|
builder = builder.pool_idle_timeout(
|
|
|
|
|
pool_idle_timeout.map(std::time::Duration::from_millis),
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
match (options.http1, options.http2) {
|
|
|
|
|
(true, false) => builder = builder.http1_only(),
|
|
|
|
|
(false, true) => builder = builder.http2_prior_knowledge(),
|
|
|
|
|
(true, true) => {}
|
|
|
|
|
(false, false) => {
|
|
|
|
|
return Err(type_error("Either `http1` or `http2` needs to be true"))
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
builder.build().map_err(|e| e.into())
|
2021-12-01 11:13:11 -05:00
|
|
|
|
}
|