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

530 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-11-17 06:09:33 +01:00
use std::mem;
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;
2018-11-17 06:09:33 +01:00
use futures::{Async, 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-11-18 05:21:28 +01:00
use body::{BodyLength, MessageBody};
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-11-18 05:21:28 +01:00
pub struct Dispatcher<T, S: Service, B: MessageBody>
2018-11-17 06:09:33 +01:00
where
S::Error: Debug,
{
2018-11-18 05:21:28 +01:00
inner: Option<InnerDispatcher<T, S, B>>,
2018-11-17 06:09:33 +01:00
}
2018-11-18 05:21:28 +01:00
struct InnerDispatcher<T, S: Service, B: MessageBody>
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,
2018-11-17 06:09:33 +01:00
framed: 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
2018-11-18 05:21:28 +01:00
state: State<S, B>,
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-11-18 05:21:28 +01:00
enum State<S: Service, B: MessageBody> {
2018-10-05 01:22:00 +02:00
None,
2018-10-07 09:04:38 +02:00
ServiceCall(S::Future),
2018-11-18 05:21:28 +01:00
SendPayload(B),
2018-10-05 01:22:00 +02:00
}
2018-11-18 05:21:28 +01:00
impl<S: Service, B: MessageBody> State<S, B> {
2018-10-05 01:22:00 +02:00
fn is_empty(&self) -> bool {
if let State::None = self {
true
} else {
false
}
}
}
2018-11-18 05:21:28 +01:00
impl<T, S, B> Dispatcher<T, S, B>
2018-10-05 01:22:00 +02:00
where
2018-10-05 05:02:10 +02:00
T: AsyncRead + AsyncWrite,
2018-11-18 05:21:28 +01:00
S: Service<Request = Request, Response = Response<B>>,
2018-10-07 18:48:53 +02:00
S::Error: Debug,
2018-11-18 05:21:28 +01:00
B: MessageBody,
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-11-17 06:09:33 +01:00
inner: Some(InnerDispatcher {
framed,
payload: None,
state: State::None,
error: None,
messages: VecDeque::new(),
unhandled: None,
service,
flags,
config,
ka_expire,
ka_timer,
}),
2018-10-05 01:22:00 +02:00
}
}
2018-11-17 06:09:33 +01:00
}
2018-10-05 01:22:00 +02:00
2018-11-18 05:21:28 +01:00
impl<T, S, B> InnerDispatcher<T, S, B>
2018-11-17 06:09:33 +01:00
where
T: AsyncRead + AsyncWrite,
2018-11-18 05:21:28 +01:00
S: Service<Request = Request, Response = Response<B>>,
2018-11-17 06:09:33 +01:00
S::Error: Debug,
2018-11-18 05:21:28 +01:00
B: MessageBody,
2018-11-17 06:09:33 +01:00
{
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) {
2018-11-17 06:09:33 +01:00
match self.framed.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-11-18 05:21:28 +01:00
fn send_response<B1: MessageBody>(
2018-11-17 06:09:33 +01:00
&mut self,
message: Response,
2018-11-18 05:21:28 +01:00
body: B1,
) -> Result<State<S, B1>, DispatchError<S::Error>> {
2018-11-17 06:09:33 +01:00
self.framed
.force_send(Message::Item(message))
.map_err(|err| {
if let Some(mut payload) = self.payload.take() {
payload.set_error(PayloadError::Incomplete(None));
}
DispatchError::Io(err)
})?;
self.flags
.set(Flags::KEEPALIVE, self.framed.get_codec().keepalive());
self.flags.remove(Flags::FLUSHED);
2018-11-18 05:21:28 +01:00
match body.length() {
BodyLength::None | BodyLength::Zero => Ok(State::None),
_ => Ok(State::SendPayload(body)),
2018-11-17 06:09:33 +01:00
}
}
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();
loop {
2018-11-17 06:09:33 +01:00
let state = match mem::replace(&mut self.state, State::None) {
State::None => match self.messages.pop_front() {
Some(DispatcherMessage::Item(req)) => {
Some(self.handle_request(req)?)
2018-10-30 00:39:46 +01:00
}
2018-11-17 06:09:33 +01:00
Some(DispatcherMessage::Error(res)) => {
2018-11-18 05:21:28 +01:00
self.send_response(res, ())?;
None
2018-11-17 06:09:33 +01:00
}
None => None,
2018-10-05 01:22:00 +02:00
},
2018-11-17 06:09:33 +01:00
State::ServiceCall(mut fut) => {
2018-10-09 00:24:51 +02:00
match fut.poll().map_err(DispatchError::Service)? {
Async::Ready(mut res) => {
2018-11-18 05:21:28 +01:00
let (mut res, body) = res.replace_body(());
self.framed
.get_codec_mut()
.prepare_te(res.head_mut(), &mut body.length());
2018-11-17 06:09:33 +01:00
Some(self.send_response(res, body)?)
2018-10-05 01:22:00 +02:00
}
2018-11-17 06:09:33 +01:00
Async::NotReady => {
self.state = State::ServiceCall(fut);
None
2018-10-07 07:36:57 +02:00
}
2018-10-05 01:22:00 +02:00
}
}
2018-11-17 06:09:33 +01:00
State::SendPayload(mut stream) => {
2018-11-14 19:52:40 +01:00
loop {
2018-11-17 06:09:33 +01:00
if !self.framed.is_write_buf_full() {
2018-11-18 05:21:28 +01:00
match stream
.poll_next()
.map_err(|_| DispatchError::Unknown)?
{
2018-11-14 19:52:40 +01:00
Async::Ready(Some(item)) => {
2018-10-09 00:24:51 +02:00
self.flags.remove(Flags::FLUSHED);
2018-11-17 06:09:33 +01:00
self.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);
2018-11-17 06:09:33 +01:00
self.framed.force_send(Message::Chunk(None))?;
}
Async::NotReady => {
self.state = State::SendPayload(stream);
return Ok(());
2018-10-09 00:24:51 +02:00
}
2018-11-14 19:52:40 +01:00
}
} else {
2018-11-17 06:09:33 +01:00
self.state = State::SendPayload(stream);
2018-11-14 19:52:40 +01:00
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.
2018-11-17 06:09:33 +01:00
// we may read more data and 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-11-18 05:21:28 +01:00
) -> Result<State<S, B>, 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)? {
2018-11-18 05:21:28 +01:00
Async::Ready(res) => {
let (mut res, body) = res.replace_body(());
self.framed
.get_codec_mut()
.prepare_te(res.head_mut(), &mut body.length());
2018-11-17 06:09:33 +01:00
self.send_response(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 {
2018-11-17 06:09:33 +01:00
match self.framed.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) => {
2018-11-17 06:09:33 +01:00
match self.framed.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>> {
2018-11-17 06:09:33 +01:00
if self.ka_timer.is_some() {
return Ok(());
}
match self.ka_timer.as_mut().unwrap().poll().map_err(|e| {
error!("Timer error {:?}", e);
DispatchError::Unknown
})? {
Async::Ready(_) => {
// if we get timeout during shutdown, drop connection
if self.flags.contains(Flags::SHUTDOWN) {
return Err(DispatchError::DisconnectTimeout);
} else if self.ka_timer.as_mut().unwrap().deadline() >= self.ka_expire {
// check for any outstanding response processing
if self.state.is_empty() && self.flags.contains(Flags::FLUSHED) {
if self.flags.contains(Flags::STARTED) {
trace!("Keep-alive timeout, close connection");
self.flags.insert(Flags::SHUTDOWN);
// start shutdown timer
if let Some(deadline) = self.config.client_disconnect_timer()
{
self.ka_timer.as_mut().map(|timer| {
2018-11-08 18:30:53 +01:00
timer.reset(deadline);
let _ = timer.poll();
2018-11-17 06:09:33 +01:00
});
2018-10-07 19:09:48 +02:00
} else {
2018-11-17 06:09:33 +01:00
return Ok(());
2018-10-05 08:39:11 +02:00
}
2018-11-17 06:09:33 +01:00
} else {
// timeout on first request (slow request) return 408
trace!("Slow request timeout");
self.flags.insert(Flags::STARTED | Flags::DISCONNECTED);
2018-11-18 05:21:28 +01:00
let _ = self
.send_response(Response::RequestTimeout().finish(), ());
self.state = State::None;
2018-11-17 06:09:33 +01:00
}
} else if let Some(deadline) = self.config.keep_alive_expire() {
self.ka_timer.as_mut().map(|timer| {
2018-11-08 18:30:53 +01:00
timer.reset(deadline);
let _ = timer.poll();
2018-11-17 06:09:33 +01:00
});
2018-10-05 08:39:11 +02:00
}
2018-11-17 06:09:33 +01:00
} else {
let expire = self.ka_expire;
self.ka_timer.as_mut().map(|timer| {
timer.reset(expire);
let _ = timer.poll();
});
2018-10-05 08:39:11 +02:00
}
}
2018-11-17 06:09:33 +01:00
Async::NotReady => (),
2018-10-05 08:39:11 +02:00
}
Ok(())
}
2018-10-05 01:22:00 +02:00
}
2018-11-18 05:21:28 +01:00
impl<T, S, B> Future for Dispatcher<T, S, B>
2018-10-05 01:22:00 +02:00
where
2018-10-05 05:02:10 +02:00
T: AsyncRead + AsyncWrite,
2018-11-18 05:21:28 +01:00
S: Service<Request = Request, Response = Response<B>>,
2018-10-07 18:48:53 +02:00
S::Error: Debug,
2018-11-18 05:21:28 +01:00
B: MessageBody,
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-11-17 06:09:33 +01:00
let shutdown = if let Some(ref mut inner) = self.inner {
if inner.flags.contains(Flags::SHUTDOWN) {
inner.poll_keepalive()?;
try_ready!(inner.poll_flush());
true
} else {
inner.poll_keepalive()?;
inner.poll_request()?;
inner.poll_response()?;
inner.poll_flush()?;
// keep-alive and stream errors
if inner.state.is_empty() && inner.flags.contains(Flags::FLUSHED) {
if let Some(err) = inner.error.take() {
return Err(err);
} else if inner.flags.contains(Flags::DISCONNECTED) {
return Ok(Async::Ready(H1ServiceResult::Disconnected));
}
// unhandled request (upgrade or connect)
else if inner.unhandled.is_some() {
false
}
// disconnect if keep-alive is not enabled
else if inner.flags.contains(Flags::STARTED) && !inner
.flags
.intersects(Flags::KEEPALIVE | Flags::KEEPALIVE_ENABLED)
{
true
} else {
return Ok(Async::NotReady);
}
2018-10-07 18:48:53 +02:00
} else {
2018-11-17 06:09:33 +01:00
return Ok(Async::NotReady);
2018-10-05 01:22:00 +02:00
}
}
2018-11-17 06:09:33 +01:00
} else {
unreachable!()
};
let mut inner = self.inner.take().unwrap();
if shutdown {
Ok(Async::Ready(H1ServiceResult::Shutdown(
inner.framed.into_inner(),
)))
} else {
let req = inner.unhandled.take().unwrap();
Ok(Async::Ready(H1ServiceResult::Unhandled(req, inner.framed)))
2018-10-05 01:22:00 +02:00
}
}
}