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
|
|
|
|
|
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;
|
2023-12-01 10:56:10 -05:00
|
|
|
|
use std::task::Context;
|
|
|
|
|
use std::task::Poll;
|
2023-05-01 16:42:05 -04:00
|
|
|
|
|
2023-08-03 16:27:25 -04:00
|
|
|
|
use deno_core::anyhow::Error;
|
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;
|
2023-08-03 16:27:25 -04:00
|
|
|
|
use deno_core::futures::FutureExt;
|
2021-01-10 14:54:29 -05:00
|
|
|
|
use deno_core::futures::Stream;
|
|
|
|
|
use deno_core::futures::StreamExt;
|
2023-09-21 10:08:23 -04:00
|
|
|
|
use deno_core::op2;
|
2023-08-23 19:03:05 -04:00
|
|
|
|
use deno_core::unsync::spawn;
|
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;
|
2023-12-01 10:56:10 -05:00
|
|
|
|
use deno_core::BufView;
|
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;
|
2023-06-22 17:37:56 -04:00
|
|
|
|
use deno_core::JsBuffer;
|
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;
|
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;
|
2023-06-13 08:11:27 -04:00
|
|
|
|
use tokio::io::AsyncReadExt;
|
|
|
|
|
use tokio::io::AsyncWriteExt;
|
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;
|
|
|
|
|
|
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,
|
2023-06-13 08:11:27 -04:00
|
|
|
|
op_fetch_response_upgrade,
|
2023-10-31 13:16:27 -04:00
|
|
|
|
op_utf8_to_byte_string,
|
2023-03-17 14:22:15 -04:00
|
|
|
|
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",
|
2023-10-31 13:16:27 -04:00
|
|
|
|
"26_fetch.js",
|
|
|
|
|
"27_eventsource.js"
|
2023-03-17 14:22:15 -04:00
|
|
|
|
],
|
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,
|
2023-08-09 12:47:47 -04:00
|
|
|
|
) -> (CancelableResponseFuture, Option<Rc<CancelHandle>>);
|
2021-11-01 00:29:46 -04:00
|
|
|
|
}
|
|
|
|
|
|
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,
|
2023-08-09 12:47:47 -04:00
|
|
|
|
) -> (CancelableResponseFuture, Option<Rc<CancelHandle>>) {
|
2021-11-01 00:29:46 -04:00
|
|
|
|
let fut = async move {
|
|
|
|
|
Ok(Err(type_error(
|
|
|
|
|
"NetworkError when attempting to fetch resource.",
|
|
|
|
|
)))
|
|
|
|
|
};
|
2023-08-09 12:47:47 -04:00
|
|
|
|
(Box::pin(fut), None)
|
2021-11-01 00:29:46 -04:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
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 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)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2023-12-01 10:56:10 -05:00
|
|
|
|
#[allow(clippy::type_complexity)]
|
|
|
|
|
pub struct ResourceToBodyAdapter(
|
|
|
|
|
Rc<dyn Resource>,
|
|
|
|
|
Option<Pin<Box<dyn Future<Output = Result<BufView, Error>>>>>,
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
impl ResourceToBodyAdapter {
|
|
|
|
|
pub fn new(resource: Rc<dyn Resource>) -> Self {
|
|
|
|
|
let future = resource.clone().read(64 * 1024);
|
|
|
|
|
Self(resource, Some(future))
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// SAFETY: we only use this on a single-threaded executor
|
|
|
|
|
unsafe impl Send for ResourceToBodyAdapter {}
|
|
|
|
|
// SAFETY: we only use this on a single-threaded executor
|
|
|
|
|
unsafe impl Sync for ResourceToBodyAdapter {}
|
|
|
|
|
|
|
|
|
|
impl Stream for ResourceToBodyAdapter {
|
|
|
|
|
type Item = Result<BufView, Error>;
|
|
|
|
|
|
|
|
|
|
fn poll_next(
|
|
|
|
|
self: Pin<&mut Self>,
|
|
|
|
|
cx: &mut Context<'_>,
|
|
|
|
|
) -> Poll<Option<Self::Item>> {
|
|
|
|
|
let this = self.get_mut();
|
|
|
|
|
if let Some(mut fut) = this.1.take() {
|
|
|
|
|
match fut.poll_unpin(cx) {
|
|
|
|
|
Poll::Pending => {
|
|
|
|
|
this.1 = Some(fut);
|
|
|
|
|
Poll::Pending
|
|
|
|
|
}
|
|
|
|
|
Poll::Ready(res) => match res {
|
|
|
|
|
Ok(buf) if buf.is_empty() => Poll::Ready(None),
|
|
|
|
|
Ok(_) => {
|
|
|
|
|
this.1 = Some(this.0.clone().read(64 * 1024));
|
|
|
|
|
Poll::Ready(Some(res))
|
|
|
|
|
}
|
|
|
|
|
_ => Poll::Ready(Some(res)),
|
|
|
|
|
},
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
Poll::Ready(None)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl Drop for ResourceToBodyAdapter {
|
|
|
|
|
fn drop(&mut self) {
|
|
|
|
|
self.0.clone().close()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2023-09-23 08:04:47 -04:00
|
|
|
|
#[op2]
|
|
|
|
|
#[serde]
|
|
|
|
|
#[allow(clippy::too_many_arguments)]
|
2021-11-28 13:07:03 -05:00
|
|
|
|
pub fn op_fetch<FP>(
|
2021-01-10 14:54:29 -05:00
|
|
|
|
state: &mut OpState,
|
2023-09-23 08:04:47 -04:00
|
|
|
|
#[serde] method: ByteString,
|
|
|
|
|
#[string] url: String,
|
|
|
|
|
#[serde] headers: Vec<(ByteString, ByteString)>,
|
|
|
|
|
#[smi] client_rid: Option<u32>,
|
2022-04-23 12:49:06 -04:00
|
|
|
|
has_body: bool,
|
2023-09-23 08:04:47 -04:00
|
|
|
|
#[buffer] data: Option<JsBuffer>,
|
2023-12-01 10:56:10 -05:00
|
|
|
|
#[smi] resource: Option<ResourceId>,
|
2021-04-05 12:40:24 -04:00
|
|
|
|
) -> Result<FetchReturn, AnyError>
|
2020-09-18 09:20:55 -04:00
|
|
|
|
where
|
|
|
|
|
FP: FetchPermissions + 'static,
|
|
|
|
|
{
|
2023-07-28 03:01:06 -04:00
|
|
|
|
let (client, allow_host) = if let Some(rid) = client_rid {
|
2021-08-15 07:29:19 -04:00
|
|
|
|
let r = state.resource_table.get::<HttpClientResource>(rid)?;
|
2023-07-28 03:01:06 -04:00
|
|
|
|
(r.client.clone(), r.allow_host)
|
2020-09-18 09:20:55 -04:00
|
|
|
|
} else {
|
2023-07-28 03:01:06 -04:00
|
|
|
|
(get_or_create_client_from_state(state)?, false)
|
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();
|
2023-12-01 10:56:10 -05:00
|
|
|
|
let (request_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();
|
2023-08-09 12:47:47 -04:00
|
|
|
|
let (request, 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_cancel_handle_rid = maybe_cancel_handle
|
|
|
|
|
.map(|ch| state.resource_table.add(FetchCancelHandle(ch)));
|
|
|
|
|
|
2023-12-01 10:56:10 -05:00
|
|
|
|
(request_rid, maybe_cancel_handle_rid)
|
2021-11-01 00:29:46 -04:00
|
|
|
|
}
|
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
|
|
|
|
|
2023-12-01 10:56:10 -05:00
|
|
|
|
if has_body {
|
|
|
|
|
match (data, resource) {
|
|
|
|
|
(Some(data), _) => {
|
2021-04-10 17:38:15 -04:00
|
|
|
|
// 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
|
|
|
|
}
|
2023-12-01 10:56:10 -05:00
|
|
|
|
(_, Some(resource)) => {
|
|
|
|
|
let resource = state.resource_table.take_any(resource)?;
|
|
|
|
|
match resource.size_hint() {
|
|
|
|
|
(body_size, Some(n)) if body_size == n && body_size > 0 => {
|
|
|
|
|
request =
|
|
|
|
|
request.header(CONTENT_LENGTH, HeaderValue::from(body_size));
|
|
|
|
|
}
|
|
|
|
|
_ => {}
|
|
|
|
|
}
|
|
|
|
|
request = request
|
|
|
|
|
.body(Body::wrap_stream(ResourceToBodyAdapter::new(resource)))
|
|
|
|
|
}
|
|
|
|
|
(None, None) => unreachable!(),
|
2021-04-10 17:38:15 -04:00
|
|
|
|
}
|
|
|
|
|
} 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-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
|
|
|
|
|
2023-07-28 03:01:06 -04:00
|
|
|
|
if (name != HOST || allow_host) && name != 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
|
2023-12-01 10:56:10 -05:00
|
|
|
|
.map(|res| res.map_err(|err| err.into()))
|
2021-07-05 09:34:37 -04:00
|
|
|
|
};
|
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));
|
|
|
|
|
|
2023-12-01 10:56:10 -05:00
|
|
|
|
(request_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)));
|
|
|
|
|
|
2023-12-01 10:56:10 -05:00
|
|
|
|
(request_rid, 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,
|
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
|
|
|
|
}
|
|
|
|
|
|
2023-12-01 10:56:10 -05:00
|
|
|
|
#[derive(Default, 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>,
|
2023-06-13 08:11:27 -04:00
|
|
|
|
pub remote_addr_ip: Option<String>,
|
|
|
|
|
pub remote_addr_port: Option<u16>,
|
2023-12-01 10:56:10 -05:00
|
|
|
|
pub error: Option<String>,
|
2021-03-17 17:33:29 -04:00
|
|
|
|
}
|
|
|
|
|
|
2023-09-21 10:08:23 -04:00
|
|
|
|
#[op2(async)]
|
|
|
|
|
#[serde]
|
2021-01-10 14:54:29 -05:00
|
|
|
|
pub async fn op_fetch_send(
|
|
|
|
|
state: Rc<RefCell<OpState>>,
|
2023-09-21 10:08:23 -04:00
|
|
|
|
#[smi] rid: ResourceId,
|
2021-04-05 12:40:24 -04:00
|
|
|
|
) -> 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,
|
2023-12-01 10:56:10 -05:00
|
|
|
|
Ok(Err(err)) => {
|
|
|
|
|
// We're going to try and rescue the error cause from a stream and return it from this fetch.
|
|
|
|
|
// If any error in the chain is a reqwest body error, return that as a special result we can use to
|
|
|
|
|
// reconstruct an error chain (eg: `new TypeError(..., { cause: new Error(...) })`).
|
|
|
|
|
// TODO(mmastrac): it would be a lot easier if we just passed a v8::Global through here instead
|
|
|
|
|
let mut err_ref: &dyn std::error::Error = err.as_ref();
|
|
|
|
|
while let Some(err) = std::error::Error::source(err_ref) {
|
|
|
|
|
if let Some(err) = err.downcast_ref::<reqwest::Error>() {
|
|
|
|
|
if err.is_body() {
|
|
|
|
|
// Extracts the next error cause and uses that for the message
|
|
|
|
|
if let Some(err) = std::error::Error::source(err) {
|
|
|
|
|
return Ok(FetchResponse {
|
|
|
|
|
error: Some(err.to_string()),
|
|
|
|
|
..Default::default()
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
err_ref = err;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return Err(type_error(err.to_string()));
|
|
|
|
|
}
|
2021-06-06 09:37:17 -04:00
|
|
|
|
Err(_) => return Err(type_error("request was cancelled")),
|
2020-12-26 08:06:00 -05:00
|
|
|
|
};
|
2020-09-18 09:20:55 -04:00
|
|
|
|
|
|
|
|
|
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();
|
2023-06-13 08:11:27 -04:00
|
|
|
|
let remote_addr = res.remote_addr();
|
|
|
|
|
let (remote_addr_ip, remote_addr_port) = if let Some(addr) = remote_addr {
|
|
|
|
|
(Some(addr.ip().to_string()), Some(addr.port()))
|
|
|
|
|
} else {
|
|
|
|
|
(None, None)
|
|
|
|
|
};
|
2022-09-26 14:27:50 -04:00
|
|
|
|
|
2023-06-15 09:34:21 -04:00
|
|
|
|
let response_rid = state
|
|
|
|
|
.borrow_mut()
|
|
|
|
|
.resource_table
|
|
|
|
|
.add(FetchResponseResource::new(res, content_length));
|
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,
|
2023-06-13 08:11:27 -04:00
|
|
|
|
response_rid,
|
2022-09-26 14:27:50 -04:00
|
|
|
|
content_length,
|
2023-06-13 08:11:27 -04:00
|
|
|
|
remote_addr_ip,
|
|
|
|
|
remote_addr_port,
|
2023-12-01 10:56:10 -05:00
|
|
|
|
error: None,
|
2021-04-05 12:40:24 -04:00
|
|
|
|
})
|
2021-03-17 17:33:29 -04:00
|
|
|
|
}
|
|
|
|
|
|
2023-09-21 10:08:23 -04:00
|
|
|
|
#[op2(async)]
|
|
|
|
|
#[smi]
|
2023-06-13 08:11:27 -04:00
|
|
|
|
pub async fn op_fetch_response_upgrade(
|
|
|
|
|
state: Rc<RefCell<OpState>>,
|
2023-09-21 10:08:23 -04:00
|
|
|
|
#[smi] rid: ResourceId,
|
2023-06-13 08:11:27 -04:00
|
|
|
|
) -> Result<ResourceId, AnyError> {
|
|
|
|
|
let raw_response = state
|
|
|
|
|
.borrow_mut()
|
|
|
|
|
.resource_table
|
|
|
|
|
.take::<FetchResponseResource>(rid)?;
|
|
|
|
|
let raw_response = Rc::try_unwrap(raw_response)
|
|
|
|
|
.expect("Someone is holding onto FetchResponseResource");
|
|
|
|
|
|
|
|
|
|
let (read, write) = tokio::io::duplex(1024);
|
|
|
|
|
let (read_rx, write_tx) = tokio::io::split(read);
|
|
|
|
|
let (mut write_rx, mut read_tx) = tokio::io::split(write);
|
2023-06-15 09:34:21 -04:00
|
|
|
|
let upgraded = raw_response.upgrade().await?;
|
2023-06-13 08:11:27 -04:00
|
|
|
|
{
|
|
|
|
|
// Stage 3: Pump the data
|
|
|
|
|
let (mut upgraded_rx, mut upgraded_tx) = tokio::io::split(upgraded);
|
|
|
|
|
|
|
|
|
|
spawn(async move {
|
|
|
|
|
let mut buf = [0; 1024];
|
|
|
|
|
loop {
|
|
|
|
|
let read = upgraded_rx.read(&mut buf).await?;
|
|
|
|
|
if read == 0 {
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
read_tx.write_all(&buf[..read]).await?;
|
|
|
|
|
}
|
|
|
|
|
Ok::<_, AnyError>(())
|
|
|
|
|
});
|
|
|
|
|
spawn(async move {
|
|
|
|
|
let mut buf = [0; 1024];
|
|
|
|
|
loop {
|
|
|
|
|
let read = write_rx.read(&mut buf).await?;
|
|
|
|
|
if read == 0 {
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
upgraded_tx.write_all(&buf[..read]).await?;
|
|
|
|
|
}
|
|
|
|
|
Ok::<_, AnyError>(())
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Ok(
|
|
|
|
|
state
|
|
|
|
|
.borrow_mut()
|
|
|
|
|
.resource_table
|
|
|
|
|
.add(UpgradeStream::new(read_rx, write_tx)),
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
struct UpgradeStream {
|
|
|
|
|
read: AsyncRefCell<tokio::io::ReadHalf<tokio::io::DuplexStream>>,
|
|
|
|
|
write: AsyncRefCell<tokio::io::WriteHalf<tokio::io::DuplexStream>>,
|
|
|
|
|
cancel_handle: CancelHandle,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl UpgradeStream {
|
|
|
|
|
pub fn new(
|
|
|
|
|
read: tokio::io::ReadHalf<tokio::io::DuplexStream>,
|
|
|
|
|
write: tokio::io::WriteHalf<tokio::io::DuplexStream>,
|
|
|
|
|
) -> Self {
|
|
|
|
|
Self {
|
|
|
|
|
read: AsyncRefCell::new(read),
|
|
|
|
|
write: AsyncRefCell::new(write),
|
|
|
|
|
cancel_handle: CancelHandle::new(),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async fn read(self: Rc<Self>, buf: &mut [u8]) -> Result<usize, AnyError> {
|
|
|
|
|
let cancel_handle = RcRef::map(self.clone(), |this| &this.cancel_handle);
|
|
|
|
|
async {
|
|
|
|
|
let read = RcRef::map(self, |this| &this.read);
|
|
|
|
|
let mut read = read.borrow_mut().await;
|
|
|
|
|
Ok(Pin::new(&mut *read).read(buf).await?)
|
|
|
|
|
}
|
|
|
|
|
.try_or_cancel(cancel_handle)
|
|
|
|
|
.await
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async fn write(self: Rc<Self>, buf: &[u8]) -> Result<usize, AnyError> {
|
|
|
|
|
let cancel_handle = RcRef::map(self.clone(), |this| &this.cancel_handle);
|
|
|
|
|
async {
|
|
|
|
|
let write = RcRef::map(self, |this| &this.write);
|
|
|
|
|
let mut write = write.borrow_mut().await;
|
|
|
|
|
Ok(Pin::new(&mut *write).write(buf).await?)
|
|
|
|
|
}
|
|
|
|
|
.try_or_cancel(cancel_handle)
|
|
|
|
|
.await
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl Resource for UpgradeStream {
|
|
|
|
|
fn name(&self) -> Cow<str> {
|
|
|
|
|
"fetchUpgradedStream".into()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
deno_core::impl_readable_byob!();
|
|
|
|
|
deno_core::impl_writable!();
|
|
|
|
|
|
|
|
|
|
fn close(self: Rc<Self>) {
|
|
|
|
|
self.cancel_handle.cancel();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
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-01-10 14:54:29 -05:00
|
|
|
|
type BytesStream =
|
|
|
|
|
Pin<Box<dyn Stream<Item = Result<bytes::Bytes, std::io::Error>> + Unpin>>;
|
|
|
|
|
|
2023-06-15 09:34:21 -04:00
|
|
|
|
pub enum FetchResponseReader {
|
|
|
|
|
Start(Response),
|
|
|
|
|
BodyReader(Peekable<BytesStream>),
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl Default for FetchResponseReader {
|
|
|
|
|
fn default() -> Self {
|
|
|
|
|
let stream: BytesStream = Box::pin(deno_core::futures::stream::empty());
|
|
|
|
|
Self::BodyReader(stream.peekable())
|
|
|
|
|
}
|
|
|
|
|
}
|
2023-06-13 08:11:27 -04:00
|
|
|
|
#[derive(Debug)]
|
|
|
|
|
pub struct FetchResponseResource {
|
2023-06-15 09:34:21 -04:00
|
|
|
|
pub response_reader: AsyncRefCell<FetchResponseReader>,
|
|
|
|
|
pub cancel: CancelHandle,
|
2023-06-13 08:11:27 -04:00
|
|
|
|
pub size: Option<u64>,
|
|
|
|
|
}
|
|
|
|
|
|
2023-06-15 09:34:21 -04:00
|
|
|
|
impl FetchResponseResource {
|
|
|
|
|
pub fn new(response: Response, size: Option<u64>) -> Self {
|
|
|
|
|
Self {
|
|
|
|
|
response_reader: AsyncRefCell::new(FetchResponseReader::Start(response)),
|
|
|
|
|
cancel: CancelHandle::default(),
|
|
|
|
|
size,
|
|
|
|
|
}
|
2023-06-13 08:11:27 -04:00
|
|
|
|
}
|
|
|
|
|
|
2023-06-15 09:34:21 -04:00
|
|
|
|
pub async fn upgrade(self) -> Result<reqwest::Upgraded, AnyError> {
|
|
|
|
|
let reader = self.response_reader.into_inner();
|
|
|
|
|
match reader {
|
|
|
|
|
FetchResponseReader::Start(resp) => Ok(resp.upgrade().await?),
|
|
|
|
|
_ => unreachable!(),
|
|
|
|
|
}
|
|
|
|
|
}
|
2020-12-16 11:14:12 -05:00
|
|
|
|
}
|
|
|
|
|
|
2023-06-15 09:34:21 -04:00
|
|
|
|
impl Resource for FetchResponseResource {
|
2020-12-16 11:14:12 -05:00
|
|
|
|
fn name(&self) -> Cow<str> {
|
2023-06-15 09:34:21 -04:00
|
|
|
|
"fetchResponse".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 {
|
2023-06-15 09:34:21 -04:00
|
|
|
|
let mut reader =
|
|
|
|
|
RcRef::map(&self, |r| &r.response_reader).borrow_mut().await;
|
2022-10-09 10:49:25 -04:00
|
|
|
|
|
2023-06-15 09:34:21 -04:00
|
|
|
|
let body = loop {
|
|
|
|
|
match &mut *reader {
|
|
|
|
|
FetchResponseReader::BodyReader(reader) => break reader,
|
|
|
|
|
FetchResponseReader::Start(_) => {}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
match std::mem::take(&mut *reader) {
|
|
|
|
|
FetchResponseReader::Start(resp) => {
|
|
|
|
|
let stream: BytesStream = Box::pin(resp.bytes_stream().map(|r| {
|
|
|
|
|
r.map_err(|err| {
|
|
|
|
|
std::io::Error::new(std::io::ErrorKind::Other, err)
|
|
|
|
|
})
|
|
|
|
|
}));
|
|
|
|
|
*reader = FetchResponseReader::BodyReader(stream.peekable());
|
|
|
|
|
}
|
|
|
|
|
FetchResponseReader::BodyReader(_) => unreachable!(),
|
|
|
|
|
}
|
|
|
|
|
};
|
2022-10-09 10:49:25 -04:00
|
|
|
|
let fut = async move {
|
2023-06-15 09:34:21 -04:00
|
|
|
|
let mut reader = Pin::new(body);
|
2022-10-09 10:49:25 -04:00
|
|
|
|
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,
|
2023-07-28 03:01:06 -04:00
|
|
|
|
pub allow_host: bool,
|
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 {
|
2023-07-28 03:01:06 -04:00
|
|
|
|
fn new(client: Client, allow_host: bool) -> Self {
|
|
|
|
|
Self { client, allow_host }
|
2020-09-18 09:20:55 -04:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
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,
|
2023-07-28 03:01:06 -04:00
|
|
|
|
#[serde(default)]
|
|
|
|
|
allow_host: bool,
|
2023-05-20 21:43:54 -04:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn default_true() -> bool {
|
|
|
|
|
true
|
2021-06-21 23:21:57 -04:00
|
|
|
|
}
|
|
|
|
|
|
2023-09-21 10:08:23 -04:00
|
|
|
|
#[op2]
|
|
|
|
|
#[smi]
|
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-09-21 10:08:23 -04:00
|
|
|
|
#[serde] 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
|
|
|
|
|
2023-07-28 03:01:06 -04:00
|
|
|
|
let rid = state
|
|
|
|
|
.resource_table
|
|
|
|
|
.add(HttpClientResource::new(client, args.allow_host));
|
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,
|
2023-11-01 17:11:01 -04:00
|
|
|
|
deno_tls::SocketUse::Http,
|
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
|
|
|
|
}
|
2023-10-31 13:16:27 -04:00
|
|
|
|
|
|
|
|
|
#[op2]
|
|
|
|
|
#[serde]
|
|
|
|
|
pub fn op_utf8_to_byte_string(
|
|
|
|
|
#[string] input: String,
|
|
|
|
|
) -> Result<ByteString, AnyError> {
|
|
|
|
|
Ok(input.into())
|
|
|
|
|
}
|