1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-25 00:12:59 +01:00
actix-extras/src/server/h2writer.rs

219 lines
7.1 KiB
Rust
Raw Normal View History

2017-11-04 17:07:44 +01:00
use std::{io, cmp};
2017-12-14 01:44:35 +01:00
use bytes::{Bytes, BytesMut};
2017-11-04 17:07:44 +01:00
use futures::{Async, Poll};
use http2::{Reason, SendStream};
2018-01-03 04:37:33 +01:00
use http2::server::SendResponse;
2017-11-04 17:07:44 +01:00
use http::{Version, HttpTryFrom, Response};
2017-12-16 16:29:15 +01:00
use http::header::{HeaderValue, CONNECTION, TRANSFER_ENCODING, DATE, CONTENT_LENGTH};
2017-11-04 17:07:44 +01:00
2017-12-14 07:54:52 +01:00
use helpers;
2018-01-14 22:50:38 +01:00
use body::{Body, Binary};
use headers::ContentEncoding;
2017-12-09 13:33:40 +01:00
use httprequest::HttpMessage;
2017-11-04 17:07:44 +01:00
use httpresponse::HttpResponse;
2018-01-12 03:41:33 +01:00
use super::encoding::PayloadEncoder;
2018-01-15 02:00:28 +01:00
use super::shared::SharedBytes;
2018-01-12 03:41:33 +01:00
use super::{Writer, WriterState, MAX_WRITE_BUFFER_SIZE};
2017-11-04 17:07:44 +01:00
const CHUNK_SIZE: usize = 16_384;
bitflags! {
struct Flags: u8 {
const STARTED = 0b0000_0001;
const DISCONNECTED = 0b0000_0010;
const EOF = 0b0000_0100;
}
}
2017-11-04 17:07:44 +01:00
pub(crate) struct H2Writer {
2018-01-03 04:37:33 +01:00
respond: SendResponse<Bytes>,
2017-11-04 17:07:44 +01:00
stream: Option<SendStream<Bytes>>,
2017-11-09 01:44:23 +01:00
encoder: PayloadEncoder,
flags: Flags,
2017-11-10 21:29:54 +01:00
written: u64,
2017-12-15 05:48:31 +01:00
buffer: SharedBytes,
2017-11-04 17:07:44 +01:00
}
impl H2Writer {
2018-01-03 04:37:33 +01:00
pub fn new(respond: SendResponse<Bytes>, buf: SharedBytes) -> H2Writer {
2017-11-04 17:07:44 +01:00
H2Writer {
respond: respond,
stream: None,
2017-12-15 05:48:31 +01:00
encoder: PayloadEncoder::empty(buf.clone()),
flags: Flags::empty(),
2017-11-10 21:29:54 +01:00
written: 0,
2017-12-15 05:48:31 +01:00
buffer: buf,
2017-11-04 17:07:44 +01:00
}
}
pub fn reset(&mut self, reason: Reason) {
if let Some(mut stream) = self.stream.take() {
stream.send_reset(reason)
}
}
2018-01-14 22:50:38 +01:00
fn write_to_stream(&mut self) -> io::Result<WriterState> {
if !self.flags.contains(Flags::STARTED) {
2017-11-04 17:07:44 +01:00
return Ok(WriterState::Done)
}
if let Some(ref mut stream) = self.stream {
2018-01-15 02:00:28 +01:00
if self.buffer.is_empty() {
if self.flags.contains(Flags::EOF) {
2017-11-04 17:07:44 +01:00
let _ = stream.send_data(Bytes::new(), true);
}
return Ok(WriterState::Done)
}
loop {
match stream.poll_capacity() {
Ok(Async::NotReady) => {
2018-01-15 02:00:28 +01:00
if self.buffer.len() > MAX_WRITE_BUFFER_SIZE {
2017-11-04 17:07:44 +01:00
return Ok(WriterState::Pause)
} else {
return Ok(WriterState::Done)
}
}
Ok(Async::Ready(None)) => {
return Ok(WriterState::Done)
}
Ok(Async::Ready(Some(cap))) => {
2018-01-15 02:00:28 +01:00
let len = self.buffer.len();
let bytes = self.buffer.split_to(cmp::min(cap, len));
let eof = self.buffer.is_empty() && self.flags.contains(Flags::EOF);
2017-11-10 21:29:54 +01:00
self.written += bytes.len() as u64;
2017-11-04 17:07:44 +01:00
if let Err(err) = stream.send_data(bytes.freeze(), eof) {
return Err(io::Error::new(io::ErrorKind::Other, err))
2018-01-15 02:00:28 +01:00
} else if !self.buffer.is_empty() {
let cap = cmp::min(self.buffer.len(), CHUNK_SIZE);
stream.reserve_capacity(cap);
2017-11-04 17:07:44 +01:00
} else {
2017-12-31 22:22:11 +01:00
return Ok(WriterState::Pause)
2017-11-04 17:07:44 +01:00
}
}
Err(_) => {
return Err(io::Error::new(io::ErrorKind::Other, ""))
}
}
}
}
Ok(WriterState::Done)
2017-11-04 17:07:44 +01:00
}
}
impl Writer for H2Writer {
2017-11-10 21:29:54 +01:00
fn written(&self) -> u64 {
self.written
}
fn start(&mut self, req: &mut HttpMessage, msg: &mut HttpResponse, encoding: ContentEncoding)
-> io::Result<WriterState> {
2017-11-04 17:07:44 +01:00
// prepare response
self.flags.insert(Flags::STARTED);
self.encoder = PayloadEncoder::new(self.buffer.clone(), req, msg, encoding);
if let Body::Empty = *msg.body() {
self.flags.insert(Flags::EOF);
}
2017-11-04 17:07:44 +01:00
// http2 specific
2017-12-08 02:38:18 +01:00
msg.headers_mut().remove(CONNECTION);
msg.headers_mut().remove(TRANSFER_ENCODING);
2017-11-04 17:07:44 +01:00
2017-12-14 07:54:52 +01:00
// using helpers::date is quite a lot faster
2017-12-08 02:38:18 +01:00
if !msg.headers().contains_key(DATE) {
2017-12-14 01:44:35 +01:00
let mut bytes = BytesMut::with_capacity(29);
2017-12-31 22:22:11 +01:00
helpers::date_value(&mut bytes);
msg.headers_mut().insert(DATE, HeaderValue::try_from(bytes.freeze()).unwrap());
2017-11-04 17:07:44 +01:00
}
2017-12-31 22:22:11 +01:00
let body = msg.replace_body(Body::Empty);
match body {
2017-12-16 16:29:15 +01:00
Body::Binary(ref bytes) => {
let mut val = BytesMut::new();
helpers::convert_usize(bytes.len(), &mut val);
2017-12-31 22:22:11 +01:00
let l = val.len();
msg.headers_mut().insert(
CONTENT_LENGTH, HeaderValue::try_from(val.split_to(l-2).freeze()).unwrap());
2017-12-16 16:29:15 +01:00
}
Body::Empty => {
2017-12-31 22:22:11 +01:00
msg.headers_mut().insert(CONTENT_LENGTH, HeaderValue::from_static("0"));
2017-12-16 16:29:15 +01:00
},
_ => (),
}
2017-12-31 22:22:11 +01:00
let mut resp = Response::new(());
*resp.status_mut() = msg.status();
*resp.version_mut() = Version::HTTP_2;
for (key, value) in msg.headers().iter() {
resp.headers_mut().insert(key, value.clone());
}
match self.respond.send_response(resp, self.flags.contains(Flags::EOF)) {
2017-11-09 01:44:23 +01:00
Ok(stream) =>
self.stream = Some(stream),
Err(_) =>
return Err(io::Error::new(io::ErrorKind::Other, "err")),
}
2017-12-31 22:22:11 +01:00
trace!("Response: {:?}", msg);
2017-11-09 04:31:25 +01:00
2017-12-31 22:22:11 +01:00
if let Body::Binary(bytes) = body {
self.flags.insert(Flags::EOF);
2018-01-02 23:53:51 +01:00
self.written = bytes.len() as u64;
2018-01-14 23:40:39 +01:00
self.encoder.write(bytes)?;
2017-12-31 22:22:11 +01:00
if let Some(ref mut stream) = self.stream {
2018-01-15 02:00:28 +01:00
stream.reserve_capacity(cmp::min(self.buffer.len(), CHUNK_SIZE));
2017-11-04 17:07:44 +01:00
}
2017-12-31 22:22:11 +01:00
Ok(WriterState::Pause)
} else {
msg.replace_body(body);
Ok(WriterState::Done)
2017-11-04 17:07:44 +01:00
}
}
2018-01-14 22:50:38 +01:00
fn write(&mut self, payload: Binary) -> io::Result<WriterState> {
2018-01-02 23:53:51 +01:00
self.written = payload.len() as u64;
if !self.flags.contains(Flags::DISCONNECTED) {
if self.flags.contains(Flags::STARTED) {
2017-11-04 17:07:44 +01:00
// TODO: add warning, write after EOF
2018-01-14 23:40:39 +01:00
self.encoder.write(payload)?;
2017-11-04 17:07:44 +01:00
} else {
// might be response for EXCEPT
2018-01-15 02:00:28 +01:00
self.buffer.extend_from_slice(payload.as_ref())
2017-11-04 17:07:44 +01:00
}
}
2018-01-15 02:00:28 +01:00
if self.buffer.len() > MAX_WRITE_BUFFER_SIZE {
Ok(WriterState::Pause)
2017-11-04 17:07:44 +01:00
} else {
Ok(WriterState::Done)
2017-11-04 17:07:44 +01:00
}
}
2018-01-14 22:50:38 +01:00
fn write_eof(&mut self) -> io::Result<WriterState> {
2017-11-09 01:44:23 +01:00
self.encoder.write_eof()?;
self.flags.insert(Flags::EOF);
2017-11-09 01:44:23 +01:00
if !self.encoder.is_eof() {
2017-11-04 17:07:44 +01:00
Err(io::Error::new(io::ErrorKind::Other,
"Last payload item, but eof is not reached"))
2018-01-15 02:00:28 +01:00
} else if self.buffer.len() > MAX_WRITE_BUFFER_SIZE {
Ok(WriterState::Pause)
2017-11-04 17:07:44 +01:00
} else {
Ok(WriterState::Done)
2017-11-04 17:07:44 +01:00
}
}
fn poll_completed(&mut self, _shutdown: bool) -> Poll<(), io::Error> {
2017-11-04 17:07:44 +01:00
match self.write_to_stream() {
Ok(WriterState::Done) => Ok(Async::Ready(())),
Ok(WriterState::Pause) => Ok(Async::NotReady),
Err(err) => Err(err)
}
}
}