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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
use crate::limit::LimitWrite;
use crate::server::Codec;
use crate::server::ServerDrive;
use crate::AsyncRead;
use crate::Error;
use futures_channel::mpsc;
use futures_util::future::poll_fn;
use futures_util::ready;
use futures_util::sink::Sink;
use futures_util::stream::Stream;
use std::fmt;
use std::io;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};

/// Send some body data to a remote peer.
///
/// Obtained either via a [`client::SendRequest`] or a [`server::SendResponse`].
///
/// [`client::SendRequest`]: client/struct.SendRequest.html
/// [`server::SendResponse`]: server/struct.SendResponse.html
pub struct SendStream {
    tx_body: mpsc::Sender<(Vec<u8>, bool)>,
    limit: LimitWrite,
    ended: bool,
    // used in RecvStream originating in server to drive the connection
    // from the RecvStream polling itelf.
    server_inner: Option<Arc<Mutex<Codec>>>,
}

impl SendStream {
    pub(crate) fn new(
        tx_body: mpsc::Sender<(Vec<u8>, bool)>,
        limit: LimitWrite,
        ended: bool,
        server_inner: Option<Arc<Mutex<Codec>>>,
    ) -> Self {
        SendStream {
            tx_body,
            limit,
            ended,
            server_inner,
        }
    }

    /// Poll for whether this connection is ready to send more data without blocking.
    fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Error>> {
        let this = self.get_mut();

        if let Some(server_inner) = &this.server_inner {
            server_inner.poll_drive_external(cx)?;
        }

        ready!(Pin::new(&mut this.tx_body).poll_ready(cx))
            .map_err(|e| io::Error::new(io::ErrorKind::ConnectionAborted, e))?;

        Ok(()).into()
    }

    /// Test whether connection is ready to send more data. The call stalls until
    /// any previous data provided in `send_data()` has been transfered to the remote
    /// peer (or at least in a buffer). As such, this can form part of a flow control.
    pub async fn ready(mut self) -> Result<SendStream, Error> {
        poll_fn(|cx| Pin::new(&mut self).poll_ready(cx)).await?;
        Ok(self)
    }

    /// Send some body data.
    ///
    /// `end` controls whether this is the last body chunk to send. It's an error
    /// to send more data after `end` is `true`.
    fn poll_send_data(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        data: &[u8],
        end: bool,
    ) -> Poll<Result<(), Error>> {
        let this = self.get_mut();

        if this.ended {
            return Err(Error::User("Body data is not expected".into())).into();
        }

        if let Some(server_inner) = &this.server_inner {
            server_inner.poll_drive_external(cx)?;
        }

        let mut chunk = Vec::with_capacity(data.len() + this.limit.overhead());
        this.limit.write(data, &mut chunk)?;

        if end {
            this.ended = true;
            this.limit.finish(&mut chunk)?;
        }

        this.tx_body
            .start_send((chunk, end))
            .map_err(|e| io::Error::new(io::ErrorKind::ConnectionAborted, e))?;

        Ok(()).into()
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Error>> {
        let this = self.get_mut();

        if let Some(server_inner) = &this.server_inner {
            server_inner.poll_drive_external(cx)?;
        }

        ready!(Pin::new(&mut this.tx_body)
            .poll_flush(cx)
            .map_err(|e| io::Error::new(io::ErrorKind::ConnectionAborted, e)))?;

        if let Some(server_inner) = &this.server_inner {
            server_inner.poll_drive_external(cx)?;
        }

        Ok(()).into()
    }

    /// Send one chunk of data. Use `end` to signal end of data.
    ///
    /// Alternate calls to this with calls to `ready` for flow control.
    ///
    /// When the body is constrained by a `content-length` header, this will only accept
    /// the amount of bytes specified in the header. If there is too much data, the
    /// function will error with a `Error::User`.
    ///
    /// For `transfer-encoding: chunked`, call to this function corresponds to one "chunk".
    pub async fn send_data(&mut self, data: &[u8], end: bool) -> Result<(), Error> {
        poll_fn(|cx| Pin::new(&mut *self).poll_ready(cx)).await?;
        poll_fn(|cx| Pin::new(&mut *self).poll_send_data(cx, data, end)).await?;
        poll_fn(|cx| Pin::new(&mut *self).poll_flush(cx)).await?;
        Ok(())
    }
}

/// Receives a body from the remote peer.
///
/// Obtained from either a [`client::ResponseFuture`] or [`server::Connection`].
///
/// [`client::ResponseFuture`]: client/struct.ResponseFuture.html
/// [`server::Connection`]: server/struct.Connection.html
pub struct RecvStream {
    rx_body: mpsc::Receiver<io::Result<Vec<u8>>>,
    ready: Option<Vec<u8>>,
    index: usize,
    // used in RecvStream originating in server to drive the connection
    // from the RecvStream polling itelf.
    server_inner: Option<Arc<Mutex<Codec>>>,
    ended: bool,
}

impl RecvStream {
    pub(crate) fn new(
        rx_body: mpsc::Receiver<io::Result<Vec<u8>>>,
        server_inner: Option<Arc<Mutex<Codec>>>,
        ended: bool,
    ) -> Self {
        RecvStream {
            rx_body,
            ready: None,
            index: 0,
            server_inner,
            ended,
        }
    }

    #[doc(hidden)]
    /// Poll for some body data.
    pub fn poll_body_data(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut [u8],
    ) -> Poll<io::Result<usize>> {
        let this = self.get_mut();

        // must drive the connection if server.
        if let Some(server_inner) = &this.server_inner {
            server_inner.poll_drive_external(cx)?;
        }

        if this.ended {
            return Ok(0).into();
        }

        loop {
            // First ship out ready data already received.
            if let Some(ready) = &this.ready {
                let i = this.index;

                let max = buf.len().min(ready.len() - i);

                (&mut buf[0..max]).copy_from_slice(&ready[i..(i + max)]);
                this.index += max;

                if this.index == ready.len() {
                    // all used up
                    this.ready.take();
                }

                return Ok(max).into();
            }

            // invariant: Should be no ready bytes if we're here.
            assert!(this.ready.is_none());

            match ready!(Pin::new(&mut this.rx_body).poll_next(cx)) {
                None => {
                    // Channel is closed which indicates end of body.
                    this.ended = true;
                    return Ok(0).into();
                }
                Some(v) => {
                    // nested io::Error
                    let v = v?;

                    this.ready = Some(v);
                    this.index = 0;
                }
            }
        }
    }

    /// Read some body data into a given buffer.
    ///
    /// Ends when returned size is `0`.
    pub async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
        Ok(poll_fn(move |cx| Pin::new(&mut *self).poll_read(cx, buf)).await?)
    }

    /// Returns `true` if there is no more data to receive.
    ///
    /// Specifically any further call to `read` will result in `0` bytes read.
    pub fn is_end_stream(&self) -> bool {
        self.ended
    }
}

impl AsyncRead for RecvStream {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut [u8],
    ) -> Poll<io::Result<usize>> {
        self.poll_body_data(cx, buf)
    }
}

impl fmt::Debug for SendStream {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "SendStream")
    }
}

impl fmt::Debug for RecvStream {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "RecvStream")
    }
}