1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-25 08:22:43 +01:00
actix-extras/src/h1/dispatcher.rs

479 lines
17 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
use body::Body;
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, InMessage, OutMessage};
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,
2018-10-05 05:02:10 +02:00
framed: Framed<T, Codec>,
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>,
2018-10-07 06:07:32 +02:00
messages: VecDeque<Message>,
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
}
2018-10-07 06:07:32 +02:00
enum Message {
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),
2018-10-05 01:22:00 +02:00
SendResponse(Option<OutMessage>),
SendResponseWithPayload(Option<(OutMessage, Body)>),
Payload(Body),
}
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(
stream: T, config: ServiceConfig, timeout: Option<Delay>, service: S,
) -> 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-05 19:03:10 +02:00
let framed = Framed::new(stream, Codec::new(keepalive));
2018-10-05 01:22:00 +02:00
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(),
service,
flags,
framed,
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);
}
}
/// 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-10-05 01:22:00 +02:00
match self.framed.poll_complete() {
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 {
State::None => loop {
break if let Some(msg) = self.messages.pop_front() {
2018-10-07 06:07:32 +02:00
match msg {
2018-10-07 09:04:38 +02:00
Message::Item(req) => Some(self.handle_request(req)?),
2018-10-07 07:36:57 +02:00
Message::Error(res) => Some(State::SendResponse(Some(
2018-10-07 06:07:32 +02:00
OutMessage::Response(res),
2018-10-07 07:36:57 +02:00
))),
2018-10-05 01:22:00 +02:00
}
} else {
None
};
},
2018-10-05 06:14:18 +02:00
State::Payload(ref mut _body) => unimplemented!(),
2018-10-07 09:04:38 +02:00
State::ServiceCall(ref mut fut) => match fut
.poll()
.map_err(DispatchError::Service)?
{
Async::Ready(mut res) => {
2018-10-07 07:36:57 +02:00
self.framed.get_codec_mut().prepare_te(&mut res);
2018-10-07 09:04:38 +02:00
let body = res.replace_body(Body::Empty);
if body.is_empty() {
2018-10-07 07:36:57 +02:00
Some(State::SendResponse(Some(OutMessage::Response(res))))
2018-10-07 09:04:38 +02:00
} else {
Some(State::SendResponseWithPayload(Some((
OutMessage::Response(res),
body,
))))
2018-10-05 01:22:00 +02:00
}
2018-10-07 07:36:57 +02:00
}
2018-10-07 09:04:38 +02:00
Async::NotReady => None,
2018-10-07 07:36:57 +02:00
},
2018-10-05 01:22:00 +02:00
State::SendResponse(ref mut item) => {
let msg = item.take().expect("SendResponse is empty");
match self.framed.start_send(msg) {
Ok(AsyncSink::Ready) => {
2018-10-05 19:03:10 +02:00
self.flags.set(
Flags::KEEPALIVE,
self.framed.get_codec().keepalive(),
);
2018-10-05 01:22:00 +02:00
self.flags.remove(Flags::FLUSHED);
2018-10-07 07:36:57 +02:00
Some(State::None)
2018-10-05 01:22:00 +02:00
}
Ok(AsyncSink::NotReady(msg)) => {
*item = Some(msg);
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);
}
return Err(DispatchError::Io(err));
}
2018-10-05 01:22:00 +02:00
}
}
State::SendResponseWithPayload(ref mut item) => {
2018-10-07 06:07:32 +02:00
let (msg, body) =
item.take().expect("SendResponseWithPayload is empty");
2018-10-05 01:22:00 +02:00
match self.framed.start_send(msg) {
Ok(AsyncSink::Ready) => {
2018-10-05 19:03:10 +02:00
self.flags.set(
Flags::KEEPALIVE,
self.framed.get_codec().keepalive(),
);
2018-10-05 01:22:00 +02:00
self.flags.remove(Flags::FLUSHED);
2018-10-07 07:36:57 +02:00
Some(State::Payload(body))
2018-10-05 01:22:00 +02:00
}
Ok(AsyncSink::NotReady(msg)) => {
*item = Some((msg, body));
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);
}
return Err(DispatchError::Io(err));
}
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(
&mut self, req: Request,
) -> 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) => {
2018-10-07 07:36:57 +02:00
self.framed.get_codec_mut().prepare_te(&mut res);
2018-10-07 09:04:38 +02:00
let body = res.replace_body(Body::Empty);
if body.is_empty() {
Ok(State::SendResponse(Some(OutMessage::Response(res))))
2018-10-07 07:36:57 +02:00
} else {
2018-10-07 09:04:38 +02:00
Ok(State::SendResponseWithPayload(Some((
OutMessage::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-05 05:02:10 +02:00
fn one_message(&mut self, msg: InMessage) -> Result<(), DispatchError<S::Error>> {
2018-10-05 01:22:00 +02:00
self.flags.insert(Flags::STARTED);
match msg {
2018-10-05 05:02:10 +02:00
InMessage::Message(msg) => {
2018-10-05 01:22:00 +02:00
// handle request early
if self.state.is_empty() {
2018-10-07 09:04:38 +02:00
self.state = self.handle_request(msg)?;
2018-10-05 01:22:00 +02:00
} else {
2018-10-07 06:07:32 +02:00
self.messages.push_back(Message::Item(msg));
2018-10-05 01:22:00 +02:00
}
}
2018-10-05 05:02:10 +02:00
InMessage::MessageWithPayload(msg) => {
2018-10-05 01:22:00 +02:00
// payload
let (ps, pl) = Payload::new(false);
*msg.inner.payload.borrow_mut() = Some(pl);
2018-10-05 16:02:09 +02:00
self.payload = Some(ps);
2018-10-05 01:22:00 +02:00
2018-10-07 06:07:32 +02:00
self.messages.push_back(Message::Item(msg));
2018-10-05 01:22:00 +02:00
}
2018-10-05 05:02:10 +02:00
InMessage::Chunk(chunk) => {
2018-10-05 01:22:00 +02:00
if let Some(ref mut payload) = self.payload {
payload.feed_data(chunk);
} else {
error!("Internal server error: unexpected payload chunk");
2018-10-07 18:48:53 +02:00
self.flags.insert(Flags::DISCONNECTED);
2018-10-07 06:07:32 +02:00
self.messages.push_back(Message::Error(
Response::InternalServerError().finish(),
));
2018-10-05 05:02:10 +02:00
self.error = Some(DispatchError::InternalError);
2018-10-05 01:22:00 +02:00
}
}
2018-10-05 05:02:10 +02:00
InMessage::Eof => {
2018-10-05 01:22:00 +02:00
if let Some(mut payload) = self.payload.take() {
payload.feed_eof();
} else {
error!("Internal server error: unexpected eof");
2018-10-07 18:48:53 +02:00
self.flags.insert(Flags::DISCONNECTED);
2018-10-07 06:07:32 +02:00
self.messages.push_back(Message::Error(
Response::InternalServerError().finish(),
));
2018-10-05 05:02:10 +02:00
self.error = Some(DispatchError::InternalError);
2018-10-05 01:22:00 +02:00
}
}
}
Ok(())
}
2018-10-07 18:48:53 +02:00
pub(self) fn poll_request(&mut self) -> Result<bool, DispatchError<S::Error>> {
2018-10-05 01:22:00 +02:00
let mut updated = false;
if self.messages.len() < MAX_PIPELINED_MESSAGES {
'outer: loop {
match self.framed.poll() {
Ok(Async::Ready(Some(msg))) => {
updated = true;
self.one_message(msg)?;
}
Ok(Async::Ready(None)) => {
2018-10-07 18:48:53 +02:00
self.client_disconnected();
2018-10-05 01:22:00 +02:00
break;
}
Ok(Async::NotReady) => break,
2018-10-07 18:48:53 +02:00
Err(ParseError::Io(e)) => {
self.client_disconnected();
self.error = Some(DispatchError::Io(e));
break;
}
2018-10-05 01:22:00 +02:00
Err(e) => {
if let Some(mut payload) = self.payload.take() {
2018-10-07 18:48:53 +02:00
payload.set_error(PayloadError::EncodingCorrupted);
2018-10-05 01:22:00 +02:00
}
// Malformed requests should be responded with 400
2018-10-07 06:07:32 +02:00
self.messages
.push_back(Message::Error(Response::BadRequest().finish()));
2018-10-07 18:48:53 +02:00
self.flags.insert(Flags::DISCONNECTED);
self.error = Some(e.into());
2018-10-05 01:22:00 +02:00
break;
}
}
}
}
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() {
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()
{
timer.reset(deadline)
} 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);
self.state =
State::SendResponse(Some(OutMessage::Response(
Response::RequestTimeout().finish(),
)));
2018-10-05 08:39:11 +02:00
}
} else if let Some(deadline) = self.config.keep_alive_expire() {
timer.reset(deadline)
}
} else {
timer.reset(self.ka_expire)
}
}
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 = ();
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::Error> {
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());
2018-10-07 18:48:53 +02:00
Ok(AsyncWrite::shutdown(self.framed.get_mut())?)
} 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(()))
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
{
self.flags.insert(Flags::SHUTDOWN);
2018-10-07 18:48:53 +02:00
self.poll()
} 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
}
}
}
}