fire_http/util/
mod.rs

1use crate::fire::RequestConfigs;
2use crate::header::{ContentType, CONTENT_TYPE};
3use crate::server::HyperRequest;
4use crate::{Body, Request, Response};
5
6use std::future::Future;
7use std::net::SocketAddr;
8use std::pin::Pin;
9use std::task::Context;
10use std::task::Poll;
11
12use tracing::error;
13
14mod header;
15use header::convert_hyper_parts_to_fire_header;
16pub use header::convert_hyper_req_to_fire_header;
17pub(crate) use header::HeaderError;
18
19use types::body::BodyHttp;
20
21pub struct PinnedFuture<'a, O> {
22	inner: Pin<Box<dyn Future<Output = O> + Send + 'a>>,
23}
24
25impl<'a, O> PinnedFuture<'a, O> {
26	pub fn new<F>(future: F) -> Self
27	where
28		F: Future<Output = O> + Send + 'a,
29	{
30		Self {
31			inner: Box::pin(future),
32		}
33	}
34}
35
36impl<O> Future for PinnedFuture<'_, O> {
37	type Output = O;
38	fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
39		self.get_mut().inner.as_mut().poll(cx)
40	}
41}
42
43// private stuff
44
45pub(crate) fn convert_hyper_req_to_fire_req(
46	hyper_req: HyperRequest,
47	address: SocketAddr,
48	configs: &RequestConfigs,
49) -> Result<Request, HeaderError> {
50	let (parts, body) = hyper_req.into_parts();
51
52	let mut body = Body::from(body);
53	body.set_size_limit(Some(configs.size_limit));
54	body.set_timeout(Some(configs.timeout));
55
56	let header = convert_hyper_parts_to_fire_header(parts, address)?;
57
58	Ok(Request::new(header, body))
59}
60
61// // Response
62pub(crate) fn convert_fire_resp_to_hyper_resp(
63	response: Response,
64) -> hyper::Response<BodyHttp> {
65	// debug_checks
66	#[cfg(debug_assertions)]
67	let _ = validate_content_length(&response);
68
69	let mut header = response.header;
70
71	if !matches!(header.content_type, ContentType::None) {
72		let e = header.values.try_insert(CONTENT_TYPE, header.content_type);
73		if let Err(e) = e {
74			error!("could not insert content type: {e}");
75		}
76	}
77
78	let mut builder = hyper::Response::builder().status(header.status_code);
79
80	*builder.headers_mut().unwrap() = header.values.into_inner();
81
82	// builder failes if any argument failed
83	// but no argument can fail that we pass here
84	builder.body(response.body.into_http_body()).unwrap()
85}
86
87#[cfg(debug_assertions)]
88fn validate_content_length(response: &Response) -> Option<()> {
89	let len = response.header().value(crate::header::CONTENT_LENGTH)?;
90
91	let len: usize = len.parse().expect("content-length not a number");
92
93	let body_len = response.body.len()?;
94
95	assert_eq!(len, body_len);
96
97	Some(())
98}