2024-01-01 14:58:21 -05:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2024-06-03 17:17:08 -04:00
|
|
|
|
2022-12-12 20:52:10 -05:00
|
|
|
use crate::util::progress_bar::UpdateGuard;
|
2024-08-15 17:47:16 -04:00
|
|
|
use crate::version;
|
2021-02-15 21:50:27 -05:00
|
|
|
|
2024-12-16 18:39:40 -05:00
|
|
|
use boxed_error::Boxed;
|
|
|
|
use deno_cache_dir::file_fetcher::RedirectHeaderParseError;
|
2021-11-08 20:26:39 -05:00
|
|
|
use deno_core::error::custom_error;
|
2020-09-14 12:48:57 -04:00
|
|
|
use deno_core::error::AnyError;
|
2022-12-12 20:52:10 -05:00
|
|
|
use deno_core::futures::StreamExt;
|
2024-06-03 17:17:08 -04:00
|
|
|
use deno_core::parking_lot::Mutex;
|
2024-07-17 19:37:31 -04:00
|
|
|
use deno_core::serde;
|
|
|
|
use deno_core::serde_json;
|
2020-09-16 14:28:07 -04:00
|
|
|
use deno_core::url::Url;
|
2024-07-17 19:37:31 -04:00
|
|
|
use deno_runtime::deno_fetch;
|
2022-11-18 17:28:14 -05:00
|
|
|
use deno_runtime::deno_fetch::create_http_client;
|
2023-05-20 21:43:54 -04:00
|
|
|
use deno_runtime::deno_fetch::CreateHttpClientOptions;
|
2024-12-16 18:39:40 -05:00
|
|
|
use deno_runtime::deno_fetch::ResBody;
|
2023-05-01 16:42:05 -04:00
|
|
|
use deno_runtime::deno_tls::RootCertStoreProvider;
|
2024-07-17 19:37:31 -04:00
|
|
|
use http::header::HeaderName;
|
|
|
|
use http::header::HeaderValue;
|
2024-08-07 05:16:27 -04:00
|
|
|
use http::header::CONTENT_LENGTH;
|
2024-12-16 18:39:40 -05:00
|
|
|
use http::HeaderMap;
|
2024-07-17 19:37:31 -04:00
|
|
|
use http::StatusCode;
|
|
|
|
use http_body_util::BodyExt;
|
|
|
|
|
2020-02-19 08:17:13 -05:00
|
|
|
use std::collections::HashMap;
|
2023-05-01 16:42:05 -04:00
|
|
|
use std::sync::Arc;
|
2024-06-03 17:17:08 -04:00
|
|
|
use std::thread::ThreadId;
|
2024-06-05 17:24:52 -04:00
|
|
|
use thiserror::Error;
|
2019-04-25 13:29:21 -04:00
|
|
|
|
2024-12-16 18:39:40 -05:00
|
|
|
#[derive(Debug, Error)]
|
|
|
|
pub enum SendError {
|
|
|
|
#[error(transparent)]
|
|
|
|
Send(#[from] deno_fetch::ClientSendError),
|
|
|
|
#[error(transparent)]
|
|
|
|
InvalidUri(#[from] http::uri::InvalidUri),
|
2024-06-03 17:17:08 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
pub struct HttpClientProvider {
|
2023-05-20 21:43:54 -04:00
|
|
|
options: CreateHttpClientOptions,
|
2023-05-01 16:42:05 -04:00
|
|
|
root_cert_store_provider: Option<Arc<dyn RootCertStoreProvider>>,
|
2024-06-03 17:17:08 -04:00
|
|
|
// it's not safe to share a reqwest::Client across tokio runtimes,
|
|
|
|
// so we store these Clients keyed by thread id
|
|
|
|
// https://github.com/seanmonstar/reqwest/issues/1148#issuecomment-910868788
|
2024-07-17 19:37:31 -04:00
|
|
|
clients_by_thread_id: Mutex<HashMap<ThreadId, deno_fetch::Client>>,
|
2023-05-01 16:42:05 -04:00
|
|
|
}
|
|
|
|
|
2024-06-03 17:17:08 -04:00
|
|
|
impl std::fmt::Debug for HttpClientProvider {
|
2023-05-01 16:42:05 -04:00
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
|
|
f.debug_struct("HttpClient")
|
2023-05-20 21:43:54 -04:00
|
|
|
.field("options", &self.options)
|
2023-05-01 16:42:05 -04:00
|
|
|
.finish()
|
|
|
|
}
|
|
|
|
}
|
2019-04-25 13:29:21 -04:00
|
|
|
|
2024-06-03 17:17:08 -04:00
|
|
|
impl HttpClientProvider {
|
2022-11-18 17:28:14 -05:00
|
|
|
pub fn new(
|
2023-05-01 16:42:05 -04:00
|
|
|
root_cert_store_provider: Option<Arc<dyn RootCertStoreProvider>>,
|
2022-11-18 17:28:14 -05:00
|
|
|
unsafely_ignore_certificate_errors: Option<Vec<String>>,
|
2023-05-01 16:42:05 -04:00
|
|
|
) -> Self {
|
|
|
|
Self {
|
2023-05-20 21:43:54 -04:00
|
|
|
options: CreateHttpClientOptions {
|
|
|
|
unsafely_ignore_certificate_errors,
|
|
|
|
..Default::default()
|
|
|
|
},
|
2023-05-01 16:42:05 -04:00
|
|
|
root_cert_store_provider,
|
2024-06-03 17:17:08 -04:00
|
|
|
clients_by_thread_id: Default::default(),
|
2023-05-01 16:42:05 -04:00
|
|
|
}
|
2021-02-15 21:50:27 -05:00
|
|
|
}
|
2022-11-18 17:28:14 -05:00
|
|
|
|
2024-06-03 17:17:08 -04:00
|
|
|
pub fn get_or_create(&self) -> Result<HttpClient, AnyError> {
|
|
|
|
use std::collections::hash_map::Entry;
|
|
|
|
let thread_id = std::thread::current().id();
|
|
|
|
let mut clients = self.clients_by_thread_id.lock();
|
|
|
|
let entry = clients.entry(thread_id);
|
|
|
|
match entry {
|
|
|
|
Entry::Occupied(entry) => Ok(HttpClient::new(entry.get().clone())),
|
|
|
|
Entry::Vacant(entry) => {
|
|
|
|
let client = create_http_client(
|
2024-08-15 17:47:16 -04:00
|
|
|
version::DENO_VERSION_INFO.user_agent,
|
2024-06-03 17:17:08 -04:00
|
|
|
CreateHttpClientOptions {
|
|
|
|
root_cert_store: match &self.root_cert_store_provider {
|
|
|
|
Some(provider) => Some(provider.get_or_try_init()?.clone()),
|
|
|
|
None => None,
|
|
|
|
},
|
|
|
|
..self.options.clone()
|
|
|
|
},
|
|
|
|
)?;
|
|
|
|
entry.insert(client.clone());
|
|
|
|
Ok(HttpClient::new(client))
|
|
|
|
}
|
|
|
|
}
|
2023-05-01 16:42:05 -04:00
|
|
|
}
|
2024-06-03 17:17:08 -04:00
|
|
|
}
|
2023-05-01 16:42:05 -04:00
|
|
|
|
2024-06-05 17:24:52 -04:00
|
|
|
#[derive(Debug, Error)]
|
|
|
|
#[error("Bad response: {:?}{}", .status_code, .response_text.as_ref().map(|s| format!("\n\n{}", s)).unwrap_or_else(String::new))]
|
|
|
|
pub struct BadResponseError {
|
|
|
|
pub status_code: StatusCode,
|
|
|
|
pub response_text: Option<String>,
|
|
|
|
}
|
|
|
|
|
2024-12-16 18:39:40 -05:00
|
|
|
#[derive(Debug, Boxed)]
|
|
|
|
pub struct DownloadError(pub Box<DownloadErrorKind>);
|
|
|
|
|
2024-06-05 17:24:52 -04:00
|
|
|
#[derive(Debug, Error)]
|
2024-12-16 18:39:40 -05:00
|
|
|
pub enum DownloadErrorKind {
|
2024-06-05 17:24:52 -04:00
|
|
|
#[error(transparent)]
|
2024-07-17 19:37:31 -04:00
|
|
|
Fetch(AnyError),
|
|
|
|
#[error(transparent)]
|
|
|
|
UrlParse(#[from] deno_core::url::ParseError),
|
|
|
|
#[error(transparent)]
|
|
|
|
HttpParse(#[from] http::Error),
|
|
|
|
#[error(transparent)]
|
|
|
|
Json(#[from] serde_json::Error),
|
2024-06-05 17:24:52 -04:00
|
|
|
#[error(transparent)]
|
2024-07-17 19:37:31 -04:00
|
|
|
ToStr(#[from] http::header::ToStrError),
|
2024-12-16 18:39:40 -05:00
|
|
|
#[error(transparent)]
|
|
|
|
RedirectHeaderParse(RedirectHeaderParseError),
|
2024-06-05 17:24:52 -04:00
|
|
|
#[error("Too many redirects.")]
|
|
|
|
TooManyRedirects,
|
|
|
|
#[error(transparent)]
|
|
|
|
BadResponse(#[from] BadResponseError),
|
|
|
|
}
|
|
|
|
|
2024-06-03 17:17:08 -04:00
|
|
|
#[derive(Debug)]
|
|
|
|
pub struct HttpClient {
|
2024-07-17 19:37:31 -04:00
|
|
|
client: deno_fetch::Client,
|
2024-06-03 17:17:08 -04:00
|
|
|
// don't allow sending this across threads because then
|
|
|
|
// it might be shared accidentally across tokio runtimes
|
|
|
|
// which will cause issues
|
|
|
|
// https://github.com/seanmonstar/reqwest/issues/1148#issuecomment-910868788
|
|
|
|
_unsend_marker: deno_core::unsync::UnsendMarker,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl HttpClient {
|
|
|
|
// DO NOT make this public. You should always be creating one of these from
|
|
|
|
// the HttpClientProvider
|
2024-07-17 19:37:31 -04:00
|
|
|
fn new(client: deno_fetch::Client) -> Self {
|
2024-06-03 17:17:08 -04:00
|
|
|
Self {
|
|
|
|
client,
|
|
|
|
_unsend_marker: deno_core::unsync::UnsendMarker::default(),
|
|
|
|
}
|
2021-12-20 21:40:22 -05:00
|
|
|
}
|
2020-01-11 05:11:05 -05:00
|
|
|
|
2024-07-17 19:37:31 -04:00
|
|
|
pub fn get(&self, url: Url) -> Result<RequestBuilder, http::Error> {
|
|
|
|
let body = http_body_util::Empty::new()
|
|
|
|
.map_err(|never| match never {})
|
|
|
|
.boxed();
|
|
|
|
let mut req = http::Request::new(body);
|
|
|
|
*req.uri_mut() = url.as_str().parse()?;
|
|
|
|
Ok(RequestBuilder {
|
|
|
|
client: self.client.clone(),
|
|
|
|
req,
|
|
|
|
})
|
2024-06-03 17:17:08 -04:00
|
|
|
}
|
|
|
|
|
2024-07-17 19:37:31 -04:00
|
|
|
pub fn post(
|
|
|
|
&self,
|
|
|
|
url: Url,
|
|
|
|
body: deno_fetch::ReqBody,
|
|
|
|
) -> Result<RequestBuilder, http::Error> {
|
|
|
|
let mut req = http::Request::new(body);
|
|
|
|
*req.method_mut() = http::Method::POST;
|
|
|
|
*req.uri_mut() = url.as_str().parse()?;
|
|
|
|
Ok(RequestBuilder {
|
|
|
|
client: self.client.clone(),
|
|
|
|
req,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn post_json<S>(
|
|
|
|
&self,
|
|
|
|
url: Url,
|
|
|
|
ser: &S,
|
|
|
|
) -> Result<RequestBuilder, DownloadError>
|
|
|
|
where
|
|
|
|
S: serde::Serialize,
|
|
|
|
{
|
|
|
|
let json = deno_core::serde_json::to_vec(ser)?;
|
|
|
|
let body = http_body_util::Full::new(json.into())
|
|
|
|
.map_err(|never| match never {})
|
|
|
|
.boxed();
|
|
|
|
let builder = self.post(url, body)?;
|
|
|
|
Ok(builder.header(
|
|
|
|
http::header::CONTENT_TYPE,
|
|
|
|
"application/json".parse().map_err(http::Error::from)?,
|
|
|
|
))
|
2024-06-03 17:17:08 -04:00
|
|
|
}
|
|
|
|
|
2024-12-16 18:39:40 -05:00
|
|
|
pub async fn send(
|
2022-12-14 08:47:18 -05:00
|
|
|
&self,
|
2024-12-16 18:39:40 -05:00
|
|
|
url: &Url,
|
|
|
|
headers: HeaderMap,
|
|
|
|
) -> Result<http::Response<ResBody>, SendError> {
|
2024-07-17 19:37:31 -04:00
|
|
|
let body = http_body_util::Empty::new()
|
|
|
|
.map_err(|never| match never {})
|
|
|
|
.boxed();
|
|
|
|
let mut request = http::Request::new(body);
|
2024-12-16 18:39:40 -05:00
|
|
|
*request.uri_mut() = http::Uri::try_from(url.as_str())?;
|
|
|
|
*request.headers_mut() = headers;
|
2024-06-03 17:17:08 -04:00
|
|
|
|
2024-12-16 18:39:40 -05:00
|
|
|
self
|
|
|
|
.client
|
|
|
|
.clone()
|
|
|
|
.send(request)
|
|
|
|
.await
|
|
|
|
.map_err(SendError::Send)
|
2020-09-04 06:43:20 -04:00
|
|
|
}
|
2019-12-30 08:57:17 -05:00
|
|
|
|
2024-07-17 19:37:31 -04:00
|
|
|
pub async fn download_text(&self, url: Url) -> Result<String, AnyError> {
|
2022-12-14 08:47:18 -05:00
|
|
|
let bytes = self.download(url).await?;
|
|
|
|
Ok(String::from_utf8(bytes)?)
|
|
|
|
}
|
|
|
|
|
2024-07-17 19:37:31 -04:00
|
|
|
pub async fn download(&self, url: Url) -> Result<Vec<u8>, AnyError> {
|
2024-06-03 17:17:08 -04:00
|
|
|
let maybe_bytes = self.download_inner(url, None, None).await?;
|
2022-12-14 08:47:18 -05:00
|
|
|
match maybe_bytes {
|
|
|
|
Some(bytes) => Ok(bytes),
|
|
|
|
None => Err(custom_error("Http", "Not found.")),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-10-15 19:46:42 -04:00
|
|
|
pub async fn download_with_progress_and_retries(
|
2022-12-12 20:52:10 -05:00
|
|
|
&self,
|
2024-07-17 19:37:31 -04:00
|
|
|
url: Url,
|
2024-05-23 17:26:23 -04:00
|
|
|
maybe_header: Option<(HeaderName, HeaderValue)>,
|
2022-12-12 20:52:10 -05:00
|
|
|
progress_guard: &UpdateGuard,
|
2024-06-05 17:24:52 -04:00
|
|
|
) -> Result<Option<Vec<u8>>, DownloadError> {
|
2024-10-15 19:46:42 -04:00
|
|
|
crate::util::retry::retry(
|
|
|
|
|| {
|
|
|
|
self.download_inner(
|
|
|
|
url.clone(),
|
|
|
|
maybe_header.clone(),
|
|
|
|
Some(progress_guard),
|
|
|
|
)
|
|
|
|
},
|
2024-12-16 18:39:40 -05:00
|
|
|
|e| {
|
|
|
|
matches!(
|
|
|
|
e.as_kind(),
|
|
|
|
DownloadErrorKind::BadResponse(_) | DownloadErrorKind::Fetch(_)
|
|
|
|
)
|
|
|
|
},
|
2024-10-15 19:46:42 -04:00
|
|
|
)
|
|
|
|
.await
|
2022-12-14 08:47:18 -05:00
|
|
|
}
|
|
|
|
|
2024-06-03 17:17:08 -04:00
|
|
|
pub async fn get_redirected_url(
|
2022-12-14 08:47:18 -05:00
|
|
|
&self,
|
2024-07-17 19:37:31 -04:00
|
|
|
url: Url,
|
2024-06-03 17:17:08 -04:00
|
|
|
maybe_header: Option<(HeaderName, HeaderValue)>,
|
|
|
|
) -> Result<Url, AnyError> {
|
2024-07-17 19:37:31 -04:00
|
|
|
let (_, url) = self.get_redirected_response(url, maybe_header).await?;
|
|
|
|
Ok(url)
|
2024-06-03 17:17:08 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
async fn download_inner(
|
|
|
|
&self,
|
2024-07-17 19:37:31 -04:00
|
|
|
url: Url,
|
2024-05-23 17:26:23 -04:00
|
|
|
maybe_header: Option<(HeaderName, HeaderValue)>,
|
2022-12-14 08:47:18 -05:00
|
|
|
progress_guard: Option<&UpdateGuard>,
|
2024-06-05 17:24:52 -04:00
|
|
|
) -> Result<Option<Vec<u8>>, DownloadError> {
|
2024-07-17 19:37:31 -04:00
|
|
|
let (response, _) = self.get_redirected_response(url, maybe_header).await?;
|
2022-12-12 20:52:10 -05:00
|
|
|
|
|
|
|
if response.status() == 404 {
|
2022-12-14 08:47:18 -05:00
|
|
|
return Ok(None);
|
2022-12-12 20:52:10 -05:00
|
|
|
} else if !response.status().is_success() {
|
|
|
|
let status = response.status();
|
2024-07-17 19:37:31 -04:00
|
|
|
let maybe_response_text = body_to_string(response).await.ok();
|
2024-12-16 18:39:40 -05:00
|
|
|
return Err(
|
|
|
|
DownloadErrorKind::BadResponse(BadResponseError {
|
|
|
|
status_code: status,
|
|
|
|
response_text: maybe_response_text
|
|
|
|
.map(|s| s.trim().to_string())
|
|
|
|
.filter(|s| !s.is_empty()),
|
|
|
|
})
|
|
|
|
.into_box(),
|
|
|
|
);
|
2022-11-18 17:28:14 -05:00
|
|
|
}
|
|
|
|
|
2022-12-19 14:31:19 -05:00
|
|
|
get_response_body_with_progress(response, progress_guard)
|
|
|
|
.await
|
2024-12-16 18:39:40 -05:00
|
|
|
.map(|(_, body)| Some(body))
|
|
|
|
.map_err(|err| DownloadErrorKind::Fetch(err).into_box())
|
2022-12-14 08:47:18 -05:00
|
|
|
}
|
2022-11-18 17:28:14 -05:00
|
|
|
|
2024-06-03 17:17:08 -04:00
|
|
|
async fn get_redirected_response(
|
2022-12-14 08:47:18 -05:00
|
|
|
&self,
|
2024-07-17 19:37:31 -04:00
|
|
|
mut url: Url,
|
2024-05-23 17:26:23 -04:00
|
|
|
mut maybe_header: Option<(HeaderName, HeaderValue)>,
|
2024-07-17 19:37:31 -04:00
|
|
|
) -> Result<(http::Response<deno_fetch::ResBody>, Url), DownloadError> {
|
|
|
|
let mut req = self.get(url.clone())?.build();
|
2024-05-23 17:26:23 -04:00
|
|
|
if let Some((header_name, header_value)) = maybe_header.as_ref() {
|
2024-07-17 19:37:31 -04:00
|
|
|
req.headers_mut().append(header_name, header_value.clone());
|
2024-05-23 17:26:23 -04:00
|
|
|
}
|
2024-07-17 19:37:31 -04:00
|
|
|
let mut response = self
|
|
|
|
.client
|
|
|
|
.clone()
|
|
|
|
.send(req)
|
|
|
|
.await
|
2024-12-16 18:39:40 -05:00
|
|
|
.map_err(|e| DownloadErrorKind::Fetch(e.into()).into_box())?;
|
2022-12-14 08:47:18 -05:00
|
|
|
let status = response.status();
|
|
|
|
if status.is_redirection() {
|
|
|
|
for _ in 0..5 {
|
|
|
|
let new_url = resolve_redirect_from_response(&url, &response)?;
|
2024-07-17 19:37:31 -04:00
|
|
|
let mut req = self.get(new_url.clone())?.build();
|
2024-05-23 17:26:23 -04:00
|
|
|
|
|
|
|
if new_url.origin() == url.origin() {
|
|
|
|
if let Some((header_name, header_value)) = maybe_header.as_ref() {
|
2024-07-17 19:37:31 -04:00
|
|
|
req.headers_mut().append(header_name, header_value.clone());
|
2024-05-23 17:26:23 -04:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
maybe_header = None;
|
|
|
|
}
|
|
|
|
|
2024-07-17 19:37:31 -04:00
|
|
|
let new_response = self
|
|
|
|
.client
|
|
|
|
.clone()
|
|
|
|
.send(req)
|
|
|
|
.await
|
2024-12-16 18:39:40 -05:00
|
|
|
.map_err(|e| DownloadErrorKind::Fetch(e.into()).into_box())?;
|
2022-12-14 08:47:18 -05:00
|
|
|
let status = new_response.status();
|
|
|
|
if status.is_redirection() {
|
|
|
|
response = new_response;
|
|
|
|
url = new_url;
|
|
|
|
} else {
|
2024-07-17 19:37:31 -04:00
|
|
|
return Ok((new_response, new_url));
|
2022-12-14 08:47:18 -05:00
|
|
|
}
|
2022-11-18 17:28:14 -05:00
|
|
|
}
|
2024-12-16 18:39:40 -05:00
|
|
|
Err(DownloadErrorKind::TooManyRedirects.into_box())
|
2022-12-14 08:47:18 -05:00
|
|
|
} else {
|
2024-07-17 19:37:31 -04:00
|
|
|
Ok((response, url))
|
2022-11-18 17:28:14 -05:00
|
|
|
}
|
|
|
|
}
|
2019-04-01 21:46:40 -04:00
|
|
|
}
|
|
|
|
|
2024-12-16 18:39:40 -05:00
|
|
|
pub async fn get_response_body_with_progress(
|
2024-07-17 19:37:31 -04:00
|
|
|
response: http::Response<deno_fetch::ResBody>,
|
2022-12-19 14:31:19 -05:00
|
|
|
progress_guard: Option<&UpdateGuard>,
|
2024-12-16 18:39:40 -05:00
|
|
|
) -> Result<(HeaderMap, Vec<u8>), AnyError> {
|
2024-07-17 19:37:31 -04:00
|
|
|
use http_body::Body as _;
|
2022-12-19 14:31:19 -05:00
|
|
|
if let Some(progress_guard) = progress_guard {
|
2024-08-07 05:16:27 -04:00
|
|
|
let mut total_size = response.body().size_hint().exact();
|
|
|
|
if total_size.is_none() {
|
|
|
|
total_size = response
|
|
|
|
.headers()
|
|
|
|
.get(CONTENT_LENGTH)
|
|
|
|
.and_then(|val| val.to_str().ok())
|
|
|
|
.and_then(|s| s.parse::<u64>().ok());
|
|
|
|
}
|
|
|
|
if let Some(total_size) = total_size {
|
2022-12-19 14:31:19 -05:00
|
|
|
progress_guard.set_total_size(total_size);
|
|
|
|
let mut current_size = 0;
|
|
|
|
let mut data = Vec::with_capacity(total_size as usize);
|
2024-12-16 18:39:40 -05:00
|
|
|
let (parts, body) = response.into_parts();
|
|
|
|
let mut stream = body.into_data_stream();
|
2022-12-19 14:31:19 -05:00
|
|
|
while let Some(item) = stream.next().await {
|
|
|
|
let bytes = item?;
|
|
|
|
current_size += bytes.len() as u64;
|
|
|
|
progress_guard.set_position(current_size);
|
|
|
|
data.extend(bytes.into_iter());
|
|
|
|
}
|
2024-12-16 18:39:40 -05:00
|
|
|
return Ok((parts.headers, data));
|
2022-12-19 14:31:19 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-12-16 18:39:40 -05:00
|
|
|
let (parts, body) = response.into_parts();
|
|
|
|
let bytes = body.collect().await?.to_bytes();
|
|
|
|
Ok((parts.headers, bytes.into()))
|
2024-06-03 17:17:08 -04:00
|
|
|
}
|
|
|
|
|
2024-07-17 19:37:31 -04:00
|
|
|
fn resolve_redirect_from_response<B>(
|
2024-06-03 17:17:08 -04:00
|
|
|
request_url: &Url,
|
2024-07-17 19:37:31 -04:00
|
|
|
response: &http::Response<B>,
|
2024-06-05 17:24:52 -04:00
|
|
|
) -> Result<Url, DownloadError> {
|
2024-06-03 17:17:08 -04:00
|
|
|
debug_assert!(response.status().is_redirection());
|
2024-12-16 18:39:40 -05:00
|
|
|
deno_cache_dir::file_fetcher::resolve_redirect_from_headers(
|
|
|
|
request_url,
|
|
|
|
response.headers(),
|
|
|
|
)
|
|
|
|
.map_err(|err| DownloadErrorKind::RedirectHeaderParse(*err).into_box())
|
2024-06-03 17:17:08 -04:00
|
|
|
}
|
|
|
|
|
2024-07-17 19:37:31 -04:00
|
|
|
pub async fn body_to_string<B>(body: B) -> Result<String, AnyError>
|
|
|
|
where
|
|
|
|
B: http_body::Body,
|
|
|
|
AnyError: From<B::Error>,
|
|
|
|
{
|
|
|
|
let bytes = body.collect().await?.to_bytes();
|
|
|
|
let s = std::str::from_utf8(&bytes)?;
|
|
|
|
Ok(s.into())
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn body_to_json<B, D>(body: B) -> Result<D, AnyError>
|
|
|
|
where
|
|
|
|
B: http_body::Body,
|
|
|
|
AnyError: From<B::Error>,
|
|
|
|
D: serde::de::DeserializeOwned,
|
|
|
|
{
|
|
|
|
let bytes = body.collect().await?.to_bytes();
|
|
|
|
let val = deno_core::serde_json::from_slice(&bytes)?;
|
|
|
|
Ok(val)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct RequestBuilder {
|
|
|
|
client: deno_fetch::Client,
|
|
|
|
req: http::Request<deno_fetch::ReqBody>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl RequestBuilder {
|
|
|
|
pub fn header(mut self, name: HeaderName, value: HeaderValue) -> Self {
|
|
|
|
self.req.headers_mut().append(name, value);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn send(
|
|
|
|
self,
|
|
|
|
) -> Result<http::Response<deno_fetch::ResBody>, AnyError> {
|
2024-08-08 02:18:33 -04:00
|
|
|
self.client.send(self.req).await.map_err(Into::into)
|
2024-07-17 19:37:31 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn build(self) -> http::Request<deno_fetch::ReqBody> {
|
|
|
|
self.req
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-06-03 17:17:08 -04:00
|
|
|
#[allow(clippy::print_stdout)]
|
|
|
|
#[allow(clippy::print_stderr)]
|
2019-04-01 21:46:40 -04:00
|
|
|
#[cfg(test)]
|
2022-12-14 08:47:18 -05:00
|
|
|
mod test {
|
2024-06-03 17:17:08 -04:00
|
|
|
use std::collections::HashSet;
|
|
|
|
use std::hash::RandomState;
|
|
|
|
|
2024-07-01 20:09:47 -04:00
|
|
|
use deno_runtime::deno_tls::rustls::RootCertStore;
|
2024-06-03 17:17:08 -04:00
|
|
|
|
2019-04-25 13:29:21 -04:00
|
|
|
use super::*;
|
2020-12-11 18:36:18 -05:00
|
|
|
|
2020-02-03 08:53:50 -05:00
|
|
|
#[tokio::test]
|
2022-12-14 08:47:18 -05:00
|
|
|
async fn test_http_client_download_redirect() {
|
2020-08-10 17:31:05 -04:00
|
|
|
let _http_server_guard = test_util::http_server();
|
2024-06-03 17:17:08 -04:00
|
|
|
let client = HttpClientProvider::new(None, None).get_or_create().unwrap();
|
2020-01-11 05:11:05 -05:00
|
|
|
|
2022-12-14 08:47:18 -05:00
|
|
|
// make a request to the redirect server
|
|
|
|
let text = client
|
2024-07-17 19:37:31 -04:00
|
|
|
.download_text(
|
|
|
|
Url::parse("http://localhost:4546/subdir/redirects/redirect1.js")
|
|
|
|
.unwrap(),
|
|
|
|
)
|
2022-12-14 08:47:18 -05:00
|
|
|
.await
|
2021-08-11 10:20:47 -04:00
|
|
|
.unwrap();
|
2022-12-14 08:47:18 -05:00
|
|
|
assert_eq!(text, "export const redirect = 1;\n");
|
2020-01-11 05:11:05 -05:00
|
|
|
|
2022-12-14 08:47:18 -05:00
|
|
|
// now make one to the infinite redirects server
|
|
|
|
let err = client
|
2024-07-17 19:37:31 -04:00
|
|
|
.download_text(
|
|
|
|
Url::parse("http://localhost:4549/subdir/redirects/redirect1.js")
|
|
|
|
.unwrap(),
|
|
|
|
)
|
2022-12-14 08:47:18 -05:00
|
|
|
.await
|
|
|
|
.err()
|
2021-08-11 10:20:47 -04:00
|
|
|
.unwrap();
|
2022-12-14 08:47:18 -05:00
|
|
|
assert_eq!(err.to_string(), "Too many redirects.");
|
2019-04-25 13:29:21 -04:00
|
|
|
}
|
2018-11-29 22:01:01 -05:00
|
|
|
|
2024-06-03 17:17:08 -04:00
|
|
|
#[tokio::test]
|
|
|
|
async fn test_fetch_with_cafile_string() {
|
|
|
|
let _http_server_guard = test_util::http_server();
|
|
|
|
let url = Url::parse("https://localhost:5545/assets/fixture.json").unwrap();
|
|
|
|
|
|
|
|
let client = HttpClient::new(
|
|
|
|
create_http_client(
|
2024-08-15 17:47:16 -04:00
|
|
|
version::DENO_VERSION_INFO.user_agent,
|
2024-06-03 17:17:08 -04:00
|
|
|
CreateHttpClientOptions {
|
|
|
|
ca_certs: vec![std::fs::read(
|
|
|
|
test_util::testdata_path().join("tls/RootCA.pem"),
|
|
|
|
)
|
|
|
|
.unwrap()],
|
|
|
|
..Default::default()
|
|
|
|
},
|
|
|
|
)
|
|
|
|
.unwrap(),
|
|
|
|
);
|
2024-12-16 18:39:40 -05:00
|
|
|
let response = client.send(&url, Default::default()).await.unwrap();
|
|
|
|
assert!(response.status().is_success());
|
|
|
|
let (parts, body) = response.into_parts();
|
|
|
|
let headers = parts.headers;
|
|
|
|
let body = body.collect().await.unwrap().to_bytes();
|
|
|
|
assert!(!body.is_empty());
|
|
|
|
assert_eq!(headers.get("content-type").unwrap(), "application/json");
|
|
|
|
assert_eq!(headers.get("etag"), None);
|
|
|
|
assert_eq!(headers.get("x-typescript-types"), None);
|
2024-06-03 17:17:08 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
static PUBLIC_HTTPS_URLS: &[&str] = &[
|
|
|
|
"https://deno.com/",
|
|
|
|
"https://example.com/",
|
|
|
|
"https://github.com/",
|
|
|
|
"https://www.w3.org/",
|
|
|
|
];
|
|
|
|
|
|
|
|
/// This test depends on external servers, so we need to be careful to avoid mistaking an offline machine with a
|
|
|
|
/// test failure.
|
|
|
|
#[tokio::test]
|
|
|
|
async fn test_fetch_with_default_certificate_store() {
|
|
|
|
let urls: HashSet<_, RandomState> =
|
|
|
|
HashSet::from_iter(PUBLIC_HTTPS_URLS.iter());
|
|
|
|
|
|
|
|
// Rely on the randomization of hashset iteration
|
|
|
|
for url in urls {
|
|
|
|
// Relies on external http server with a valid mozilla root CA cert.
|
|
|
|
let url = Url::parse(url).unwrap();
|
|
|
|
eprintln!("Attempting to fetch {url}...");
|
|
|
|
|
|
|
|
let client = HttpClient::new(
|
|
|
|
create_http_client(
|
2024-08-15 17:47:16 -04:00
|
|
|
version::DENO_VERSION_INFO.user_agent,
|
2024-06-03 17:17:08 -04:00
|
|
|
CreateHttpClientOptions::default(),
|
|
|
|
)
|
|
|
|
.unwrap(),
|
|
|
|
);
|
|
|
|
|
2024-12-16 18:39:40 -05:00
|
|
|
let result = client.send(&url, Default::default()).await;
|
2024-06-03 17:17:08 -04:00
|
|
|
match result {
|
2024-12-16 18:39:40 -05:00
|
|
|
Ok(response) if response.status().is_success() => {
|
|
|
|
return; // success
|
2024-06-03 17:17:08 -04:00
|
|
|
}
|
2024-12-16 18:39:40 -05:00
|
|
|
_ => {
|
|
|
|
// keep going
|
2024-06-03 17:17:08 -04:00
|
|
|
}
|
2024-12-16 18:39:40 -05:00
|
|
|
}
|
2024-06-03 17:17:08 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// Use 1.1.1.1 and 8.8.8.8 as our last-ditch internet check
|
|
|
|
if std::net::TcpStream::connect("8.8.8.8:80").is_err()
|
|
|
|
&& std::net::TcpStream::connect("1.1.1.1:80").is_err()
|
|
|
|
{
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
panic!("None of the expected public URLs were available but internet appears to be available");
|
|
|
|
}
|
|
|
|
|
|
|
|
#[tokio::test]
|
|
|
|
async fn test_fetch_with_empty_certificate_store() {
|
|
|
|
let root_cert_store = RootCertStore::empty();
|
|
|
|
let urls: HashSet<_, RandomState> =
|
|
|
|
HashSet::from_iter(PUBLIC_HTTPS_URLS.iter());
|
|
|
|
|
|
|
|
// Rely on the randomization of hashset iteration
|
|
|
|
let url = urls.into_iter().next().unwrap();
|
|
|
|
// Relies on external http server with a valid mozilla root CA cert.
|
|
|
|
let url = Url::parse(url).unwrap();
|
|
|
|
eprintln!("Attempting to fetch {url}...");
|
|
|
|
|
|
|
|
let client = HttpClient::new(
|
|
|
|
create_http_client(
|
2024-08-15 17:47:16 -04:00
|
|
|
version::DENO_VERSION_INFO.user_agent,
|
2024-06-03 17:17:08 -04:00
|
|
|
CreateHttpClientOptions {
|
|
|
|
root_cert_store: Some(root_cert_store),
|
|
|
|
..Default::default()
|
|
|
|
},
|
|
|
|
)
|
|
|
|
.unwrap(),
|
|
|
|
);
|
|
|
|
|
2024-12-16 18:39:40 -05:00
|
|
|
let result = client.send(&url, HeaderMap::new()).await;
|
|
|
|
assert!(result.is_err() || !result.unwrap().status().is_success());
|
2024-06-03 17:17:08 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
#[tokio::test]
|
|
|
|
async fn test_fetch_with_cafile_gzip() {
|
|
|
|
let _http_server_guard = test_util::http_server();
|
|
|
|
let url =
|
|
|
|
Url::parse("https://localhost:5545/run/import_compression/gziped")
|
|
|
|
.unwrap();
|
|
|
|
let client = HttpClient::new(
|
|
|
|
create_http_client(
|
2024-08-15 17:47:16 -04:00
|
|
|
version::DENO_VERSION_INFO.user_agent,
|
2024-06-03 17:17:08 -04:00
|
|
|
CreateHttpClientOptions {
|
|
|
|
ca_certs: vec![std::fs::read(
|
|
|
|
test_util::testdata_path()
|
|
|
|
.join("tls/RootCA.pem")
|
|
|
|
.to_string(),
|
|
|
|
)
|
|
|
|
.unwrap()],
|
|
|
|
..Default::default()
|
|
|
|
},
|
|
|
|
)
|
|
|
|
.unwrap(),
|
|
|
|
);
|
2024-12-16 18:39:40 -05:00
|
|
|
let response = client.send(&url, Default::default()).await.unwrap();
|
|
|
|
assert!(response.status().is_success());
|
|
|
|
let (parts, body) = response.into_parts();
|
|
|
|
let headers = parts.headers;
|
|
|
|
let body = body.collect().await.unwrap().to_bytes().to_vec();
|
|
|
|
assert_eq!(String::from_utf8(body).unwrap(), "console.log('gzip')");
|
|
|
|
assert_eq!(
|
|
|
|
headers.get("content-type").unwrap(),
|
|
|
|
"application/javascript"
|
|
|
|
);
|
|
|
|
assert_eq!(headers.get("etag"), None);
|
|
|
|
assert_eq!(headers.get("x-typescript-types"), None);
|
2024-06-03 17:17:08 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
#[tokio::test]
|
|
|
|
async fn test_fetch_with_cafile_with_etag() {
|
|
|
|
let _http_server_guard = test_util::http_server();
|
|
|
|
let url = Url::parse("https://localhost:5545/etag_script.ts").unwrap();
|
|
|
|
let client = HttpClient::new(
|
|
|
|
create_http_client(
|
2024-08-15 17:47:16 -04:00
|
|
|
version::DENO_VERSION_INFO.user_agent,
|
2024-06-03 17:17:08 -04:00
|
|
|
CreateHttpClientOptions {
|
|
|
|
ca_certs: vec![std::fs::read(
|
|
|
|
test_util::testdata_path()
|
|
|
|
.join("tls/RootCA.pem")
|
|
|
|
.to_string(),
|
|
|
|
)
|
|
|
|
.unwrap()],
|
|
|
|
..Default::default()
|
|
|
|
},
|
|
|
|
)
|
|
|
|
.unwrap(),
|
|
|
|
);
|
2024-12-16 18:39:40 -05:00
|
|
|
let response = client.send(&url, Default::default()).await.unwrap();
|
|
|
|
assert!(response.status().is_success());
|
|
|
|
let (parts, body) = response.into_parts();
|
|
|
|
let headers = parts.headers;
|
|
|
|
let body = body.collect().await.unwrap().to_bytes().to_vec();
|
|
|
|
assert!(!body.is_empty());
|
|
|
|
assert_eq!(String::from_utf8(body).unwrap(), "console.log('etag')");
|
|
|
|
assert_eq!(
|
|
|
|
headers.get("content-type").unwrap(),
|
|
|
|
"application/typescript"
|
|
|
|
);
|
|
|
|
assert_eq!(headers.get("etag").unwrap(), "33a64df551425fcc55e");
|
|
|
|
assert_eq!(headers.get("x-typescript-types"), None);
|
2024-06-03 17:17:08 -04:00
|
|
|
|
2024-12-16 18:39:40 -05:00
|
|
|
let mut headers = HeaderMap::new();
|
|
|
|
headers.insert("If-None-Match", "33a64df551425fcc55e".parse().unwrap());
|
|
|
|
let res = client.send(&url, headers).await.unwrap();
|
|
|
|
assert_eq!(res.status(), StatusCode::NOT_MODIFIED);
|
2024-06-03 17:17:08 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
#[tokio::test]
|
|
|
|
async fn test_fetch_with_cafile_brotli() {
|
|
|
|
let _http_server_guard = test_util::http_server();
|
|
|
|
let url =
|
|
|
|
Url::parse("https://localhost:5545/run/import_compression/brotli")
|
|
|
|
.unwrap();
|
|
|
|
let client = HttpClient::new(
|
|
|
|
create_http_client(
|
2024-08-15 17:47:16 -04:00
|
|
|
version::DENO_VERSION_INFO.user_agent,
|
2024-06-03 17:17:08 -04:00
|
|
|
CreateHttpClientOptions {
|
|
|
|
ca_certs: vec![std::fs::read(
|
|
|
|
test_util::testdata_path()
|
|
|
|
.join("tls/RootCA.pem")
|
|
|
|
.to_string(),
|
|
|
|
)
|
|
|
|
.unwrap()],
|
|
|
|
..Default::default()
|
|
|
|
},
|
|
|
|
)
|
|
|
|
.unwrap(),
|
|
|
|
);
|
2024-12-16 18:39:40 -05:00
|
|
|
let response = client.send(&url, Default::default()).await.unwrap();
|
|
|
|
assert!(response.status().is_success());
|
|
|
|
let (parts, body) = response.into_parts();
|
|
|
|
let headers = parts.headers;
|
|
|
|
let body = body.collect().await.unwrap().to_bytes().to_vec();
|
|
|
|
assert!(!body.is_empty());
|
|
|
|
assert_eq!(String::from_utf8(body).unwrap(), "console.log('brotli');");
|
|
|
|
assert_eq!(
|
|
|
|
headers.get("content-type").unwrap(),
|
|
|
|
"application/javascript"
|
|
|
|
);
|
|
|
|
assert_eq!(headers.get("etag"), None);
|
|
|
|
assert_eq!(headers.get("x-typescript-types"), None);
|
2024-06-03 17:17:08 -04:00
|
|
|
}
|
2018-11-29 22:01:01 -05:00
|
|
|
}
|