1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
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)
	}
}


// private stuff


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))
}


// // Response
pub(crate) fn convert_fire_resp_to_hyper_resp(
	response: Response
) -> hyper::Response<BodyHttp> {

	// debug_checks
	#[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 failes if any argument failed
	// but no argument can fail that we pass here
	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)*);
		}
	)
}