2020-07-29 08:56:18 +00:00
|
|
|
// Copyright 2020 The Matrix.org Foundation C.I.C.
|
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
// you may not use this file except in compliance with the License.
|
|
|
|
// You may obtain a copy of the License at
|
|
|
|
//
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
//
|
|
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
// See the License for the specific language governing permissions and
|
|
|
|
// limitations under the License.
|
|
|
|
|
2020-08-11 15:25:33 +00:00
|
|
|
use std::{convert::TryFrom, fmt::Debug, sync::Arc};
|
2020-07-29 08:56:18 +00:00
|
|
|
|
2021-04-01 17:25:31 +00:00
|
|
|
#[cfg(all(not(target_arch = "wasm32")))]
|
2021-02-01 16:58:03 +00:00
|
|
|
use backoff::{future::retry, Error as RetryError, ExponentialBackoff};
|
2021-04-01 17:25:31 +00:00
|
|
|
#[cfg(all(not(target_arch = "wasm32")))]
|
2021-01-31 20:10:30 +00:00
|
|
|
use http::StatusCode;
|
2021-03-01 18:29:04 +00:00
|
|
|
use http::{HeaderValue, Response as HttpResponse};
|
2020-07-31 18:35:27 +00:00
|
|
|
use reqwest::{Client, Response};
|
2021-04-01 17:25:31 +00:00
|
|
|
#[cfg(all(not(target_arch = "wasm32")))]
|
|
|
|
use std::sync::atomic::{AtomicU64, Ordering};
|
2020-07-29 08:56:18 +00:00
|
|
|
use tracing::trace;
|
|
|
|
use url::Url;
|
|
|
|
|
2020-09-29 15:23:14 +00:00
|
|
|
use matrix_sdk_common::{
|
2021-04-01 17:25:31 +00:00
|
|
|
api::r0::media::create_content, async_trait, locks::RwLock, AsyncTraitDeps, AuthScheme,
|
2021-04-26 06:05:58 +00:00
|
|
|
FromHttpResponseError, IncomingResponse, SendAccessToken,
|
2020-09-29 15:23:14 +00:00
|
|
|
};
|
2020-08-11 15:25:33 +00:00
|
|
|
|
2021-04-26 12:21:45 +00:00
|
|
|
use crate::{
|
|
|
|
error::HttpError, Bytes, BytesMut, ClientConfig, OutgoingRequest, RequestConfig, Session,
|
|
|
|
};
|
2021-02-01 16:15:29 +00:00
|
|
|
|
2020-08-11 15:25:33 +00:00
|
|
|
/// Abstraction around the http layer. The allows implementors to use different
|
|
|
|
/// http libraries.
|
2021-01-22 17:12:46 +00:00
|
|
|
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
|
|
|
|
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
|
|
|
|
pub trait HttpSend: AsyncTraitDeps {
|
2020-08-11 15:25:33 +00:00
|
|
|
/// The method abstracting sending request types and receiving response types.
|
|
|
|
///
|
|
|
|
/// This is called by the client every time it wants to send anything to a homeserver.
|
|
|
|
///
|
|
|
|
/// # Arguments
|
|
|
|
///
|
|
|
|
/// * `request` - The http request that has been converted from a ruma `Request`.
|
|
|
|
///
|
2021-04-01 17:25:31 +00:00
|
|
|
/// * `request_config` - The config used for this request.
|
|
|
|
///
|
2020-08-11 15:25:33 +00:00
|
|
|
/// # Examples
|
|
|
|
///
|
2020-08-26 11:41:15 +00:00
|
|
|
/// ```
|
|
|
|
/// use std::convert::TryFrom;
|
2021-04-19 10:26:10 +00:00
|
|
|
/// use matrix_sdk::{HttpSend, async_trait, HttpError, RequestConfig, Bytes};
|
2020-08-11 15:25:33 +00:00
|
|
|
///
|
|
|
|
/// #[derive(Debug)]
|
2020-08-26 11:41:15 +00:00
|
|
|
/// struct Client(reqwest::Client);
|
2020-08-11 15:25:33 +00:00
|
|
|
///
|
2020-08-26 11:41:15 +00:00
|
|
|
/// impl Client {
|
|
|
|
/// async fn response_to_http_response(
|
|
|
|
/// &self,
|
|
|
|
/// mut response: reqwest::Response,
|
2021-04-19 10:26:10 +00:00
|
|
|
/// ) -> Result<http::Response<Bytes>, HttpError> {
|
2020-08-26 11:41:15 +00:00
|
|
|
/// // Convert the reqwest response to a http one.
|
|
|
|
/// todo!()
|
|
|
|
/// }
|
2020-08-11 15:25:33 +00:00
|
|
|
/// }
|
|
|
|
///
|
2020-08-26 11:41:15 +00:00
|
|
|
/// #[async_trait]
|
|
|
|
/// impl HttpSend for Client {
|
2021-02-01 18:24:29 +00:00
|
|
|
/// async fn send_request(
|
|
|
|
/// &self,
|
2021-04-26 12:21:45 +00:00
|
|
|
/// request: http::Request<Bytes>,
|
2021-04-01 17:25:31 +00:00
|
|
|
/// config: RequestConfig,
|
2021-04-19 10:26:10 +00:00
|
|
|
/// ) -> Result<http::Response<Bytes>, HttpError> {
|
2020-08-26 11:41:15 +00:00
|
|
|
/// Ok(self
|
|
|
|
/// .response_to_http_response(
|
|
|
|
/// self.0
|
|
|
|
/// .execute(reqwest::Request::try_from(request)?)
|
|
|
|
/// .await?,
|
|
|
|
/// )
|
|
|
|
/// .await?)
|
|
|
|
/// }
|
|
|
|
/// }
|
2020-08-11 15:25:33 +00:00
|
|
|
/// ```
|
2020-08-26 11:41:15 +00:00
|
|
|
async fn send_request(
|
|
|
|
&self,
|
2021-04-26 12:21:45 +00:00
|
|
|
request: http::Request<Bytes>,
|
2021-04-01 17:25:31 +00:00
|
|
|
config: RequestConfig,
|
2021-04-19 10:26:10 +00:00
|
|
|
) -> Result<http::Response<Bytes>, HttpError>;
|
2020-08-11 15:25:33 +00:00
|
|
|
}
|
2020-07-29 08:56:18 +00:00
|
|
|
|
|
|
|
#[derive(Clone, Debug)]
|
|
|
|
pub(crate) struct HttpClient {
|
2020-08-11 12:07:45 +00:00
|
|
|
pub(crate) inner: Arc<dyn HttpSend>,
|
2020-07-29 08:56:18 +00:00
|
|
|
pub(crate) homeserver: Arc<Url>,
|
2020-08-17 13:29:07 +00:00
|
|
|
pub(crate) session: Arc<RwLock<Option<Session>>>,
|
2021-04-01 17:25:31 +00:00
|
|
|
pub(crate) request_config: RequestConfig,
|
2020-07-29 08:56:18 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl HttpClient {
|
2020-08-15 01:09:13 +00:00
|
|
|
async fn send_request<Request: OutgoingRequest>(
|
2020-07-29 08:56:18 +00:00
|
|
|
&self,
|
2020-07-31 18:35:27 +00:00
|
|
|
request: Request,
|
2020-07-29 11:50:01 +00:00
|
|
|
session: Arc<RwLock<Option<Session>>>,
|
2021-04-01 17:25:31 +00:00
|
|
|
config: Option<RequestConfig>,
|
2021-04-19 10:26:10 +00:00
|
|
|
) -> Result<http::Response<Bytes>, HttpError> {
|
2021-04-26 15:31:25 +00:00
|
|
|
let config = match config {
|
|
|
|
Some(config) => config,
|
|
|
|
None => self.request_config,
|
|
|
|
};
|
|
|
|
|
2021-03-01 18:29:04 +00:00
|
|
|
let request = {
|
2020-07-31 18:35:27 +00:00
|
|
|
let read_guard;
|
2021-04-26 15:31:25 +00:00
|
|
|
let access_token = if config.force_auth {
|
|
|
|
read_guard = session.read().await;
|
|
|
|
if let Some(session) = read_guard.as_ref() {
|
|
|
|
SendAccessToken::Always(session.access_token.as_str())
|
|
|
|
} else {
|
|
|
|
return Err(HttpError::ForcedAuthenticationWithoutAccessToken);
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
match Request::METADATA.authentication {
|
|
|
|
AuthScheme::AccessToken => {
|
|
|
|
read_guard = session.read().await;
|
2020-07-31 18:35:27 +00:00
|
|
|
|
2021-04-26 15:31:25 +00:00
|
|
|
if let Some(session) = read_guard.as_ref() {
|
2021-04-26 06:05:58 +00:00
|
|
|
SendAccessToken::IfRequired(session.access_token.as_str())
|
2021-04-26 15:31:25 +00:00
|
|
|
} else {
|
|
|
|
return Err(HttpError::AuthenticationRequired);
|
|
|
|
}
|
2020-09-29 15:23:14 +00:00
|
|
|
}
|
2021-04-26 06:05:58 +00:00
|
|
|
AuthScheme::None => SendAccessToken::None,
|
2021-04-26 15:31:25 +00:00
|
|
|
_ => return Err(HttpError::NotClientRequest),
|
|
|
|
}
|
2020-07-31 18:35:27 +00:00
|
|
|
};
|
|
|
|
|
2021-04-26 12:21:45 +00:00
|
|
|
request
|
|
|
|
.try_into_http_request::<BytesMut>(&self.homeserver.to_string(), access_token)?
|
|
|
|
.map(|body| body.freeze())
|
2020-07-31 18:35:27 +00:00
|
|
|
};
|
2020-07-29 08:56:18 +00:00
|
|
|
|
2021-04-01 17:25:31 +00:00
|
|
|
self.inner.send_request(request, config).await
|
2020-07-29 08:56:18 +00:00
|
|
|
}
|
|
|
|
|
2020-09-15 15:16:16 +00:00
|
|
|
pub async fn upload(
|
|
|
|
&self,
|
|
|
|
request: create_content::Request<'_>,
|
2021-04-01 17:25:31 +00:00
|
|
|
config: Option<RequestConfig>,
|
2021-01-31 17:09:03 +00:00
|
|
|
) -> Result<create_content::Response, HttpError> {
|
2020-09-15 15:16:16 +00:00
|
|
|
let response = self
|
2021-04-01 17:25:31 +00:00
|
|
|
.send_request(request, self.session.clone(), config)
|
2020-09-15 15:16:16 +00:00
|
|
|
.await?;
|
2021-04-16 10:45:21 +00:00
|
|
|
Ok(create_content::Response::try_from_http_response(response)?)
|
2020-09-15 15:16:16 +00:00
|
|
|
}
|
|
|
|
|
2021-01-31 17:09:03 +00:00
|
|
|
pub async fn send<Request>(
|
|
|
|
&self,
|
|
|
|
request: Request,
|
2021-04-01 17:25:31 +00:00
|
|
|
config: Option<RequestConfig>,
|
2021-01-31 17:09:03 +00:00
|
|
|
) -> Result<Request::IncomingResponse, HttpError>
|
2020-07-31 18:35:27 +00:00
|
|
|
where
|
2021-01-31 17:09:03 +00:00
|
|
|
Request: OutgoingRequest + Debug,
|
|
|
|
HttpError: From<FromHttpResponseError<Request::EndpointError>>,
|
2020-07-31 18:35:27 +00:00
|
|
|
{
|
2020-09-15 15:16:16 +00:00
|
|
|
let response = self
|
2021-04-01 17:25:31 +00:00
|
|
|
.send_request(request, self.session.clone(), config)
|
2020-09-15 15:16:16 +00:00
|
|
|
.await?;
|
2020-07-29 08:56:18 +00:00
|
|
|
|
|
|
|
trace!("Got response: {:?}", response);
|
|
|
|
|
2021-04-16 10:45:21 +00:00
|
|
|
let response = Request::IncomingResponse::try_from_http_response(response)?;
|
2021-01-31 17:09:03 +00:00
|
|
|
|
|
|
|
Ok(response)
|
2020-07-29 08:56:18 +00:00
|
|
|
}
|
|
|
|
}
|
2020-08-11 12:07:45 +00:00
|
|
|
|
2020-08-26 12:37:48 +00:00
|
|
|
/// Build a client with the specified configuration.
|
2021-01-31 17:09:03 +00:00
|
|
|
pub(crate) fn client_with_config(config: &ClientConfig) -> Result<Client, HttpError> {
|
2020-08-26 12:37:48 +00:00
|
|
|
let http_client = reqwest::Client::builder();
|
|
|
|
|
|
|
|
#[cfg(not(target_arch = "wasm32"))]
|
|
|
|
let http_client = {
|
|
|
|
let http_client = if config.disable_ssl_verification {
|
|
|
|
http_client.danger_accept_invalid_certs(true)
|
|
|
|
} else {
|
|
|
|
http_client
|
|
|
|
};
|
2020-08-11 12:07:45 +00:00
|
|
|
|
2020-08-26 12:37:48 +00:00
|
|
|
let http_client = match &config.proxy {
|
|
|
|
Some(p) => http_client.proxy(p.clone()),
|
|
|
|
None => http_client,
|
|
|
|
};
|
2020-08-11 12:07:45 +00:00
|
|
|
|
2020-08-26 12:37:48 +00:00
|
|
|
let mut headers = reqwest::header::HeaderMap::new();
|
2020-08-11 12:07:45 +00:00
|
|
|
|
2020-08-26 12:37:48 +00:00
|
|
|
let user_agent = match &config.user_agent {
|
|
|
|
Some(a) => a.clone(),
|
2021-01-31 20:12:00 +00:00
|
|
|
None => HeaderValue::from_str(&format!("matrix-rust-sdk {}", crate::VERSION))
|
|
|
|
.expect("Can't construct the version header"),
|
2020-08-26 12:37:48 +00:00
|
|
|
};
|
2020-08-11 12:07:45 +00:00
|
|
|
|
2020-08-26 12:37:48 +00:00
|
|
|
headers.insert(reqwest::header::USER_AGENT, user_agent);
|
2020-08-11 12:07:45 +00:00
|
|
|
|
2021-02-01 16:15:29 +00:00
|
|
|
http_client
|
|
|
|
.default_headers(headers)
|
2021-04-01 17:25:31 +00:00
|
|
|
.timeout(config.request_config.timeout)
|
2020-08-26 12:37:48 +00:00
|
|
|
};
|
2020-08-11 12:07:45 +00:00
|
|
|
|
2020-08-26 12:37:48 +00:00
|
|
|
#[cfg(target_arch = "wasm32")]
|
|
|
|
#[allow(unused)]
|
|
|
|
let _ = config;
|
2020-08-11 13:17:18 +00:00
|
|
|
|
2020-08-26 12:37:48 +00:00
|
|
|
Ok(http_client.build()?)
|
|
|
|
}
|
2020-08-26 11:41:15 +00:00
|
|
|
|
2021-01-31 17:09:03 +00:00
|
|
|
async fn response_to_http_response(
|
|
|
|
mut response: Response,
|
2021-04-19 10:26:10 +00:00
|
|
|
) -> Result<http::Response<Bytes>, reqwest::Error> {
|
2020-08-26 12:37:48 +00:00
|
|
|
let status = response.status();
|
2020-08-26 11:41:15 +00:00
|
|
|
|
2020-08-26 12:37:48 +00:00
|
|
|
let mut http_builder = HttpResponse::builder().status(status);
|
2021-01-31 20:12:00 +00:00
|
|
|
let headers = http_builder
|
|
|
|
.headers_mut()
|
|
|
|
.expect("Can't get the response builder headers");
|
2020-08-26 11:41:15 +00:00
|
|
|
|
2020-08-26 12:37:48 +00:00
|
|
|
for (k, v) in response.headers_mut().drain() {
|
|
|
|
if let Some(key) = k {
|
|
|
|
headers.insert(key, v);
|
2020-08-26 11:41:15 +00:00
|
|
|
}
|
2020-08-26 12:37:48 +00:00
|
|
|
}
|
2020-08-26 11:41:15 +00:00
|
|
|
|
2021-04-19 10:26:10 +00:00
|
|
|
let body = response.bytes().await?;
|
2020-08-26 11:41:15 +00:00
|
|
|
|
2021-01-31 20:12:00 +00:00
|
|
|
Ok(http_builder
|
|
|
|
.body(body)
|
|
|
|
.expect("Can't construct a response using the given body"))
|
2020-08-11 12:07:45 +00:00
|
|
|
}
|
|
|
|
|
2021-04-01 17:25:31 +00:00
|
|
|
#[cfg(any(target_arch = "wasm32"))]
|
2021-01-31 20:10:30 +00:00
|
|
|
async fn send_request(
|
|
|
|
client: &Client,
|
2021-04-26 12:21:45 +00:00
|
|
|
request: http::Request<Bytes>,
|
2021-04-01 17:25:31 +00:00
|
|
|
_: RequestConfig,
|
2021-04-19 10:26:10 +00:00
|
|
|
) -> Result<http::Response<Bytes>, HttpError> {
|
2021-01-31 20:10:30 +00:00
|
|
|
let request = reqwest::Request::try_from(request)?;
|
|
|
|
let response = client.execute(request).await?;
|
|
|
|
|
|
|
|
Ok(response_to_http_response(response).await?)
|
|
|
|
}
|
|
|
|
|
2021-04-01 17:25:31 +00:00
|
|
|
#[cfg(all(not(target_arch = "wasm32")))]
|
2021-01-31 20:10:30 +00:00
|
|
|
async fn send_request(
|
|
|
|
client: &Client,
|
2021-04-26 12:21:45 +00:00
|
|
|
request: http::Request<Bytes>,
|
2021-04-01 17:25:31 +00:00
|
|
|
config: RequestConfig,
|
2021-04-19 10:26:10 +00:00
|
|
|
) -> Result<http::Response<Bytes>, HttpError> {
|
2021-04-01 17:25:31 +00:00
|
|
|
let mut backoff = ExponentialBackoff::default();
|
2021-02-01 16:15:29 +00:00
|
|
|
let mut request = reqwest::Request::try_from(request)?;
|
2021-04-01 17:25:31 +00:00
|
|
|
let retry_limit = config.retry_limit;
|
|
|
|
let retry_count = AtomicU64::new(1);
|
2021-02-01 16:15:29 +00:00
|
|
|
|
2021-04-01 17:25:31 +00:00
|
|
|
*request.timeout_mut() = Some(config.timeout);
|
|
|
|
|
|
|
|
backoff.max_elapsed_time = config.retry_timeout;
|
2021-02-01 16:15:29 +00:00
|
|
|
|
|
|
|
let request = &request;
|
2021-04-01 17:25:31 +00:00
|
|
|
let retry_count = &retry_count;
|
2021-01-31 20:10:30 +00:00
|
|
|
|
|
|
|
let request = || async move {
|
2021-04-01 17:25:31 +00:00
|
|
|
let stop = if let Some(retry_limit) = retry_limit {
|
|
|
|
retry_count.fetch_add(1, Ordering::Relaxed) >= retry_limit
|
|
|
|
} else {
|
|
|
|
false
|
|
|
|
};
|
|
|
|
|
|
|
|
// Turn errors into permanent errors when the retry limit is reached
|
|
|
|
let error_type = if stop {
|
|
|
|
RetryError::Permanent
|
|
|
|
} else {
|
|
|
|
RetryError::Transient
|
|
|
|
};
|
|
|
|
|
2021-01-31 20:10:30 +00:00
|
|
|
let request = request.try_clone().ok_or(HttpError::UnableToCloneRequest)?;
|
|
|
|
|
|
|
|
let response = client
|
|
|
|
.execute(request)
|
|
|
|
.await
|
2021-04-01 17:25:31 +00:00
|
|
|
.map_err(|e| error_type(HttpError::Reqwest(e)))?;
|
2021-01-31 20:10:30 +00:00
|
|
|
|
|
|
|
let status_code = response.status();
|
|
|
|
// TODO TOO_MANY_REQUESTS will have a retry timeout which we should
|
|
|
|
// use.
|
2021-04-01 17:25:31 +00:00
|
|
|
if !stop
|
|
|
|
&& (status_code.is_server_error() || response.status() == StatusCode::TOO_MANY_REQUESTS)
|
|
|
|
{
|
|
|
|
return Err(error_type(HttpError::Server(status_code)));
|
2021-01-31 20:10:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
let response = response_to_http_response(response)
|
|
|
|
.await
|
|
|
|
.map_err(|e| RetryError::Permanent(HttpError::Reqwest(e)))?;
|
|
|
|
|
|
|
|
Ok(response)
|
|
|
|
};
|
|
|
|
|
|
|
|
let response = retry(backoff, request).await?;
|
|
|
|
|
|
|
|
Ok(response)
|
|
|
|
}
|
|
|
|
|
2021-01-22 17:12:46 +00:00
|
|
|
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
|
|
|
|
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
|
2020-08-26 12:37:48 +00:00
|
|
|
impl HttpSend for Client {
|
2020-08-26 11:41:15 +00:00
|
|
|
async fn send_request(
|
|
|
|
&self,
|
2021-04-26 12:21:45 +00:00
|
|
|
request: http::Request<Bytes>,
|
2021-04-01 17:25:31 +00:00
|
|
|
config: RequestConfig,
|
2021-04-19 10:26:10 +00:00
|
|
|
) -> Result<http::Response<Bytes>, HttpError> {
|
2021-04-01 17:25:31 +00:00
|
|
|
send_request(&self, request, config).await
|
2020-08-11 12:07:45 +00:00
|
|
|
}
|
|
|
|
}
|