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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
use crate::raw::{BodyPart, DefaultRawBody};
use crate::BaseBody;
use bytes::{Buf, Bytes, BytesMut};
use conjure_error::Error;
use futures::channel::mpsc;
use futures::{ready, SinkExt, Stream};
use http::HeaderMap;
use http_body::Body;
use pin_project::pin_project;
use std::marker::PhantomPinned;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::{error, io, mem};
use tokio::io::{AsyncBufRead, AsyncRead, AsyncWrite, AsyncWriteExt, ReadBuf};
#[pin_project]
pub struct BodyWriter {
#[pin]
sender: mpsc::Sender<BodyPart>,
buf: BytesMut,
#[pin]
_p: PhantomPinned,
}
impl BodyWriter {
pub(crate) fn new(sender: mpsc::Sender<BodyPart>) -> BodyWriter {
BodyWriter {
sender,
buf: BytesMut::new(),
_p: PhantomPinned,
}
}
pub(crate) async fn finish(mut self: Pin<&mut Self>) -> io::Result<()> {
self.flush().await?;
self.project()
.sender
.send(BodyPart::Done)
.await
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
Ok(())
}
pub async fn write_bytes(mut self: Pin<&mut Self>, bytes: Bytes) -> io::Result<()> {
self.flush().await?;
self.project()
.sender
.send(BodyPart::Chunk(bytes))
.await
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
Ok(())
}
}
impl AsyncWrite for BodyWriter {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
if self.buf.len() > 4096 {
ready!(self.as_mut().poll_flush(cx))?;
}
self.project().buf.extend_from_slice(buf);
Poll::Ready(Ok(buf.len()))
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
let mut this = self.project();
if this.buf.is_empty() {
return Poll::Ready(Ok(()));
}
ready!(this.sender.poll_ready(cx)).map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
let chunk = this.buf.split().freeze();
this.sender
.start_send(BodyPart::Chunk(chunk))
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
Poll::Ready(Ok(()))
}
fn poll_shutdown(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
Poll::Ready(Ok(()))
}
}
#[pin_project]
pub struct ResponseBody<B = DefaultRawBody> {
#[pin]
body: FuseBody<BaseBody<B>>,
cur: Bytes,
#[pin]
_p: PhantomPinned,
}
impl<B> ResponseBody<B> {
pub(crate) fn new(body: BaseBody<B>) -> Self {
ResponseBody {
body: FuseBody::new(body),
cur: Bytes::new(),
_p: PhantomPinned,
}
}
pub(crate) fn buffer(&self) -> &[u8] {
&self.cur
}
}
impl<B> Stream for ResponseBody<B>
where
B: Body<Data = Bytes>,
B::Error: Into<Box<dyn error::Error + Sync + Send>>,
{
type Item = Result<Bytes, Error>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.project();
if this.cur.has_remaining() {
return Poll::Ready(Some(Ok(mem::take(this.cur))));
}
this.body.poll_data(cx).map_err(Error::internal_safe)
}
}
impl<B> AsyncRead for ResponseBody<B>
where
B: Body<Data = Bytes>,
B::Error: Into<Box<dyn error::Error + Sync + Send>>,
{
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
let in_buf = ready!(self.as_mut().poll_fill_buf(cx))?;
let len = usize::min(in_buf.len(), buf.remaining());
buf.put_slice(&in_buf[..len]);
self.consume(len);
Poll::Ready(Ok(()))
}
}
impl<B> AsyncBufRead for ResponseBody<B>
where
B: Body<Data = Bytes>,
B::Error: Into<Box<dyn error::Error + Sync + Send>>,
{
fn poll_fill_buf(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> {
while !self.cur.has_remaining() {
match ready!(self.as_mut().project().body.poll_data(cx)).transpose()? {
Some(bytes) => *self.as_mut().project().cur = bytes,
None => break,
}
}
Poll::Ready(Ok(self.project().cur))
}
fn consume(self: Pin<&mut Self>, amt: usize) {
self.project().cur.advance(amt)
}
}
#[pin_project]
struct FuseBody<B> {
#[pin]
body: B,
done: bool,
}
impl<B> FuseBody<B> {
fn new(body: B) -> FuseBody<B> {
FuseBody { body, done: false }
}
}
impl<B> Body for FuseBody<B>
where
B: Body,
{
type Data = B::Data;
type Error = B::Error;
fn poll_data(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Self::Data, Self::Error>>> {
let this = self.project();
if *this.done {
return Poll::Ready(None);
}
let chunk = ready!(this.body.poll_data(cx));
if chunk.is_none() {
*this.done = true;
}
Poll::Ready(chunk)
}
fn size_hint(&self) -> http_body::SizeHint {
self.body.size_hint()
}
fn poll_trailers(
self: Pin<&mut Self>,
cx: &mut Context,
) -> Poll<Result<Option<HeaderMap>, Self::Error>> {
self.project().body.poll_trailers(cx)
}
}