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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
use crate::ws::HttpOrWsIncoming;
use async_http_codec::internal::buffer_decode::BufferDecode;
use async_http_codec::{BodyDecodeWithContinue, BodyEncode, RequestHead, ResponseHead};
use futures::prelude::*;
use futures::stream::FuturesUnordered;
use futures::StreamExt;
use http::header::{IntoHeaderName, TRANSFER_ENCODING};
use http::{HeaderMap, HeaderValue, Method, Request, StatusCode, Uri, Version};
use std::borrow::Cow;
use std::io;
use std::pin::Pin;
use std::task::{Context, Poll};
pub struct HttpIncoming<IO: AsyncRead + AsyncWrite + Unpin, T: Stream<Item = IO> + Unpin> {
incoming: T,
decoding: FuturesUnordered<BufferDecode<IO, RequestHead<'static>>>,
}
impl<IO: AsyncRead + AsyncWrite + Unpin, T: Stream<Item = IO> + Unpin> HttpIncoming<IO, T> {
pub fn new(transport_incoming: T) -> Self {
HttpIncoming {
incoming: transport_incoming,
decoding: FuturesUnordered::new(),
}
}
pub fn or_ws(self) -> HttpOrWsIncoming<IO, Self> {
HttpOrWsIncoming::new(self)
}
}
impl<IO: AsyncRead + AsyncWrite + Unpin, T: Stream<Item = IO> + Unpin> Stream
for HttpIncoming<IO, T>
{
type Item = HttpRequest<IO>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
loop {
match self.decoding.poll_next_unpin(cx) {
Poll::Ready(Some(Ok((transport, head)))) => {
match BodyDecodeWithContinue::from_head(&head, transport) {
Ok(body) => return Poll::Ready(Some(HttpRequest { head, body })),
Err(err) => log::error!("http head error: {:?}", err),
};
}
Poll::Ready(Some(Err(err))) => log::error!("http head decode error: {:?}", err),
Poll::Ready(None) | Poll::Pending => match self.incoming.poll_next_unpin(cx) {
Poll::Ready(Some(transport)) => {
self.decoding.push(RequestHead::decode(transport))
}
Poll::Ready(None) => return Poll::Ready(None),
Poll::Pending => {
return Poll::Pending;
}
},
}
}
}
}
pub struct HttpRequest<IO: AsyncRead + AsyncWrite + Unpin> {
pub(crate) head: RequestHead<'static>,
pub(crate) body: BodyDecodeWithContinue<IO>,
}
impl<IO: AsyncRead + AsyncWrite + Unpin> HttpRequest<IO> {
pub fn into_inner(self) -> Request<IO> {
Request::from_parts(self.head.into(), self.body.checkpoint().0)
}
pub async fn response(mut self) -> anyhow::Result<HttpResponse<IO>> {
while 0 < self.body().read(&mut [0u8; 1 << 14]).await? {}
let Self { head, body } = self;
let request_head = http::request::Parts::from(head);
let request_headers = request_head.headers;
let request_method = request_head.method;
let request_uri = request_head.uri;
let transport = body.checkpoint().0;
let headers = Cow::Owned(HeaderMap::with_capacity(128));
Ok(HttpResponse {
request_headers,
request_uri,
request_method,
head: ResponseHead::new(StatusCode::OK, request_head.version, headers),
transport,
})
}
pub fn body(&mut self) -> &mut BodyDecodeWithContinue<IO> {
&mut self.body
}
pub async fn body_string(&mut self) -> anyhow::Result<String> {
let mut body = String::new();
self.body().read_to_string(&mut body).await?;
Ok(body)
}
pub async fn body_vec(&mut self) -> io::Result<Vec<u8>> {
let mut body = Vec::new();
self.body().read_to_end(&mut body).await?;
Ok(body)
}
pub fn headers(&self) -> &HeaderMap {
self.head.headers()
}
pub fn uri(&self) -> &Uri {
&self.head.uri()
}
pub fn method(&self) -> Method {
self.head.method().clone()
}
pub fn version(&self) -> Version {
self.head.version()
}
}
pub struct HttpResponse<IO: AsyncRead + AsyncWrite + Unpin> {
request_uri: Uri,
request_headers: HeaderMap,
request_method: Method,
head: ResponseHead<'static>,
transport: IO,
}
impl<IO: AsyncRead + AsyncWrite + Unpin> HttpResponse<IO> {
pub fn request_headers(&self) -> &HeaderMap {
&self.request_headers
}
pub fn uri(&self) -> &Uri {
&self.request_uri
}
pub fn method(&self) -> Method {
self.request_method.clone()
}
pub fn version(&self) -> Version {
self.head.version()
}
pub fn headers(&self) -> &HeaderMap {
self.head.headers()
}
pub fn headers_mut(&mut self) -> &mut HeaderMap {
self.head.headers_mut()
}
pub fn insert_header(&mut self, key: impl IntoHeaderName, value: HeaderValue) -> &mut Self {
self.headers_mut().insert(key, value);
self
}
pub fn status(&self) -> StatusCode {
self.head.status()
}
pub fn status_mut(&mut self) -> &mut StatusCode {
self.head.status_mut()
}
pub fn set_status(&mut self, status: StatusCode) -> &mut Self {
*self.status_mut() = status;
self
}
pub async fn send(mut self, body: impl AsRef<[u8]>) -> io::Result<()> {
self.insert_header(TRANSFER_ENCODING, HeaderValue::from_static("chunked"));
self.head.encode(&mut self.transport).await?;
let mut encoder = BodyEncode::new(&mut self.transport, None);
encoder.write_all(body.as_ref()).await?;
encoder.close().await?;
Ok(())
}
}