1
0
mirror of https://github.com/fafhrd91/actix-net synced 2024-12-19 03:03:11 +01:00
actix-net/actix-ioframe/src/dispatcher.rs

328 lines
11 KiB
Rust
Raw Normal View History

2019-06-26 11:19:40 +02:00
//! Framed dispatcher service and related utilities
use std::collections::VecDeque;
use std::mem;
2019-07-02 08:10:05 +02:00
use std::rc::Rc;
2019-06-26 11:19:40 +02:00
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
use actix_service::{IntoService, Service};
use futures::task::AtomicTask;
use futures::unsync::{mpsc, oneshot};
use futures::{Async, Future, Poll, Sink as FutureSink, Stream};
use log::debug;
use crate::cell::Cell;
use crate::error::ServiceError;
use crate::item::Item;
use crate::sink::Sink;
2019-07-01 07:20:24 +02:00
use crate::state::State;
2019-06-26 11:19:40 +02:00
type Request<S, U> = Item<S, U>;
type Response<U> = <U as Encoder>::Item;
pub(crate) enum FramedMessage<T> {
Message(T),
Close,
WaitClose(oneshot::Sender<()>),
}
/// FramedTransport - is a future that reads frames from Framed object
/// and pass then to the service.
pub(crate) struct FramedDispatcher<St, S, T, U>
where
S: Service<Request = Request<St, U>, Response = Option<Response<U>>>,
S::Error: 'static,
S::Future: 'static,
T: AsyncRead + AsyncWrite,
U: Encoder + Decoder,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: std::fmt::Debug,
{
service: S,
sink: Sink<<U as Encoder>::Item>,
2019-07-01 07:20:24 +02:00
state: State<St>,
dispatch_state: FramedState<S, U>,
2019-06-26 11:19:40 +02:00
framed: Framed<T, U>,
rx: Option<mpsc::UnboundedReceiver<FramedMessage<<U as Encoder>::Item>>>,
inner: Cell<FramedDispatcherInner<<U as Encoder>::Item, S::Error>>,
disconnect: Option<Rc<dyn Fn(&mut St, bool)>>,
2019-06-26 11:19:40 +02:00
}
impl<St, S, T, U> FramedDispatcher<St, S, T, U>
where
S: Service<Request = Request<St, U>, Response = Option<Response<U>>>,
S::Error: 'static,
S::Future: 'static,
T: AsyncRead + AsyncWrite,
U: Decoder + Encoder,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: std::fmt::Debug,
{
pub(crate) fn new<F: IntoService<S>>(
framed: Framed<T, U>,
2019-07-01 07:20:24 +02:00
state: State<St>,
2019-06-26 11:19:40 +02:00
service: F,
rx: mpsc::UnboundedReceiver<FramedMessage<<U as Encoder>::Item>>,
sink: Sink<<U as Encoder>::Item>,
disconnect: Option<Rc<dyn Fn(&mut St, bool)>>,
2019-06-26 11:19:40 +02:00
) -> Self {
FramedDispatcher {
framed,
state,
sink,
2019-07-02 08:10:05 +02:00
disconnect,
2019-06-26 11:19:40 +02:00
rx: Some(rx),
service: service.into_service(),
2019-07-01 07:20:24 +02:00
dispatch_state: FramedState::Processing,
2019-06-26 11:19:40 +02:00
inner: Cell::new(FramedDispatcherInner {
buf: VecDeque::new(),
task: AtomicTask::new(),
}),
}
}
}
2019-07-01 07:20:24 +02:00
enum FramedState<S: Service, U: Encoder + Decoder> {
2019-06-26 11:19:40 +02:00
Processing,
Error(ServiceError<S::Error, U>),
FramedError(ServiceError<S::Error, U>),
FlushAndStop(Vec<oneshot::Sender<()>>),
Stopping,
}
2019-07-01 07:20:24 +02:00
impl<S: Service, U: Encoder + Decoder> FramedState<S, U> {
2019-06-26 11:19:40 +02:00
fn stop(&mut self, tx: Option<oneshot::Sender<()>>) {
match self {
2019-07-01 07:20:24 +02:00
FramedState::FlushAndStop(ref mut vec) => {
2019-06-26 11:19:40 +02:00
if let Some(tx) = tx {
vec.push(tx)
}
}
2019-07-01 07:20:24 +02:00
FramedState::Processing => {
*self = FramedState::FlushAndStop(if let Some(tx) = tx {
2019-06-26 11:19:40 +02:00
vec![tx]
} else {
Vec::new()
})
}
2019-07-01 07:20:24 +02:00
FramedState::Error(_) | FramedState::FramedError(_) | FramedState::Stopping => {
2019-06-26 11:19:40 +02:00
if let Some(tx) = tx {
let _ = tx.send(());
}
}
}
}
}
struct FramedDispatcherInner<I, E> {
buf: VecDeque<Result<I, E>>,
task: AtomicTask,
}
impl<St, S, T, U> FramedDispatcher<St, S, T, U>
where
S: Service<Request = Request<St, U>, Response = Option<Response<U>>>,
S::Error: 'static,
S::Future: 'static,
T: AsyncRead + AsyncWrite,
U: Decoder + Encoder,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: std::fmt::Debug,
{
2019-07-02 08:10:05 +02:00
fn disconnect(&mut self, error: bool) {
if let Some(ref disconnect) = self.disconnect {
(&*disconnect)(&mut *self.state.get_mut(), error);
}
}
2019-06-26 11:19:40 +02:00
fn poll_read(&mut self) -> bool {
loop {
match self.service.poll_ready() {
Ok(Async::Ready(_)) => {
let item = match self.framed.poll() {
Ok(Async::Ready(Some(el))) => el,
Err(err) => {
self.dispatch_state =
2019-07-01 07:20:24 +02:00
FramedState::FramedError(ServiceError::Decoder(err));
2019-06-26 11:19:40 +02:00
return true;
}
Ok(Async::NotReady) => return false,
Ok(Async::Ready(None)) => {
2019-10-08 10:46:22 +02:00
log::trace!("Client disconnected");
2019-07-01 07:20:24 +02:00
self.dispatch_state = FramedState::Stopping;
2019-06-26 11:19:40 +02:00
return true;
}
};
let mut cell = self.inner.clone();
tokio_current_thread::spawn(
self.service
.call(Item::new(self.state.clone(), self.sink.clone(), item))
.then(move |item| {
let item = match item {
Ok(Some(item)) => Ok(item),
Ok(None) => return Ok(()),
Err(err) => Err(err),
};
2019-07-17 07:16:38 +02:00
unsafe {
let inner = cell.get_mut();
inner.buf.push_back(item);
inner.task.notify();
}
2019-06-26 11:19:40 +02:00
Ok(())
}),
);
}
Ok(Async::NotReady) => return false,
Err(err) => {
2019-07-01 07:20:24 +02:00
self.dispatch_state = FramedState::Error(ServiceError::Service(err));
2019-06-26 11:19:40 +02:00
return true;
}
}
}
}
/// write to framed object
fn poll_write(&mut self) -> bool {
2019-07-17 07:16:38 +02:00
let inner = unsafe { self.inner.get_mut() };
2019-06-26 11:19:40 +02:00
let mut rx_done = self.rx.is_none();
let mut buf_empty = inner.buf.is_empty();
loop {
while !self.framed.is_write_buf_full() {
if !buf_empty {
match inner.buf.pop_front().unwrap() {
Ok(msg) => {
if let Err(err) = self.framed.force_send(msg) {
self.dispatch_state =
2019-07-01 07:20:24 +02:00
FramedState::FramedError(ServiceError::Encoder(err));
2019-06-26 11:19:40 +02:00
return true;
}
buf_empty = inner.buf.is_empty();
}
Err(err) => {
2019-07-01 07:20:24 +02:00
self.dispatch_state =
FramedState::Error(ServiceError::Service(err));
2019-06-26 11:19:40 +02:00
return true;
}
}
}
if !rx_done && self.rx.is_some() {
match self.rx.as_mut().unwrap().poll() {
Ok(Async::Ready(Some(FramedMessage::Message(msg)))) => {
if let Err(err) = self.framed.force_send(msg) {
self.dispatch_state =
2019-07-01 07:20:24 +02:00
FramedState::FramedError(ServiceError::Encoder(err));
2019-06-26 11:19:40 +02:00
return true;
}
}
Ok(Async::Ready(Some(FramedMessage::Close))) => {
self.dispatch_state.stop(None);
return true;
}
Ok(Async::Ready(Some(FramedMessage::WaitClose(tx)))) => {
self.dispatch_state.stop(Some(tx));
return true;
}
Ok(Async::Ready(None)) => {
rx_done = true;
let _ = self.rx.take();
}
Ok(Async::NotReady) => rx_done = true,
Err(_e) => {
rx_done = true;
let _ = self.rx.take();
}
}
}
if rx_done && buf_empty {
break;
}
}
if !self.framed.is_write_buf_empty() {
match self.framed.poll_complete() {
Ok(Async::NotReady) => break,
Err(err) => {
debug!("Error sending data: {:?}", err);
2019-07-01 07:20:24 +02:00
self.dispatch_state =
FramedState::FramedError(ServiceError::Encoder(err));
2019-06-26 11:19:40 +02:00
return true;
}
Ok(Async::Ready(_)) => (),
}
} else {
break;
}
}
false
}
}
impl<St, S, T, U> Future for FramedDispatcher<St, S, T, U>
where
S: Service<Request = Request<St, U>, Response = Option<Response<U>>>,
S::Error: 'static,
S::Future: 'static,
T: AsyncRead + AsyncWrite,
U: Decoder + Encoder,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: std::fmt::Debug,
{
type Item = ();
type Error = ServiceError<S::Error, U>;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
2019-10-14 13:55:52 +02:00
unsafe { self.inner.get_ref().task.register() };
2019-07-01 07:20:24 +02:00
match mem::replace(&mut self.dispatch_state, FramedState::Processing) {
FramedState::Processing => {
2019-06-26 11:19:40 +02:00
if self.poll_read() || self.poll_write() {
self.poll()
} else {
Ok(Async::NotReady)
}
}
2019-07-01 07:20:24 +02:00
FramedState::Error(err) => {
2019-06-26 11:19:40 +02:00
if self.framed.is_write_buf_empty()
|| (self.poll_write() || self.framed.is_write_buf_empty())
{
2019-07-02 08:10:05 +02:00
self.disconnect(true);
2019-06-26 11:19:40 +02:00
Err(err)
} else {
2019-07-01 07:20:24 +02:00
self.dispatch_state = FramedState::Error(err);
2019-06-26 11:19:40 +02:00
Ok(Async::NotReady)
}
}
2019-07-01 07:20:24 +02:00
FramedState::FlushAndStop(mut vec) => {
2019-06-26 11:19:40 +02:00
if !self.framed.is_write_buf_empty() {
match self.framed.poll_complete() {
Err(err) => {
debug!("Error sending data: {:?}", err);
}
Ok(Async::NotReady) => {
2019-07-01 07:20:24 +02:00
self.dispatch_state = FramedState::FlushAndStop(vec);
2019-06-26 11:19:40 +02:00
return Ok(Async::NotReady);
}
Ok(Async::Ready(_)) => (),
}
};
for tx in vec.drain(..) {
let _ = tx.send(());
}
2019-07-02 08:10:05 +02:00
self.disconnect(false);
2019-06-26 11:19:40 +02:00
Ok(Async::Ready(()))
}
2019-07-02 08:10:05 +02:00
FramedState::FramedError(err) => {
self.disconnect(true);
Err(err)
}
2019-07-03 09:02:03 +02:00
FramedState::Stopping => {
self.disconnect(false);
Ok(Async::Ready(()))
}
2019-06-26 11:19:40 +02:00
}
}
}