1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-11-28 01:52:57 +01:00
actix-web/src/pipeline.rs

428 lines
14 KiB
Rust
Raw Normal View History

2017-11-25 07:15:52 +01:00
use std::mem;
use std::rc::Rc;
use futures::{Async, Poll, Future};
use task::Task;
use error::Error;
use middlewares::{Middleware, Finished, Started, Response};
use h1writer::Writer;
use httprequest::HttpRequest;
use httpresponse::HttpResponse;
2017-11-29 04:49:17 +01:00
type Handler = Fn(HttpRequest, &mut Task);
pub(crate) type PipelineHandler<'a> = &'a Fn(HttpRequest, &mut Task);
2017-11-25 07:15:52 +01:00
pub struct Pipeline(PipelineState);
enum PipelineState {
None,
Starting(Start),
Handle(Box<Handle>),
Finishing(Box<Finish>),
Error(Box<(Task, HttpRequest)>),
Task(Box<(Task, HttpRequest)>),
}
impl Pipeline {
2017-11-27 05:32:12 +01:00
pub fn new(req: HttpRequest, mw: Rc<Vec<Box<Middleware>>>, handler: PipelineHandler) -> Pipeline
{
2017-11-25 07:15:52 +01:00
if mw.is_empty() {
2017-11-29 04:49:17 +01:00
let mut task = Task::default();
(handler)(req.clone(), &mut task);
2017-11-25 07:15:52 +01:00
Pipeline(PipelineState::Task(Box::new((task, req))))
} else {
2017-11-27 04:00:57 +01:00
match Start::init(mw, req, handler) {
2017-11-25 18:40:57 +01:00
Ok(StartResult::Ready(res)) =>
Pipeline(PipelineState::Handle(res)),
Ok(StartResult::NotReady(res)) =>
Pipeline(PipelineState::Starting(res)),
Err(err) =>
Pipeline(PipelineState::Error(
2017-11-29 04:49:17 +01:00
Box::new((Task::from_error(err), HttpRequest::default()))))
2017-11-25 07:15:52 +01:00
}
}
}
pub fn error<R: Into<HttpResponse>>(resp: R) -> Self {
2017-11-29 04:49:17 +01:00
Pipeline(PipelineState::Error(
Box::new((Task::from_response(resp), HttpRequest::default()))))
2017-11-25 07:15:52 +01:00
}
pub(crate) fn disconnected(&mut self) {
match self.0 {
PipelineState::Starting(ref mut st) =>
st.disconnected(),
PipelineState::Handle(ref mut st) =>
st.task.disconnected(),
2017-11-27 02:30:35 +01:00
PipelineState::Task(ref mut st) | PipelineState::Error(ref mut st) =>
2017-11-25 18:52:32 +01:00
st.0.disconnected(),
2017-11-25 07:15:52 +01:00
_ =>(),
}
}
2017-11-25 18:28:25 +01:00
pub(crate) fn poll_io<T: Writer>(&mut self, io: &mut T) -> Poll<bool, Error> {
2017-11-25 07:15:52 +01:00
loop {
2017-11-25 18:52:32 +01:00
match mem::replace(&mut self.0, PipelineState::None) {
2017-11-25 07:15:52 +01:00
PipelineState::Task(mut st) => {
let req:&mut HttpRequest = unsafe{mem::transmute(&mut st.1)};
let res = st.0.poll_io(io, req);
self.0 = PipelineState::Task(st);
return res
}
PipelineState::Starting(mut st) => {
match st.poll() {
2017-11-25 18:40:57 +01:00
Ok(Async::NotReady) => {
2017-11-25 07:15:52 +01:00
self.0 = PipelineState::Starting(st);
return Ok(Async::NotReady)
}
2017-11-25 18:40:57 +01:00
Ok(Async::Ready(h)) =>
2017-11-25 07:15:52 +01:00
self.0 = PipelineState::Handle(h),
2017-11-25 18:40:57 +01:00
Err(err) =>
self.0 = PipelineState::Error(
2017-11-29 04:49:17 +01:00
Box::new((Task::from_error(err), HttpRequest::default())))
2017-11-25 07:15:52 +01:00
}
}
PipelineState::Handle(mut st) => {
let res = st.poll_io(io);
if let Ok(Async::Ready(r)) = res {
if r {
self.0 = PipelineState::Finishing(st.finish());
return Ok(Async::Ready(false))
} else {
self.0 = PipelineState::Handle(st);
return res
}
} else {
self.0 = PipelineState::Handle(st);
return res
}
}
PipelineState::Error(mut st) => {
let req:&mut HttpRequest = unsafe{mem::transmute(&mut st.1)};
let res = st.0.poll_io(io, req);
self.0 = PipelineState::Error(st);
return res
}
PipelineState::Finishing(_) | PipelineState::None => unreachable!(),
}
}
}
pub(crate) fn poll(&mut self) -> Poll<(), Error> {
loop {
2017-11-25 18:52:32 +01:00
match mem::replace(&mut self.0, PipelineState::None) {
2017-11-25 07:15:52 +01:00
PipelineState::Handle(mut st) => {
let res = st.poll();
match res {
Ok(Async::NotReady) => {
self.0 = PipelineState::Handle(st);
return Ok(Async::NotReady)
}
Ok(Async::Ready(())) | Err(_) => {
self.0 = PipelineState::Finishing(st.finish());
}
}
}
PipelineState::Finishing(mut st) => {
let res = st.poll();
self.0 = PipelineState::Finishing(st);
return Ok(res)
}
PipelineState::Error(mut st) => {
let res = st.0.poll();
self.0 = PipelineState::Error(st);
return res
}
PipelineState::Task(mut st) => {
let res = st.0.poll();
self.0 = PipelineState::Task(st);
return res
}
_ => {
return Ok(Async::Ready(()))
}
}
}
}
}
2017-11-27 06:47:33 +01:00
type Fut = Box<Future<Item=Option<HttpResponse>, Error=Error>>;
2017-11-25 07:15:52 +01:00
/// Middlewares start executor
struct Start {
idx: usize,
hnd: *mut Handler,
disconnected: bool,
2017-11-27 06:47:33 +01:00
req: HttpRequest,
2017-11-25 07:15:52 +01:00
fut: Option<Fut>,
middlewares: Rc<Vec<Box<Middleware>>>,
}
enum StartResult {
Ready(Box<Handle>),
NotReady(Start),
}
impl Start {
fn init(mw: Rc<Vec<Box<Middleware>>>,
2017-11-27 04:00:57 +01:00
req: HttpRequest, handler: PipelineHandler) -> Result<StartResult, Error> {
2017-11-25 07:15:52 +01:00
Start {
idx: 0,
fut: None,
2017-11-27 06:47:33 +01:00
req: req,
2017-11-25 07:15:52 +01:00
disconnected: false,
hnd: handler as *const _ as *mut _,
middlewares: mw,
2017-11-27 06:47:33 +01:00
}.start()
2017-11-25 07:15:52 +01:00
}
fn disconnected(&mut self) {
self.disconnected = true;
}
fn prepare(&self, mut task: Task) -> Task {
if self.disconnected {
task.disconnected()
}
2017-11-25 21:05:27 +01:00
task.set_middlewares(MiddlewaresResponse::new(self.idx-1, Rc::clone(&self.middlewares)));
2017-11-25 07:15:52 +01:00
task
}
2017-11-27 06:47:33 +01:00
fn start(mut self) -> Result<StartResult, Error> {
2017-11-25 21:05:27 +01:00
let len = self.middlewares.len();
2017-11-25 07:15:52 +01:00
loop {
2017-11-25 21:05:27 +01:00
if self.idx == len {
2017-11-29 04:49:17 +01:00
let mut task = Task::default();
(unsafe{&*self.hnd})(self.req.clone(), &mut task);
2017-11-25 18:40:57 +01:00
return Ok(StartResult::Ready(
2017-11-27 06:47:33 +01:00
Box::new(Handle::new(self.idx-1, self.req.clone(),
self.prepare(task), self.middlewares))))
2017-11-25 07:15:52 +01:00
} else {
2017-11-27 06:47:33 +01:00
match self.middlewares[self.idx].start(&mut self.req) {
Started::Done =>
self.idx += 1,
Started::Response(resp) =>
2017-11-25 18:40:57 +01:00
return Ok(StartResult::Ready(
2017-11-25 07:15:52 +01:00
Box::new(Handle::new(
2017-11-27 06:47:33 +01:00
self.idx, self.req.clone(),
2017-11-29 04:49:17 +01:00
self.prepare(Task::from_response(resp)), self.middlewares)))),
2017-11-27 06:47:33 +01:00
Started::Future(mut fut) =>
2017-11-25 07:15:52 +01:00
match fut.poll() {
Ok(Async::NotReady) => {
self.fut = Some(fut);
2017-11-25 18:40:57 +01:00
return Ok(StartResult::NotReady(self))
2017-11-25 07:15:52 +01:00
}
2017-11-27 06:47:33 +01:00
Ok(Async::Ready(resp)) => {
2017-11-25 07:15:52 +01:00
if let Some(resp) = resp {
2017-11-25 18:40:57 +01:00
return Ok(StartResult::Ready(
2017-11-25 07:15:52 +01:00
Box::new(Handle::new(
2017-11-27 06:47:33 +01:00
self.idx, self.req.clone(),
2017-11-29 04:49:17 +01:00
self.prepare(Task::from_response(resp)),
self.middlewares))))
2017-11-25 07:15:52 +01:00
}
2017-11-25 21:05:27 +01:00
self.idx += 1;
2017-11-25 07:15:52 +01:00
}
2017-11-25 18:40:57 +01:00
Err(err) => return Err(err)
2017-11-27 06:47:33 +01:00
},
2017-11-25 19:24:45 +01:00
Started::Err(err) => return Err(err),
2017-11-25 07:15:52 +01:00
}
}
}
}
2017-11-25 18:40:57 +01:00
fn poll(&mut self) -> Poll<Box<Handle>, Error> {
2017-11-25 21:05:27 +01:00
let len = self.middlewares.len();
2017-11-25 07:15:52 +01:00
'outer: loop {
match self.fut.as_mut().unwrap().poll() {
2017-11-25 18:40:57 +01:00
Ok(Async::NotReady) => return Ok(Async::NotReady),
2017-11-27 06:47:33 +01:00
Ok(Async::Ready(resp)) => {
2017-11-25 07:15:52 +01:00
self.idx += 1;
if let Some(resp) = resp {
2017-11-25 18:40:57 +01:00
return Ok(Async::Ready(Box::new(Handle::new(
2017-11-27 06:47:33 +01:00
self.idx-1, self.req.clone(),
2017-11-29 04:49:17 +01:00
self.prepare(Task::from_response(resp)),
Rc::clone(&self.middlewares)))))
2017-11-25 07:15:52 +01:00
}
2017-11-25 21:05:27 +01:00
if self.idx == len {
2017-11-29 04:49:17 +01:00
let mut task = Task::default();
(unsafe{&*self.hnd})(self.req.clone(), &mut task);
2017-11-25 18:40:57 +01:00
return Ok(Async::Ready(Box::new(Handle::new(
2017-11-27 06:47:33 +01:00
self.idx-1, self.req.clone(),
self.prepare(task), Rc::clone(&self.middlewares)))))
2017-11-25 07:15:52 +01:00
} else {
loop {
2017-11-27 06:47:33 +01:00
match self.middlewares[self.idx].start(&mut self.req) {
Started::Done =>
self.idx += 1,
Started::Response(resp) => {
2017-11-25 21:05:27 +01:00
self.idx += 1;
2017-11-25 18:40:57 +01:00
return Ok(Async::Ready(Box::new(Handle::new(
2017-11-27 06:47:33 +01:00
self.idx-1, self.req.clone(),
2017-11-29 04:49:17 +01:00
self.prepare(Task::from_response(resp)),
2017-11-25 18:40:57 +01:00
Rc::clone(&self.middlewares)))))
2017-11-25 07:15:52 +01:00
},
2017-11-25 19:52:43 +01:00
Started::Future(fut) => {
2017-11-25 07:15:52 +01:00
self.fut = Some(fut);
continue 'outer
},
2017-11-25 19:24:45 +01:00
Started::Err(err) => return Err(err),
2017-11-25 07:15:52 +01:00
}
}
}
}
2017-11-25 18:40:57 +01:00
Err(err) => return Err(err)
2017-11-25 07:15:52 +01:00
}
}
}
}
2017-11-25 21:05:27 +01:00
struct Handle {
idx: usize,
req: HttpRequest,
task: Task,
middlewares: Rc<Vec<Box<Middleware>>>,
}
impl Handle {
fn new(idx: usize, req: HttpRequest, task: Task, mw: Rc<Vec<Box<Middleware>>>) -> Handle {
Handle { idx: idx, req: req, task:task, middlewares: mw }
}
fn poll_io<T: Writer>(&mut self, io: &mut T) -> Poll<bool, Error> {
self.task.poll_io(io, &mut self.req)
}
fn poll(&mut self) -> Poll<(), Error> {
self.task.poll()
}
fn finish(mut self) -> Box<Finish> {
Box::new(Finish {
idx: self.idx,
req: self.req,
fut: None,
resp: self.task.response(),
middlewares: self.middlewares
})
}
}
/// Middlewares start executor
struct Finish {
idx: usize,
req: HttpRequest,
resp: HttpResponse,
fut: Option<Box<Future<Item=(), Error=Error>>>,
middlewares: Rc<Vec<Box<Middleware>>>,
}
impl Finish {
pub fn poll(&mut self) -> Async<()> {
loop {
// poll latest fut
if let Some(ref mut fut) = self.fut {
match fut.poll() {
Ok(Async::NotReady) => return Async::NotReady,
Ok(Async::Ready(())) => self.idx -= 1,
Err(err) => {
error!("Middleware finish error: {}", err);
self.idx -= 1;
}
}
}
self.fut = None;
match self.middlewares[self.idx].finish(&mut self.req, &self.resp) {
Finished::Done => {
if self.idx == 0 {
return Async::Ready(())
} else {
self.idx -= 1
}
}
Finished::Future(fut) => {
self.fut = Some(fut);
},
}
}
}
}
2017-11-25 07:15:52 +01:00
/// Middlewares response executor
pub(crate) struct MiddlewaresResponse {
idx: usize,
2017-11-25 18:28:25 +01:00
fut: Option<Box<Future<Item=HttpResponse, Error=Error>>>,
2017-11-25 07:15:52 +01:00
middlewares: Rc<Vec<Box<Middleware>>>,
}
impl MiddlewaresResponse {
2017-11-25 21:05:27 +01:00
fn new(idx: usize, mw: Rc<Vec<Box<Middleware>>>) -> MiddlewaresResponse {
2017-11-25 07:15:52 +01:00
MiddlewaresResponse {
2017-11-25 21:05:27 +01:00
idx: idx,
2017-11-25 07:15:52 +01:00
fut: None,
middlewares: mw }
}
pub fn response(&mut self, req: &mut HttpRequest, mut resp: HttpResponse)
2017-11-25 19:24:45 +01:00
-> Result<Option<HttpResponse>, Error>
2017-11-25 07:15:52 +01:00
{
loop {
resp = match self.middlewares[self.idx].response(req, resp) {
2017-11-25 19:24:45 +01:00
Response::Err(err) =>
return Err(err),
Response::Done(r) => {
2017-11-25 07:15:52 +01:00
if self.idx == 0 {
2017-11-25 19:24:45 +01:00
return Ok(Some(r))
2017-11-25 07:15:52 +01:00
} else {
self.idx -= 1;
r
}
},
Response::Future(fut) => {
self.fut = Some(fut);
2017-11-25 19:24:45 +01:00
return Ok(None)
2017-11-25 07:15:52 +01:00
},
};
}
}
2017-11-30 23:42:20 +01:00
pub fn poll(&mut self, req: &mut HttpRequest) -> Poll<HttpResponse, Error> {
2017-11-25 07:15:52 +01:00
loop {
// poll latest fut
let mut resp = match self.fut.as_mut().unwrap().poll() {
2017-11-25 18:28:25 +01:00
Ok(Async::NotReady) =>
return Ok(Async::NotReady),
Ok(Async::Ready(resp)) => {
2017-11-25 21:05:27 +01:00
self.idx -= 1;
2017-11-25 07:15:52 +01:00
resp
}
2017-11-25 18:28:25 +01:00
Err(err) => return Err(err)
2017-11-25 07:15:52 +01:00
};
loop {
if self.idx == 0 {
2017-11-30 23:42:20 +01:00
return Ok(Async::Ready(resp))
2017-11-25 07:15:52 +01:00
} else {
match self.middlewares[self.idx].response(req, resp) {
2017-11-25 19:24:45 +01:00
Response::Err(err) =>
return Err(err),
Response::Done(r) => {
2017-11-25 07:15:52 +01:00
self.idx -= 1;
resp = r
},
Response::Future(fut) => {
self.fut = Some(fut);
break
},
}
}
}
}
}
}