matrix-sdk: Implement the HttpSend trait directly on the reqwest client.

master
Damir Jelić 2020-08-26 14:37:48 +02:00
parent deff66ac42
commit 7a418ae09e
2 changed files with 54 additions and 72 deletions

View File

@ -81,7 +81,7 @@ use matrix_sdk_common::{
use crate::{ use crate::{
events::{room::message::MessageEventContent, AnyMessageEventContent}, events::{room::message::MessageEventContent, AnyMessageEventContent},
http_client::{DefaultHttpClient, HttpClient, HttpSend}, http_client::{client_with_config, HttpClient, HttpSend},
identifiers::{EventId, RoomId, RoomIdOrAliasId, UserId}, identifiers::{EventId, RoomId, RoomIdOrAliasId, UserId},
Error, EventEmitter, OutgoingRequest, Result, Error, EventEmitter, OutgoingRequest, Result,
}; };
@ -353,7 +353,7 @@ impl Client {
let client = if let Some(client) = config.client { let client = if let Some(client) = config.client {
client client
} else { } else {
Arc::new(DefaultHttpClient::with_config(&config)?) Arc::new(client_with_config(&config)?)
}; };
let base_client = BaseClient::new_with_config(config.base_config)?; let base_client = BaseClient::new_with_config(config.base_config)?;

View File

@ -128,91 +128,73 @@ impl HttpClient {
} }
} }
/// Default http client used if none is specified using `Client::with_client`. /// Build a client with the specified configuration.
#[derive(Clone, Debug)] pub(crate) fn client_with_config(config: &ClientConfig) -> Result<Client> {
pub struct DefaultHttpClient { let http_client = reqwest::Client::builder();
inner: Client,
}
impl DefaultHttpClient { #[cfg(not(target_arch = "wasm32"))]
/// Build a client with the specified configuration. let http_client = {
pub fn with_config(config: &ClientConfig) -> Result<Self> { let http_client = match config.timeout {
let http_client = reqwest::Client::builder(); Some(x) => http_client.timeout(x),
None => http_client,
#[cfg(not(target_arch = "wasm32"))]
let http_client = {
let http_client = match config.timeout {
Some(x) => http_client.timeout(x),
None => http_client,
};
let http_client = if config.disable_ssl_verification {
http_client.danger_accept_invalid_certs(true)
} else {
http_client
};
let http_client = match &config.proxy {
Some(p) => http_client.proxy(p.clone()),
None => http_client,
};
let mut headers = reqwest::header::HeaderMap::new();
let user_agent = match &config.user_agent {
Some(a) => a.clone(),
None => {
HeaderValue::from_str(&format!("matrix-rust-sdk {}", crate::VERSION)).unwrap()
}
};
headers.insert(reqwest::header::USER_AGENT, user_agent);
http_client.default_headers(headers)
}; };
#[cfg(target_arch = "wasm32")] let http_client = if config.disable_ssl_verification {
#[allow(unused)] http_client.danger_accept_invalid_certs(true)
let _ = config; } else {
http_client
};
Ok(Self { let http_client = match &config.proxy {
inner: http_client.build()?, Some(p) => http_client.proxy(p.clone()),
}) None => http_client,
} };
async fn response_to_http_response( let mut headers = reqwest::header::HeaderMap::new();
&self,
mut response: Response,
) -> Result<http::Response<Vec<u8>>> {
let status = response.status();
let mut http_builder = HttpResponse::builder().status(status); let user_agent = match &config.user_agent {
let headers = http_builder.headers_mut().unwrap(); Some(a) => a.clone(),
None => HeaderValue::from_str(&format!("matrix-rust-sdk {}", crate::VERSION)).unwrap(),
};
for (k, v) in response.headers_mut().drain() { headers.insert(reqwest::header::USER_AGENT, user_agent);
if let Some(key) = k {
headers.insert(key, v); http_client.default_headers(headers)
} };
#[cfg(target_arch = "wasm32")]
#[allow(unused)]
let _ = config;
Ok(http_client.build()?)
}
async fn response_to_http_response(mut response: Response) -> Result<http::Response<Vec<u8>>> {
let status = response.status();
let mut http_builder = HttpResponse::builder().status(status);
let headers = http_builder.headers_mut().unwrap();
for (k, v) in response.headers_mut().drain() {
if let Some(key) = k {
headers.insert(key, v);
} }
let body = response.bytes().await?.as_ref().to_owned();
Ok(http_builder.body(body).unwrap())
} }
let body = response.bytes().await?.as_ref().to_owned();
Ok(http_builder.body(body).unwrap())
} }
#[async_trait] #[async_trait]
impl HttpSend for DefaultHttpClient { impl HttpSend for Client {
async fn send_request( async fn send_request(
&self, &self,
request: http::Request<Vec<u8>>, request: http::Request<Vec<u8>>,
) -> Result<http::Response<Vec<u8>>> { ) -> Result<http::Response<Vec<u8>>> {
Ok(self Ok(
.response_to_http_response( response_to_http_response(self.execute(reqwest::Request::try_from(request)?).await?)
self.inner .await?,
.execute(reqwest::Request::try_from(request)?) )
.await?,
)
.await?)
} }
} }