AppFlowy/rust-lib/flowy-net/src/request/request.rs

210 lines
5.9 KiB
Rust
Raw Normal View History

2021-09-09 09:34:01 +00:00
use crate::{config::HEADER_TOKEN, errors::ServerError, response::FlowyResponse};
2021-08-20 13:09:21 +00:00
use bytes::Bytes;
2021-09-09 09:34:01 +00:00
use hyper::http;
2021-08-23 00:27:29 +00:00
use protobuf::ProtobufError;
2021-09-09 09:34:01 +00:00
use reqwest::{header::HeaderMap, Client, Method, Response};
use std::{
convert::{TryFrom, TryInto},
sync::Arc,
time::Duration,
};
use tokio::sync::oneshot;
2021-08-20 13:09:21 +00:00
pub trait ResponseMiddleware {
2021-09-08 10:25:32 +00:00
fn receive_response(&self, token: &Option<String>, response: &FlowyResponse);
}
2021-08-23 00:27:29 +00:00
pub struct HttpRequestBuilder {
url: String,
body: Option<Bytes>,
2021-09-01 08:08:32 +00:00
response: Option<Bytes>,
headers: HeaderMap,
2021-08-23 00:27:29 +00:00
method: Method,
middleware: Vec<Arc<dyn ResponseMiddleware + Send + Sync>>,
2021-08-23 00:27:29 +00:00
}
impl HttpRequestBuilder {
pub fn new() -> Self {
2021-08-23 00:27:29 +00:00
Self {
url: "".to_owned(),
2021-08-23 00:27:29 +00:00
body: None,
response: None,
2021-09-01 08:08:32 +00:00
headers: HeaderMap::new(),
2021-08-23 00:27:29 +00:00
method: Method::GET,
middleware: Vec::new(),
2021-08-23 00:27:29 +00:00
}
}
pub fn middleware<T>(mut self, middleware: Arc<T>) -> Self
where
T: 'static + ResponseMiddleware + Send + Sync,
{
self.middleware.push(middleware);
self
}
pub fn get(mut self, url: &str) -> Self {
self.url = url.to_owned();
self.method = Method::GET;
self
2021-08-23 00:27:29 +00:00
}
pub fn post(mut self, url: &str) -> Self {
self.url = url.to_owned();
self.method = Method::POST;
self
2021-08-23 00:27:29 +00:00
}
pub fn patch(mut self, url: &str) -> Self {
self.url = url.to_owned();
self.method = Method::PATCH;
self
2021-08-25 09:34:20 +00:00
}
pub fn delete(mut self, url: &str) -> Self {
self.url = url.to_owned();
self.method = Method::DELETE;
self
2021-08-25 09:34:20 +00:00
}
2021-09-01 08:08:32 +00:00
pub fn header(mut self, key: &'static str, value: &str) -> Self {
self.headers.insert(key, value.parse().unwrap());
self
}
pub fn protobuf<T>(self, body: T) -> Result<Self, ServerError>
2021-08-23 00:27:29 +00:00
where
T: TryInto<Bytes, Error = ProtobufError>,
2021-08-23 00:27:29 +00:00
{
let body: Bytes = body.try_into()?;
2021-08-26 09:58:59 +00:00
self.bytes(body)
}
pub fn bytes(mut self, body: Bytes) -> Result<Self, ServerError> {
2021-08-23 00:27:29 +00:00
self.body = Some(body);
Ok(self)
}
2021-09-09 09:34:01 +00:00
pub async fn send(self) -> Result<(), ServerError> {
let _ = self.inner_send().await?;
Ok(())
}
pub async fn response<T>(self) -> Result<T, ServerError>
where
T: TryFrom<Bytes, Error = ProtobufError>,
{
let builder = self.inner_send().await?;
match builder.response {
None => Err(unexpected_empty_payload(&builder.url)),
Some(data) => Ok(T::try_from(data)?),
}
}
pub async fn option_response<T>(self) -> Result<Option<T>, ServerError>
where
T: TryFrom<Bytes, Error = ProtobufError>,
{
let result = self.inner_send().await;
match result {
Ok(builder) => match builder.response {
None => Err(unexpected_empty_payload(&builder.url)),
Some(data) => Ok(Some(T::try_from(data)?)),
},
Err(error) => match error.is_record_not_found() {
true => Ok(None),
false => Err(error),
},
}
}
fn token(&self) -> Option<String> {
match self.headers.get(HEADER_TOKEN) {
None => None,
Some(header) => match header.to_str() {
Ok(val) => Some(val.to_owned()),
Err(_) => None,
},
}
}
async fn inner_send(mut self) -> Result<Self, ServerError> {
2021-08-23 00:27:29 +00:00
let (tx, rx) = oneshot::channel::<Result<Response, _>>();
let url = self.url.clone();
let body = self.body.take();
let method = self.method.clone();
2021-09-01 08:08:32 +00:00
let headers = self.headers.clone();
2021-08-23 00:27:29 +00:00
2021-08-23 10:39:10 +00:00
// reqwest client is not 'Sync' by channel is.
2021-08-23 00:27:29 +00:00
tokio::spawn(async move {
let client = default_client();
2021-09-04 07:12:53 +00:00
let mut builder = client.request(method.clone(), url).headers(headers);
2021-08-23 00:27:29 +00:00
if let Some(body) = body {
builder = builder.body(body);
}
let response = builder.send().await;
match tx.send(response) {
Ok(_) => {},
Err(e) => {
2021-09-04 07:12:53 +00:00
log::error!("[{}] Send http request failed: {:?}", method, e);
},
}
2021-08-23 00:27:29 +00:00
});
let response = rx.await??;
let flowy_response = flowy_response_from(response).await?;
2021-09-08 10:25:32 +00:00
let token = self.token();
self.middleware.iter().for_each(|middleware| {
2021-09-08 10:25:32 +00:00
middleware.receive_response(&token, &flowy_response);
});
match flowy_response.error {
None => {
self.response = Some(flowy_response.data);
2021-09-01 08:08:32 +00:00
Ok(self)
},
Some(error) => Err(error),
2021-09-01 08:08:32 +00:00
}
2021-08-23 00:27:29 +00:00
}
2021-09-09 09:34:01 +00:00
}
2021-08-23 00:27:29 +00:00
2021-09-09 09:34:01 +00:00
fn unexpected_empty_payload(url: &str) -> ServerError {
let msg = format!("Request: {} receives unexpected empty payload", url);
ServerError::payload_none().context(msg)
2021-08-23 00:27:29 +00:00
}
async fn flowy_response_from(original: Response) -> Result<FlowyResponse, ServerError> {
let bytes = original.bytes().await?;
let response: FlowyResponse = serde_json::from_slice(&bytes)?;
Ok(response)
}
#[allow(dead_code)]
2021-08-22 14:16:03 +00:00
async fn get_response_data(original: Response) -> Result<Bytes, ServerError> {
if original.status() == http::StatusCode::OK {
let bytes = original.bytes().await?;
let response: FlowyResponse = serde_json::from_slice(&bytes)?;
match response.error {
None => Ok(response.data),
Some(error) => Err(error),
}
} else {
2021-08-23 15:02:42 +00:00
Err(ServerError::http().context(original))
2021-08-20 13:09:21 +00:00
}
}
fn default_client() -> Client {
let result = reqwest::Client::builder()
.connect_timeout(Duration::from_millis(500))
.timeout(Duration::from_secs(5))
.build();
match result {
Ok(client) => client,
Err(e) => {
log::error!("Create reqwest client failed: {}", e);
reqwest::Client::new()
},
}
}