use crate::{Request, Response, Body};
use crate::server::HyperRequest;
use crate::fire::RequestConfigs;
use crate::header::{ContentType, CONTENT_TYPE};
use std::task::Poll;
use std::pin::Pin;
use std::future::Future;
use std::task::Context;
use std::net::SocketAddr;
use tracing::error;
mod header;
use header::{convert_hyper_parts_to_fire_header};
pub(crate) use header::HeaderError;
use types::body::BodyHttp;
pub struct PinnedFuture<'a, O> {
inner: Pin<Box<dyn Future<Output = O> + Send + 'a>>
}
impl<'a, O> PinnedFuture<'a, O> {
pub fn new<F>(future: F) -> Self
where F: Future<Output = O> + Send + 'a {
Self {
inner: Box::pin(future)
}
}
}
impl<O> Future for PinnedFuture<'_, O> {
type Output = O;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
self.get_mut().inner.as_mut().poll(cx)
}
}
pub(crate) fn convert_hyper_req_to_fire_req(
hyper_req: HyperRequest,
address: SocketAddr,
configs: &RequestConfigs
) -> Result<Request, HeaderError> {
let (parts, body) = hyper_req.into_parts();
let mut body = Body::from_hyper(body);
body.set_size_limit(Some(configs.size_limit));
body.set_timeout(Some(configs.timeout));
let header = convert_hyper_parts_to_fire_header(parts, address)?;
Ok(Request::new(header, body))
}
pub(crate) fn convert_fire_resp_to_hyper_resp(
response: Response
) -> hyper::Response<BodyHttp> {
#[cfg(debug_assertions)]
let _ = validate_content_length(&response);
let mut header = response.header;
if !matches!(header.content_type, ContentType::None) {
let e = header.values.try_insert(CONTENT_TYPE, header.content_type);
if let Err(e) = e {
error!("could not insert content type {:?}", e);
}
}
let mut builder = hyper::Response::builder()
.status(header.status_code);
*builder.headers_mut().unwrap() = header.values.into_inner();
builder.body(response.body.into_http_body()).unwrap()
}
#[cfg(debug_assertions)]
fn validate_content_length(response: &Response) -> Option<()> {
let len = response.header().value(crate::header::CONTENT_LENGTH)?;
let len: usize = len.parse().expect("content-length not a number");
let body_len = response.body.len()?;
assert_eq!(len, body_len);
Some(())
}
macro_rules! trace {
($($tt:tt)*) => (
#[cfg(feature = "trace")]
{
tracing::trace!($($tt)*);
}
)
}