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
use bytes::Bytes;
use http::{HeaderMap, HeaderValue, Response, StatusCode};
use http_body::{Body, Full, SizeHint};
use pin_project_lite::pin_project;
use std::pin::Pin;
use std::task::{Context, Poll};
pin_project! {
pub struct ResponseBody<B> {
#[pin]
inner: ResponseBodyInner<B>
}
}
impl<B> ResponseBody<B> {
fn payload_too_large() -> Self {
Self {
inner: ResponseBodyInner::PayloadTooLarge {
body: Full::from(BODY),
},
}
}
pub(crate) fn new(body: B) -> Self {
Self {
inner: ResponseBodyInner::Body { body },
}
}
}
pin_project! {
#[project = BodyProj]
enum ResponseBodyInner<B> {
PayloadTooLarge {
#[pin]
body: Full<Bytes>,
},
Body {
#[pin]
body: B
}
}
}
impl<B> Body for ResponseBody<B>
where
B: Body<Data = Bytes>,
{
type Data = Bytes;
type Error = B::Error;
fn poll_data(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Self::Data, Self::Error>>> {
match self.project().inner.project() {
BodyProj::PayloadTooLarge { body } => body.poll_data(cx).map_err(|err| match err {}),
BodyProj::Body { body } => body.poll_data(cx),
}
}
fn poll_trailers(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Result<Option<HeaderMap>, Self::Error>> {
match self.project().inner.project() {
BodyProj::PayloadTooLarge { body } => {
body.poll_trailers(cx).map_err(|err| match err {})
}
BodyProj::Body { body } => body.poll_trailers(cx),
}
}
fn is_end_stream(&self) -> bool {
match &self.inner {
ResponseBodyInner::PayloadTooLarge { body } => body.is_end_stream(),
ResponseBodyInner::Body { body } => body.is_end_stream(),
}
}
fn size_hint(&self) -> SizeHint {
match &self.inner {
ResponseBodyInner::PayloadTooLarge { body } => body.size_hint(),
ResponseBodyInner::Body { body } => body.size_hint(),
}
}
}
const BODY: &[u8] = b"length limit exceeded";
pub(crate) fn create_error_response<B>() -> Response<ResponseBody<B>>
where
B: Body,
{
let mut res = Response::new(ResponseBody::payload_too_large());
*res.status_mut() = StatusCode::PAYLOAD_TOO_LARGE;
#[allow(clippy::declare_interior_mutable_const)]
const TEXT_PLAIN: HeaderValue = HeaderValue::from_static("text/plain; charset=utf-8");
res.headers_mut()
.insert(http::header::CONTENT_TYPE, TEXT_PLAIN);
res
}