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

326 lines
8.9 KiB
Rust
Raw Normal View History

2017-10-07 06:48:14 +02:00
use std;
use std::rc::Rc;
2017-10-29 14:05:31 +01:00
use std::cell::RefCell;
2017-10-07 06:48:14 +02:00
use std::collections::VecDeque;
2017-10-29 14:05:31 +01:00
use std::marker::PhantomData;
2017-11-30 23:42:20 +01:00
use futures::{Async, Future, Poll};
2017-10-21 02:16:17 +02:00
use futures::sync::oneshot::Sender;
2017-10-07 06:48:14 +02:00
2017-10-21 02:16:17 +02:00
use actix::{Actor, ActorState, ActorContext, AsyncContext,
Handler, Subscriber, ResponseType};
2017-10-07 06:48:14 +02:00
use actix::fut::ActorFuture;
2017-10-21 02:16:17 +02:00
use actix::dev::{AsyncContextApi, ActorAddressCell, ActorItemsCell, ActorWaitCell, SpawnHandle,
Envelope, ToEnvelope, RemoteEnvelope};
2017-10-07 06:48:14 +02:00
2017-11-30 23:42:20 +01:00
use body::{Body, Binary};
2017-11-29 19:31:24 +01:00
use error::Error;
use httprequest::HttpRequest;
2017-10-15 18:33:17 +02:00
use httpresponse::HttpResponse;
2017-12-02 00:45:15 +01:00
use pipeline::DrainFut;
2017-10-07 06:48:14 +02:00
2017-12-02 00:45:15 +01:00
pub(crate) trait IoContext: 'static {
fn disconnected(&mut self);
fn poll(&mut self) -> Poll<Option<Frame>, Error>;
}
2017-10-07 06:48:14 +02:00
2017-11-30 23:42:20 +01:00
#[derive(Debug)]
pub(crate) enum Frame {
2017-12-13 20:10:03 +01:00
Message(Box<HttpResponse>),
2017-11-30 23:42:20 +01:00
Payload(Option<Binary>),
Drain(Rc<RefCell<DrainFut>>),
}
2017-11-10 07:08:54 +01:00
/// Http actor execution context
2017-11-29 19:31:24 +01:00
pub struct HttpContext<A, S=()> where A: Actor<Context=HttpContext<A, S>>,
2017-10-07 06:48:14 +02:00
{
2017-11-29 19:31:24 +01:00
act: A,
2017-10-07 06:48:14 +02:00
state: ActorState,
2017-10-22 00:21:16 +02:00
modified: bool,
2017-10-09 19:44:11 +02:00
items: ActorItemsCell<A>,
2017-10-07 06:48:14 +02:00
address: ActorAddressCell<A>,
stream: VecDeque<Frame>,
2017-10-17 23:44:00 +02:00
wait: ActorWaitCell<A>,
2017-11-29 19:31:24 +01:00
request: HttpRequest<S>,
2017-11-30 23:42:20 +01:00
streaming: bool,
2017-10-26 01:25:26 +02:00
disconnected: bool,
2017-10-07 06:48:14 +02:00
}
2017-11-29 19:31:24 +01:00
impl<A, S> ActorContext for HttpContext<A, S> where A: Actor<Context=Self>
2017-10-07 06:48:14 +02:00
{
/// Stop actor execution
fn stop(&mut self) {
2017-12-02 00:45:15 +01:00
self.stream.push_back(Frame::Payload(None));
2017-10-30 22:49:20 +01:00
self.items.stop();
2017-10-07 06:48:14 +02:00
self.address.close();
if self.state == ActorState::Running {
self.state = ActorState::Stopping;
}
}
/// Terminate actor execution
fn terminate(&mut self) {
self.address.close();
2017-10-09 19:44:11 +02:00
self.items.close();
2017-10-07 06:48:14 +02:00
self.state = ActorState::Stopped;
}
/// Actor execution state
fn state(&self) -> ActorState {
self.state
}
}
2017-11-29 19:31:24 +01:00
impl<A, S> AsyncContext<A> for HttpContext<A, S> where A: Actor<Context=Self>
2017-10-07 06:48:14 +02:00
{
2017-10-09 19:44:11 +02:00
fn spawn<F>(&mut self, fut: F) -> SpawnHandle
2017-10-07 06:48:14 +02:00
where F: ActorFuture<Item=(), Error=(), Actor=A> + 'static
{
2017-10-22 00:21:16 +02:00
self.modified = true;
2017-10-09 19:44:11 +02:00
self.items.spawn(fut)
}
2017-10-12 04:20:05 +02:00
fn wait<F>(&mut self, fut: F)
where F: ActorFuture<Item=(), Error=(), Actor=A> + 'static
{
2017-10-22 00:21:16 +02:00
self.modified = true;
2017-10-17 23:44:00 +02:00
self.wait.add(fut);
2017-10-12 04:20:05 +02:00
}
2017-10-09 19:44:11 +02:00
fn cancel_future(&mut self, handle: SpawnHandle) -> bool {
2017-10-22 00:21:16 +02:00
self.modified = true;
2017-10-09 19:44:11 +02:00
self.items.cancel_future(handle)
2017-10-07 06:48:14 +02:00
}
2017-10-30 22:49:20 +01:00
fn cancel_future_on_stop(&mut self, handle: SpawnHandle) {
self.items.cancel_future_on_stop(handle)
}
2017-10-07 06:48:14 +02:00
}
2017-10-07 08:14:13 +02:00
#[doc(hidden)]
2017-11-29 19:31:24 +01:00
impl<A, S> AsyncContextApi<A> for HttpContext<A, S> where A: Actor<Context=Self> {
2017-10-07 06:48:14 +02:00
fn address_cell(&mut self) -> &mut ActorAddressCell<A> {
&mut self.address
}
}
2017-11-29 19:31:24 +01:00
impl<A, S> HttpContext<A, S> where A: Actor<Context=Self> {
2017-10-07 06:48:14 +02:00
2017-11-29 19:31:24 +01:00
pub fn new(req: HttpRequest<S>, actor: A) -> HttpContext<A, S>
2017-11-27 06:47:33 +01:00
{
2017-10-07 06:48:14 +02:00
HttpContext {
2017-11-29 19:31:24 +01:00
act: actor,
2017-10-07 06:48:14 +02:00
state: ActorState::Started,
2017-10-22 00:21:16 +02:00
modified: false,
2017-10-09 19:44:11 +02:00
items: ActorItemsCell::default(),
2017-10-07 09:22:09 +02:00
address: ActorAddressCell::default(),
2017-10-17 23:44:00 +02:00
wait: ActorWaitCell::default(),
2017-10-07 06:48:14 +02:00
stream: VecDeque::new(),
2017-11-29 19:31:24 +01:00
request: req,
2017-11-30 23:42:20 +01:00
streaming: false,
2017-10-26 01:25:26 +02:00
disconnected: false,
2017-10-07 06:48:14 +02:00
}
}
}
2017-11-29 19:31:24 +01:00
impl<A, S> HttpContext<A, S> where A: Actor<Context=Self> {
2017-10-07 06:48:14 +02:00
2017-11-27 06:47:33 +01:00
/// Shared application state
2017-11-29 19:31:24 +01:00
pub fn state(&self) -> &S {
self.request.state()
2017-11-27 06:47:33 +01:00
}
2017-11-29 19:31:24 +01:00
/// Incoming request
pub fn request(&mut self) -> &mut HttpRequest<S> {
&mut self.request
}
2017-11-30 23:42:20 +01:00
/// Send response to peer
pub fn start<R: Into<HttpResponse>>(&mut self, response: R) {
2017-11-30 23:42:20 +01:00
let resp = response.into();
match *resp.body() {
Body::StreamingContext | Body::UpgradeContext => self.streaming = true,
_ => (),
}
2017-12-13 20:10:03 +01:00
self.stream.push_back(Frame::Message(Box::new(resp)))
2017-10-07 06:48:14 +02:00
}
/// Write payload
2017-11-10 22:42:32 +01:00
pub fn write<B: Into<Binary>>(&mut self, data: B) {
2017-11-30 23:42:20 +01:00
if self.streaming {
if !self.disconnected {
self.stream.push_back(Frame::Payload(Some(data.into())))
}
} else {
warn!("Trying to write response body for non-streaming response");
}
2017-10-07 06:48:14 +02:00
}
2017-10-26 01:25:26 +02:00
2017-12-02 00:45:15 +01:00
/// Indicate end of streamimng payload. Also this method calls `Self::close`.
pub fn write_eof(&mut self) {
self.stop();
}
2017-10-29 14:05:31 +01:00
/// Returns drain future
pub fn drain(&mut self) -> Drain<A> {
2017-10-29 23:04:44 +01:00
let fut = Rc::new(RefCell::new(DrainFut::default()));
self.stream.push_back(Frame::Drain(Rc::clone(&fut)));
2017-10-29 14:05:31 +01:00
self.modified = true;
Drain{ a: PhantomData, inner: fut }
}
2017-10-26 01:25:26 +02:00
/// Check if connection still open
pub fn connected(&self) -> bool {
!self.disconnected
}
2017-10-07 06:48:14 +02:00
}
2017-11-29 19:31:24 +01:00
impl<A, S> HttpContext<A, S> where A: Actor<Context=Self> {
2017-10-21 02:16:17 +02:00
#[doc(hidden)]
2017-10-22 00:21:16 +02:00
pub fn subscriber<M>(&mut self) -> Box<Subscriber<M>>
where A: Handler<M>,
M: ResponseType + 'static,
2017-10-21 02:16:17 +02:00
{
Box::new(self.address.unsync_address())
}
#[doc(hidden)]
2017-10-22 00:21:16 +02:00
pub fn sync_subscriber<M>(&mut self) -> Box<Subscriber<M> + Send>
2017-10-21 02:16:17 +02:00
where A: Handler<M>,
2017-10-22 00:21:16 +02:00
M: ResponseType + Send + 'static,
M::Item: Send,
M::Error: Send,
2017-10-21 02:16:17 +02:00
{
Box::new(self.address.sync_address())
}
}
2017-11-30 23:42:20 +01:00
impl<A, S> IoContext for HttpContext<A, S> where A: Actor<Context=Self>, S: 'static {
fn disconnected(&mut self) {
self.items.stop();
self.disconnected = true;
if self.state == ActorState::Running {
self.state = ActorState::Stopping;
}
}
2017-10-07 06:48:14 +02:00
2017-11-16 07:06:28 +01:00
fn poll(&mut self) -> Poll<Option<Frame>, Error> {
2017-10-07 08:14:13 +02:00
let act: &mut A = unsafe {
2017-11-29 19:31:24 +01:00
std::mem::transmute(&mut self.act as &mut A)
2017-10-07 08:14:13 +02:00
};
2017-11-29 19:31:24 +01:00
let ctx: &mut HttpContext<A, S> = unsafe {
std::mem::transmute(self as &mut HttpContext<A, S>)
2017-10-07 06:48:14 +02:00
};
// update state
match self.state {
ActorState::Started => {
2017-10-07 08:14:13 +02:00
Actor::started(act, ctx);
2017-10-07 06:48:14 +02:00
self.state = ActorState::Running;
},
ActorState::Stopping => {
2017-10-07 08:14:13 +02:00
Actor::stopping(act, ctx);
2017-10-07 06:48:14 +02:00
}
_ => ()
}
let mut prep_stop = false;
loop {
2017-10-22 00:21:16 +02:00
self.modified = false;
2017-10-07 06:48:14 +02:00
2017-10-21 02:16:17 +02:00
// check wait futures
if self.wait.poll(act, ctx) {
2017-10-29 14:05:31 +01:00
// get frame
if let Some(frame) = self.stream.pop_front() {
return Ok(Async::Ready(Some(frame)))
}
2017-10-21 02:16:17 +02:00
return Ok(Async::NotReady)
}
2017-10-22 00:21:16 +02:00
// incoming messages
self.address.poll(act, ctx);
// spawned futures and streams
self.items.poll(act, ctx);
2017-10-07 06:48:14 +02:00
// are we done
2017-10-22 00:21:16 +02:00
if self.modified {
2017-10-07 06:48:14 +02:00
continue
}
// get frame
if let Some(frame) = self.stream.pop_front() {
return Ok(Async::Ready(Some(frame)))
}
// check state
match self.state {
ActorState::Stopped => {
self.state = ActorState::Stopped;
2017-10-07 08:14:13 +02:00
Actor::stopped(act, ctx);
2017-10-07 06:48:14 +02:00
return Ok(Async::Ready(None))
},
ActorState::Stopping => {
if prep_stop {
if self.address.connected() || !self.items.is_empty() {
self.state = ActorState::Running;
continue
} else {
self.state = ActorState::Stopped;
2017-10-07 08:14:13 +02:00
Actor::stopped(act, ctx);
2017-10-07 06:48:14 +02:00
return Ok(Async::Ready(None))
}
} else {
2017-10-07 08:14:13 +02:00
Actor::stopping(act, ctx);
2017-10-07 06:48:14 +02:00
prep_stop = true;
continue
}
},
ActorState::Running => {
if !self.address.connected() && self.items.is_empty() {
self.state = ActorState::Stopping;
2017-10-07 08:14:13 +02:00
Actor::stopping(act, ctx);
2017-10-07 06:48:14 +02:00
prep_stop = true;
continue
}
},
_ => (),
}
return Ok(Async::NotReady)
}
}
}
2017-10-21 02:16:17 +02:00
2017-11-29 19:31:24 +01:00
impl<A, S> ToEnvelope<A> for HttpContext<A, S>
where A: Actor<Context=HttpContext<A, S>>,
2017-10-21 02:16:17 +02:00
{
2017-10-25 05:24:14 +02:00
fn pack<M>(msg: M, tx: Option<Sender<Result<M::Item, M::Error>>>) -> Envelope<A>
where A: Handler<M>,
M: ResponseType + Send + 'static,
M::Item: Send,
M::Error: Send
2017-10-21 02:16:17 +02:00
{
RemoteEnvelope::new(msg, tx).into()
}
}
2017-10-29 14:05:31 +01:00
pub struct Drain<A> {
a: PhantomData<A>,
inner: Rc<RefCell<DrainFut>>
}
impl<A> ActorFuture for Drain<A>
where A: Actor
{
type Item = ();
type Error = ();
type Actor = A;
fn poll(&mut self, _: &mut A, _: &mut <Self::Actor as Actor>::Context) -> Poll<(), ()> {
self.inner.borrow_mut().poll()
}
}