1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-11-24 16:32:59 +01:00
actix-web/actix-http/src/h2/dispatcher.rs

327 lines
11 KiB
Rust
Raw Normal View History

2019-02-06 20:44:15 +01:00
use std::collections::VecDeque;
use std::marker::PhantomData;
use std::time::Instant;
use std::{fmt, mem};
use actix_codec::{AsyncRead, AsyncWrite};
use actix_service::Service;
use actix_utils::cloneable::CloneableService;
2019-02-06 20:44:15 +01:00
use bitflags::bitflags;
use bytes::{Bytes, BytesMut};
use futures::{try_ready, Async, Future, Poll, Sink, Stream};
use h2::server::{Connection, SendResponse};
use h2::{RecvStream, SendStream};
use http::header::{
HeaderValue, ACCEPT_ENCODING, CONNECTION, CONTENT_LENGTH, DATE, TRANSFER_ENCODING,
};
use http::HttpTryFrom;
use log::{debug, error, trace};
use tokio_timer::Delay;
2019-03-27 17:24:55 +01:00
use crate::body::{Body, BodySize, MessageBody, ResponseBody};
2019-02-06 20:44:15 +01:00
use crate::config::ServiceConfig;
use crate::error::{DispatchError, Error, ParseError, PayloadError, ResponseError};
use crate::message::ResponseHead;
2019-02-07 22:41:50 +01:00
use crate::payload::Payload;
2019-02-06 20:44:15 +01:00
use crate::request::Request;
use crate::response::Response;
const CHUNK_SIZE: usize = 16_384;
/// Dispatcher for HTTP/2 protocol
2019-03-05 18:30:11 +01:00
pub struct Dispatcher<
T: AsyncRead + AsyncWrite,
2019-04-04 19:59:34 +02:00
S: Service<Request = Request>,
2019-03-05 18:30:11 +01:00
B: MessageBody,
> {
service: CloneableService<S>,
2019-02-06 20:44:15 +01:00
connection: Connection<T, Bytes>,
config: ServiceConfig,
ka_expire: Instant,
ka_timer: Option<Delay>,
_t: PhantomData<B>,
}
impl<T, S, B> Dispatcher<T, S, B>
where
T: AsyncRead + AsyncWrite,
2019-04-04 19:59:34 +02:00
S: Service<Request = Request>,
2019-04-06 01:46:44 +02:00
S::Error: Into<Error>,
2019-04-04 19:59:34 +02:00
S::Future: 'static,
S::Response: Into<Response<B>>,
2019-02-06 20:44:15 +01:00
B: MessageBody + 'static,
{
pub fn new(
service: CloneableService<S>,
2019-02-06 20:44:15 +01:00
connection: Connection<T, Bytes>,
config: ServiceConfig,
timeout: Option<Delay>,
) -> Self {
// let keepalive = config.keep_alive_enabled();
2019-02-06 20:44:15 +01:00
// let flags = if keepalive {
// Flags::KEEPALIVE | Flags::KEEPALIVE_ENABLED
// } else {
// Flags::empty()
// };
// keep-alive timer
let (ka_expire, ka_timer) = if let Some(delay) = timeout {
(delay.deadline(), Some(delay))
} else if let Some(delay) = config.keep_alive_timer() {
(delay.deadline(), Some(delay))
} else {
(config.now(), None)
};
Dispatcher {
service,
config,
ka_expire,
ka_timer,
connection,
_t: PhantomData,
}
}
}
impl<T, S, B> Future for Dispatcher<T, S, B>
where
T: AsyncRead + AsyncWrite,
2019-04-04 19:59:34 +02:00
S: Service<Request = Request>,
2019-04-06 01:46:44 +02:00
S::Error: Into<Error>,
2019-04-04 19:59:34 +02:00
S::Future: 'static,
S::Response: Into<Response<B>>,
2019-02-06 20:44:15 +01:00
B: MessageBody + 'static,
{
type Item = ();
2019-03-07 07:56:34 +01:00
type Error = DispatchError;
2019-02-06 20:44:15 +01:00
#[inline]
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
loop {
match self.connection.poll()? {
2019-03-12 00:42:33 +01:00
Async::Ready(None) => return Ok(Async::Ready(())),
2019-02-06 20:44:15 +01:00
Async::Ready(Some((req, res))) => {
// update keep-alive expire
if self.ka_timer.is_some() {
if let Some(expire) = self.config.keep_alive_expire() {
self.ka_expire = expire;
}
}
let (parts, body) = req.into_parts();
2019-02-07 22:41:50 +01:00
let mut req = Request::with_payload(body.into());
2019-02-06 20:44:15 +01:00
2019-02-08 06:16:46 +01:00
let head = &mut req.head_mut();
2019-02-06 20:44:15 +01:00
head.uri = parts.uri;
head.method = parts.method;
head.version = parts.version;
head.headers = parts.headers;
2019-04-04 19:59:34 +02:00
tokio_current_thread::spawn(ServiceResponse::<S::Future, B> {
2019-02-06 20:44:15 +01:00
state: ServiceResponseState::ServiceCall(
self.service.call(req),
Some(res),
),
config: self.config.clone(),
buffer: None,
})
}
Async::NotReady => return Ok(Async::NotReady),
}
}
}
}
2019-04-04 19:59:34 +02:00
struct ServiceResponse<F, B> {
state: ServiceResponseState<F, B>,
2019-02-06 20:44:15 +01:00
config: ServiceConfig,
buffer: Option<Bytes>,
}
2019-04-04 19:59:34 +02:00
enum ServiceResponseState<F, B> {
ServiceCall(F, Option<SendResponse<Bytes>>),
2019-02-06 20:44:15 +01:00
SendPayload(SendStream<Bytes>, ResponseBody<B>),
}
2019-04-04 19:59:34 +02:00
impl<F, B> ServiceResponse<F, B>
2019-02-06 20:44:15 +01:00
where
2019-04-04 19:59:34 +02:00
F: Future,
2019-04-06 01:46:44 +02:00
F::Error: Into<Error>,
2019-04-04 19:59:34 +02:00
F::Item: Into<Response<B>>,
2019-02-06 20:44:15 +01:00
B: MessageBody + 'static,
{
fn prepare_response(
&self,
head: &ResponseHead,
2019-03-27 17:24:55 +01:00
length: &mut BodySize,
2019-02-06 20:44:15 +01:00
) -> http::Response<()> {
let mut has_date = false;
2019-03-27 17:24:55 +01:00
let mut skip_len = length != &BodySize::Stream;
2019-02-06 20:44:15 +01:00
let mut res = http::Response::new(());
*res.status_mut() = head.status;
*res.version_mut() = http::Version::HTTP_2;
// Content length
match head.status {
http::StatusCode::NO_CONTENT
| http::StatusCode::CONTINUE
2019-03-27 17:24:55 +01:00
| http::StatusCode::PROCESSING => *length = BodySize::None,
2019-02-06 20:44:15 +01:00
http::StatusCode::SWITCHING_PROTOCOLS => {
skip_len = true;
2019-03-27 17:24:55 +01:00
*length = BodySize::Stream;
2019-02-06 20:44:15 +01:00
}
_ => (),
}
let _ = match length {
2019-03-27 17:24:55 +01:00
BodySize::None | BodySize::Stream => None,
BodySize::Empty => res
2019-02-06 20:44:15 +01:00
.headers_mut()
.insert(CONTENT_LENGTH, HeaderValue::from_static("0")),
2019-03-27 17:24:55 +01:00
BodySize::Sized(len) => res.headers_mut().insert(
2019-02-06 20:44:15 +01:00
CONTENT_LENGTH,
HeaderValue::try_from(format!("{}", len)).unwrap(),
),
2019-03-27 17:24:55 +01:00
BodySize::Sized64(len) => res.headers_mut().insert(
2019-02-06 20:44:15 +01:00
CONTENT_LENGTH,
HeaderValue::try_from(format!("{}", len)).unwrap(),
),
};
// copy headers
for (key, value) in head.headers.iter() {
match *key {
CONNECTION | TRANSFER_ENCODING => continue, // http2 specific
CONTENT_LENGTH if skip_len => continue,
DATE => has_date = true,
_ => (),
}
res.headers_mut().append(key, value.clone());
}
// set date header
if !has_date {
let mut bytes = BytesMut::with_capacity(29);
self.config.set_date_header(&mut bytes);
res.headers_mut()
.insert(DATE, HeaderValue::try_from(bytes.freeze()).unwrap());
}
res
}
}
2019-04-04 19:59:34 +02:00
impl<F, B> Future for ServiceResponse<F, B>
2019-02-06 20:44:15 +01:00
where
2019-04-04 19:59:34 +02:00
F: Future,
2019-04-06 01:46:44 +02:00
F::Error: Into<Error>,
2019-04-04 19:59:34 +02:00
F::Item: Into<Response<B>>,
2019-02-06 20:44:15 +01:00
B: MessageBody + 'static,
{
type Item = ();
type Error = ();
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
match self.state {
ServiceResponseState::ServiceCall(ref mut call, ref mut send) => {
match call.poll() {
Ok(Async::Ready(res)) => {
let (res, body) = res.into().replace_body(());
2019-02-06 20:44:15 +01:00
let mut send = send.take().unwrap();
let mut length = body.length();
let h2_res = self.prepare_response(res.head(), &mut length);
let stream = send
.send_response(h2_res, length.is_eof())
.map_err(|e| {
trace!("Error sending h2 response: {:?}", e);
})?;
if length.is_eof() {
Ok(Async::Ready(()))
} else {
self.state = ServiceResponseState::SendPayload(stream, body);
self.poll()
}
}
Ok(Async::NotReady) => Ok(Async::NotReady),
2019-03-12 00:42:33 +01:00
Err(_e) => {
2019-03-07 07:56:34 +01:00
let res: Response = Response::InternalServerError().finish();
2019-02-06 20:44:15 +01:00
let (res, body) = res.replace_body(());
let mut send = send.take().unwrap();
let mut length = body.length();
let h2_res = self.prepare_response(res.head(), &mut length);
let stream = send
.send_response(h2_res, length.is_eof())
.map_err(|e| {
trace!("Error sending h2 response: {:?}", e);
})?;
if length.is_eof() {
Ok(Async::Ready(()))
} else {
self.state = ServiceResponseState::SendPayload(
stream,
body.into_body(),
);
self.poll()
}
}
}
}
ServiceResponseState::SendPayload(ref mut stream, ref mut body) => loop {
loop {
if let Some(ref mut buffer) = self.buffer {
match stream.poll_capacity().map_err(|e| warn!("{:?}", e))? {
Async::NotReady => return Ok(Async::NotReady),
Async::Ready(None) => return Ok(Async::Ready(())),
Async::Ready(Some(cap)) => {
let len = buffer.len();
let bytes = buffer.split_to(std::cmp::min(cap, len));
if let Err(e) = stream.send_data(bytes, false) {
warn!("{:?}", e);
return Err(());
} else if !buffer.is_empty() {
let cap = std::cmp::min(buffer.len(), CHUNK_SIZE);
stream.reserve_capacity(cap);
} else {
self.buffer.take();
}
}
}
} else {
match body.poll_next() {
2019-03-12 00:42:33 +01:00
Ok(Async::NotReady) => {
return Ok(Async::NotReady);
}
2019-02-06 20:44:15 +01:00
Ok(Async::Ready(None)) => {
if let Err(e) = stream.send_data(Bytes::new(), true) {
warn!("{:?}", e);
return Err(());
} else {
return Ok(Async::Ready(()));
}
}
Ok(Async::Ready(Some(chunk))) => {
stream.reserve_capacity(std::cmp::min(
chunk.len(),
CHUNK_SIZE,
));
self.buffer = Some(chunk);
}
Err(e) => {
error!("Response payload stream error: {:?}", e);
return Err(());
}
}
}
}
},
}
}
}