1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-11-25 17:02:44 +01:00
actix-web/src/h1/dispatcher.rs

512 lines
19 KiB
Rust
Raw Normal View History

2018-10-05 01:22:00 +02:00
use std::collections::VecDeque;
2018-10-07 18:48:53 +02:00
use std::fmt::Debug;
2018-10-05 08:39:11 +02:00
use std::time::Instant;
2018-10-05 01:22:00 +02:00
2018-10-05 23:30:40 +02:00
use actix_net::codec::Framed;
2018-10-05 01:22:00 +02:00
use actix_net::service::Service;
use futures::{Async, AsyncSink, Future, Poll, Sink, Stream};
2018-10-05 05:02:10 +02:00
use tokio_io::{AsyncRead, AsyncWrite};
2018-10-05 08:39:11 +02:00
use tokio_timer::Delay;
2018-10-05 01:22:00 +02:00
2018-10-07 09:04:38 +02:00
use error::{ParseError, PayloadError};
2018-10-05 16:02:09 +02:00
use payload::{Payload, PayloadSender, PayloadStatus, PayloadWriter};
2018-10-05 01:22:00 +02:00
2018-10-09 00:24:51 +02:00
use body::{Body, BodyStream};
2018-10-05 06:14:18 +02:00
use config::ServiceConfig;
2018-10-05 05:02:10 +02:00
use error::DispatchError;
2018-10-05 06:14:18 +02:00
use request::Request;
2018-10-05 20:04:59 +02:00
use response::Response;
2018-10-05 05:02:10 +02:00
use super::codec::Codec;
use super::{H1ServiceResult, Message, MessageType};
2018-10-05 01:22:00 +02:00
const MAX_PIPELINED_MESSAGES: usize = 16;
bitflags! {
pub struct Flags: u8 {
const STARTED = 0b0000_0001;
const KEEPALIVE_ENABLED = 0b0000_0010;
const KEEPALIVE = 0b0000_0100;
2018-10-07 18:48:53 +02:00
const POLLED = 0b0000_1000;
const FLUSHED = 0b0001_0000;
const SHUTDOWN = 0b0010_0000;
const DISCONNECTED = 0b0100_0000;
2018-10-05 01:22:00 +02:00
}
}
/// Dispatcher for HTTP/1.1 protocol
2018-10-05 05:02:10 +02:00
pub struct Dispatcher<T, S: Service>
2018-10-05 01:22:00 +02:00
where
2018-10-07 18:48:53 +02:00
S::Error: Debug,
2018-10-05 01:22:00 +02:00
{
service: S,
flags: Flags,
framed: Option<Framed<T, Codec>>,
2018-10-05 05:02:10 +02:00
error: Option<DispatchError<S::Error>>,
2018-10-05 08:39:11 +02:00
config: ServiceConfig,
2018-10-05 01:22:00 +02:00
state: State<S>,
2018-10-05 16:02:09 +02:00
payload: Option<PayloadSender>,
messages: VecDeque<DispatcherMessage>,
unhandled: Option<Request>,
2018-10-05 06:14:18 +02:00
2018-10-05 08:39:11 +02:00
ka_expire: Instant,
ka_timer: Option<Delay>,
2018-10-05 01:22:00 +02:00
}
enum DispatcherMessage {
2018-10-07 06:07:32 +02:00
Item(Request),
Error(Response),
}
2018-10-05 01:22:00 +02:00
enum State<S: Service> {
None,
2018-10-07 09:04:38 +02:00
ServiceCall(S::Future),
SendResponse(Option<(Message<Response>, Body)>),
2018-11-14 19:52:40 +01:00
SendPayload(BodyStream),
2018-10-05 01:22:00 +02:00
}
impl<S: Service> State<S> {
fn is_empty(&self) -> bool {
if let State::None = self {
true
} else {
false
}
}
}
2018-10-05 05:02:10 +02:00
impl<T, S> Dispatcher<T, S>
2018-10-05 01:22:00 +02:00
where
2018-10-05 05:02:10 +02:00
T: AsyncRead + AsyncWrite,
2018-10-05 20:04:59 +02:00
S: Service<Request = Request, Response = Response>,
2018-10-07 18:48:53 +02:00
S::Error: Debug,
2018-10-05 01:22:00 +02:00
{
2018-10-05 05:02:10 +02:00
/// Create http/1 dispatcher.
2018-10-05 06:14:18 +02:00
pub fn new(stream: T, config: ServiceConfig, service: S) -> Self {
2018-10-05 08:39:11 +02:00
Dispatcher::with_timeout(stream, config, None, service)
}
/// Create http/1 dispatcher with slow request timeout.
pub fn with_timeout(
2018-10-30 00:39:46 +01:00
stream: T,
config: ServiceConfig,
timeout: Option<Delay>,
service: S,
2018-10-05 08:39:11 +02:00
) -> Self {
2018-10-05 19:03:10 +02:00
let keepalive = config.keep_alive_enabled();
let flags = if keepalive {
2018-10-05 08:39:11 +02:00
Flags::KEEPALIVE | Flags::KEEPALIVE_ENABLED | Flags::FLUSHED
} else {
Flags::FLUSHED
};
2018-10-08 19:14:29 +02:00
let framed = Framed::new(stream, Codec::new(config.clone()));
2018-10-05 01:22:00 +02:00
2018-10-09 00:24:51 +02:00
// keep-alive timer
2018-10-05 08:39:11 +02:00
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)
};
2018-10-05 05:02:10 +02:00
Dispatcher {
2018-10-05 01:22:00 +02:00
payload: None,
state: State::None,
error: None,
messages: VecDeque::new(),
framed: Some(framed),
unhandled: None,
2018-10-05 01:22:00 +02:00
service,
flags,
2018-10-05 06:14:18 +02:00
config,
2018-10-05 08:39:11 +02:00
ka_expire,
ka_timer,
2018-10-05 01:22:00 +02:00
}
}
fn can_read(&self) -> bool {
2018-10-07 18:48:53 +02:00
if self.flags.contains(Flags::DISCONNECTED) {
2018-10-05 01:22:00 +02:00
return false;
}
if let Some(ref info) = self.payload {
info.need_read() == PayloadStatus::Read
} else {
true
}
}
// if checked is set to true, delay disconnect until all tasks have finished.
2018-10-07 06:07:32 +02:00
fn client_disconnected(&mut self) {
2018-10-07 18:48:53 +02:00
self.flags.insert(Flags::DISCONNECTED);
2018-10-05 01:22:00 +02:00
if let Some(mut payload) = self.payload.take() {
payload.set_error(PayloadError::Incomplete(None));
2018-10-05 01:22:00 +02:00
}
}
/// Flush stream
2018-10-05 05:02:10 +02:00
fn poll_flush(&mut self) -> Poll<(), DispatchError<S::Error>> {
2018-10-07 18:48:53 +02:00
if !self.flags.contains(Flags::FLUSHED) {
match self.framed.as_mut().unwrap().poll_complete() {
2018-10-05 01:22:00 +02:00
Ok(Async::NotReady) => Ok(Async::NotReady),
Err(err) => {
debug!("Error sending data: {}", err);
Err(err.into())
}
Ok(Async::Ready(_)) => {
// if payload is not consumed we can not use connection
if self.payload.is_some() && self.state.is_empty() {
2018-10-05 05:02:10 +02:00
return Err(DispatchError::PayloadIsNotConsumed);
2018-10-05 01:22:00 +02:00
}
self.flags.insert(Flags::FLUSHED);
Ok(Async::Ready(()))
}
}
} else {
Ok(Async::Ready(()))
}
}
2018-10-07 18:48:53 +02:00
fn poll_response(&mut self) -> Result<(), DispatchError<S::Error>> {
2018-10-05 01:22:00 +02:00
let mut retry = self.can_read();
// process
loop {
let state = match self.state {
2018-10-30 00:39:46 +01:00
State::None => if let Some(msg) = self.messages.pop_front() {
match msg {
DispatcherMessage::Item(req) => Some(self.handle_request(req)?),
DispatcherMessage::Error(res) => Some(State::SendResponse(
Some((Message::Item(res), Body::Empty)),
)),
}
} else {
None
2018-10-05 01:22:00 +02:00
},
2018-10-09 00:24:51 +02:00
// call inner service
State::ServiceCall(ref mut fut) => {
match fut.poll().map_err(DispatchError::Service)? {
Async::Ready(mut res) => {
self.framed
.as_mut()
.unwrap()
.get_codec_mut()
.prepare_te(&mut res);
2018-10-09 00:24:51 +02:00
let body = res.replace_body(Body::Empty);
Some(State::SendResponse(Some((Message::Item(res), body))))
2018-10-05 01:22:00 +02:00
}
2018-10-09 00:24:51 +02:00
Async::NotReady => None,
2018-10-07 07:36:57 +02:00
}
2018-10-09 00:24:51 +02:00
}
// send respons
2018-10-05 01:22:00 +02:00
State::SendResponse(ref mut item) => {
2018-10-09 00:24:51 +02:00
let (msg, body) = item.take().expect("SendResponse is empty");
2018-11-14 19:52:40 +01:00
let framed = self.framed.as_mut().unwrap();
match framed.start_send(msg) {
2018-10-05 01:22:00 +02:00
Ok(AsyncSink::Ready) => {
2018-11-14 19:52:40 +01:00
self.flags
.set(Flags::KEEPALIVE, framed.get_codec().keepalive());
2018-10-05 01:22:00 +02:00
self.flags.remove(Flags::FLUSHED);
2018-10-09 00:24:51 +02:00
match body {
Body::Empty => Some(State::None),
Body::Streaming(stream) => {
2018-11-14 19:52:40 +01:00
Some(State::SendPayload(stream))
}
Body::Binary(mut bin) => {
self.flags.remove(Flags::FLUSHED);
framed
.force_send(Message::Chunk(Some(bin.take())))?;
framed.force_send(Message::Chunk(None))?;
Some(State::None)
2018-10-09 00:24:51 +02:00
}
}
2018-10-05 01:22:00 +02:00
}
Ok(AsyncSink::NotReady(msg)) => {
2018-10-09 00:24:51 +02:00
*item = Some((msg, body));
2018-10-05 01:22:00 +02:00
return Ok(());
}
2018-10-07 07:36:57 +02:00
Err(err) => {
if let Some(mut payload) = self.payload.take() {
payload.set_error(PayloadError::Incomplete(None));
2018-10-07 07:36:57 +02:00
}
return Err(DispatchError::Io(err));
}
2018-10-05 01:22:00 +02:00
}
}
2018-10-09 00:24:51 +02:00
// Send payload
2018-11-14 19:52:40 +01:00
State::SendPayload(ref mut stream) => {
let mut framed = self.framed.as_mut().unwrap();
loop {
if !framed.is_write_buf_full() {
match stream.poll().map_err(|_| DispatchError::Unknown)? {
Async::Ready(Some(item)) => {
2018-10-09 00:24:51 +02:00
self.flags.remove(Flags::FLUSHED);
2018-11-14 19:52:40 +01:00
framed.force_send(Message::Chunk(Some(item)))?;
2018-10-09 00:24:51 +02:00
continue;
}
2018-11-14 19:52:40 +01:00
Async::Ready(None) => {
self.flags.remove(Flags::FLUSHED);
framed.force_send(Message::Chunk(None))?;
2018-10-09 00:24:51 +02:00
}
2018-11-14 19:52:40 +01:00
Async::NotReady => return Ok(()),
}
} else {
return Ok(());
2018-10-09 00:24:51 +02:00
}
2018-11-14 19:52:40 +01:00
break;
2018-10-09 00:24:51 +02:00
}
2018-11-14 19:52:40 +01:00
None
2018-10-05 01:22:00 +02:00
}
};
match state {
2018-10-07 07:36:57 +02:00
Some(state) => self.state = state,
2018-10-05 01:22:00 +02:00
None => {
// if read-backpressure is enabled and we consumed some data.
// we may read more dataand retry
2018-10-07 18:48:53 +02:00
if !retry && self.can_read() && self.poll_request()? {
2018-10-05 01:22:00 +02:00
retry = self.can_read();
continue;
}
break;
}
}
}
Ok(())
}
2018-10-07 09:04:38 +02:00
fn handle_request(
2018-10-30 00:39:46 +01:00
&mut self,
req: Request,
2018-10-07 09:04:38 +02:00
) -> Result<State<S>, DispatchError<S::Error>> {
2018-10-07 07:36:57 +02:00
let mut task = self.service.call(req);
2018-10-07 09:04:38 +02:00
match task.poll().map_err(DispatchError::Service)? {
Async::Ready(mut res) => {
self.framed
.as_mut()
.unwrap()
.get_codec_mut()
.prepare_te(&mut res);
2018-10-07 09:04:38 +02:00
let body = res.replace_body(Body::Empty);
Ok(State::SendResponse(Some((Message::Item(res), body))))
2018-10-07 07:36:57 +02:00
}
2018-10-07 09:04:38 +02:00
Async::NotReady => Ok(State::ServiceCall(task)),
2018-10-07 07:36:57 +02:00
}
}
2018-10-09 19:36:40 +02:00
/// Process one incoming requests
pub(self) fn poll_request(&mut self) -> Result<bool, DispatchError<S::Error>> {
// limit a mount of non processed requests
if self.messages.len() >= MAX_PIPELINED_MESSAGES {
return Ok(false);
2018-10-05 01:22:00 +02:00
}
let mut updated = false;
2018-10-30 00:39:46 +01:00
loop {
match self.framed.as_mut().unwrap().poll() {
2018-10-09 19:36:40 +02:00
Ok(Async::Ready(Some(msg))) => {
updated = true;
self.flags.insert(Flags::STARTED);
match msg {
Message::Item(req) => {
match self
.framed
.as_ref()
.unwrap()
.get_codec()
.message_type()
{
MessageType::Payload => {
let (ps, pl) = Payload::new(false);
*req.inner.payload.borrow_mut() = Some(pl);
self.payload = Some(ps);
}
2018-11-14 07:53:30 +01:00
MessageType::Stream => {
self.unhandled = Some(req);
return Ok(updated);
}
_ => (),
2018-10-09 19:36:40 +02:00
}
2018-10-05 01:22:00 +02:00
2018-10-09 19:36:40 +02:00
// handle request early
if self.state.is_empty() {
self.state = self.handle_request(req)?;
} else {
self.messages.push_back(DispatcherMessage::Item(req));
2018-10-09 19:36:40 +02:00
}
}
Message::Chunk(Some(chunk)) => {
2018-10-09 19:36:40 +02:00
if let Some(ref mut payload) = self.payload {
payload.feed_data(chunk);
} else {
error!(
"Internal server error: unexpected payload chunk"
);
self.flags.insert(Flags::DISCONNECTED);
self.messages.push_back(DispatcherMessage::Error(
2018-10-09 19:36:40 +02:00
Response::InternalServerError().finish(),
));
self.error = Some(DispatchError::InternalError);
2018-11-06 04:32:03 +01:00
break;
2018-10-09 19:36:40 +02:00
}
}
Message::Chunk(None) => {
2018-10-09 19:36:40 +02:00
if let Some(mut payload) = self.payload.take() {
payload.feed_eof();
} else {
error!("Internal server error: unexpected eof");
self.flags.insert(Flags::DISCONNECTED);
self.messages.push_back(DispatcherMessage::Error(
2018-10-09 19:36:40 +02:00
Response::InternalServerError().finish(),
));
self.error = Some(DispatchError::InternalError);
2018-11-06 04:32:03 +01:00
break;
2018-10-09 19:36:40 +02:00
}
}
2018-10-05 01:22:00 +02:00
}
2018-10-09 19:36:40 +02:00
}
Ok(Async::Ready(None)) => {
self.client_disconnected();
break;
}
Ok(Async::NotReady) => break,
Err(ParseError::Io(e)) => {
self.client_disconnected();
self.error = Some(DispatchError::Io(e));
break;
}
Err(e) => {
if let Some(mut payload) = self.payload.take() {
payload.set_error(PayloadError::EncodingCorrupted);
2018-10-07 18:48:53 +02:00
}
2018-10-05 01:22:00 +02:00
2018-10-09 19:36:40 +02:00
// Malformed requests should be responded with 400
self.messages.push_back(DispatcherMessage::Error(
Response::BadRequest().finish(),
));
2018-10-09 19:36:40 +02:00
self.flags.insert(Flags::DISCONNECTED);
self.error = Some(e.into());
break;
2018-10-05 01:22:00 +02:00
}
}
}
2018-10-05 08:39:11 +02:00
if self.ka_timer.is_some() && updated {
if let Some(expire) = self.config.keep_alive_expire() {
self.ka_expire = expire;
}
}
2018-10-05 01:22:00 +02:00
Ok(updated)
}
2018-10-05 08:39:11 +02:00
/// keep-alive timer
fn poll_keepalive(&mut self) -> Result<(), DispatchError<S::Error>> {
if let Some(ref mut timer) = self.ka_timer {
match timer.poll() {
Ok(Async::Ready(_)) => {
2018-10-07 19:09:48 +02:00
// if we get timer during shutdown, just drop connection
if self.flags.contains(Flags::SHUTDOWN) {
return Err(DispatchError::DisconnectTimeout);
} else if timer.deadline() >= self.ka_expire {
// check for any outstanding response processing
if self.state.is_empty() && self.flags.contains(Flags::FLUSHED) {
2018-10-07 19:09:48 +02:00
if self.flags.contains(Flags::STARTED) {
2018-10-05 08:39:11 +02:00
trace!("Keep-alive timeout, close connection");
self.flags.insert(Flags::SHUTDOWN);
// start shutdown timer
if let Some(deadline) =
self.config.client_disconnect_timer()
{
2018-11-08 18:30:53 +01:00
timer.reset(deadline);
let _ = timer.poll();
2018-10-05 08:39:11 +02:00
} else {
return Ok(());
}
2018-10-07 19:09:48 +02:00
} else {
// timeout on first request (slow request) return 408
trace!("Slow request timeout");
self.flags.insert(Flags::STARTED | Flags::DISCONNECTED);
2018-10-09 00:24:51 +02:00
self.state = State::SendResponse(Some((
Message::Item(Response::RequestTimeout().finish()),
2018-10-09 00:24:51 +02:00
Body::Empty,
)));
2018-10-05 08:39:11 +02:00
}
} else if let Some(deadline) = self.config.keep_alive_expire() {
2018-11-08 18:30:53 +01:00
timer.reset(deadline);
let _ = timer.poll();
2018-10-05 08:39:11 +02:00
}
} else {
2018-11-08 18:30:53 +01:00
timer.reset(self.ka_expire);
let _ = timer.poll();
2018-10-05 08:39:11 +02:00
}
}
Ok(Async::NotReady) => (),
Err(e) => {
error!("Timer error {:?}", e);
return Err(DispatchError::Unknown);
}
}
}
Ok(())
}
2018-10-05 01:22:00 +02:00
}
2018-10-05 05:02:10 +02:00
impl<T, S> Future for Dispatcher<T, S>
2018-10-05 01:22:00 +02:00
where
2018-10-05 05:02:10 +02:00
T: AsyncRead + AsyncWrite,
2018-10-05 20:04:59 +02:00
S: Service<Request = Request, Response = Response>,
2018-10-07 18:48:53 +02:00
S::Error: Debug,
2018-10-05 01:22:00 +02:00
{
type Item = H1ServiceResult<T>;
2018-10-05 05:02:10 +02:00
type Error = DispatchError<S::Error>;
2018-10-05 01:22:00 +02:00
#[inline]
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
2018-10-05 01:22:00 +02:00
if self.flags.contains(Flags::SHUTDOWN) {
2018-10-07 18:48:53 +02:00
self.poll_keepalive()?;
2018-10-05 01:22:00 +02:00
try_ready!(self.poll_flush());
let io = self.framed.take().unwrap().into_inner();
Ok(Async::Ready(H1ServiceResult::Shutdown(io)))
2018-10-07 18:48:53 +02:00
} else {
self.poll_keepalive()?;
self.poll_request()?;
self.poll_response()?;
2018-10-05 01:22:00 +02:00
self.poll_flush()?;
2018-10-07 18:48:53 +02:00
// keep-alive and stream errors
2018-10-05 01:22:00 +02:00
if self.state.is_empty() && self.flags.contains(Flags::FLUSHED) {
2018-10-07 18:48:53 +02:00
if let Some(err) = self.error.take() {
Err(err)
} else if self.flags.contains(Flags::DISCONNECTED) {
Ok(Async::Ready(H1ServiceResult::Disconnected))
}
// unhandled request (upgrade or connect)
else if self.unhandled.is_some() {
let req = self.unhandled.take().unwrap();
let framed = self.framed.take().unwrap();
Ok(Async::Ready(H1ServiceResult::Unhandled(req, framed)))
2018-10-05 01:22:00 +02:00
}
2018-10-07 18:48:53 +02:00
// disconnect if keep-alive is not enabled
else if self.flags.contains(Flags::STARTED) && !self
.flags
.intersects(Flags::KEEPALIVE | Flags::KEEPALIVE_ENABLED)
2018-10-05 01:22:00 +02:00
{
let io = self.framed.take().unwrap().into_inner();
Ok(Async::Ready(H1ServiceResult::Shutdown(io)))
2018-10-07 18:48:53 +02:00
} else {
Ok(Async::NotReady)
2018-10-05 01:22:00 +02:00
}
2018-10-07 18:48:53 +02:00
} else {
Ok(Async::NotReady)
2018-10-05 01:22:00 +02:00
}
}
}
}