1
0
mirror of https://github.com/fafhrd91/actix-net synced 2024-11-30 22:14:35 +01:00
actix-net/actix-utils/src/framed.rs

331 lines
11 KiB
Rust
Raw Normal View History

2018-09-13 03:47:39 +02:00
//! Framed dispatcher service and related utilities
2019-01-27 06:41:28 +01:00
use std::collections::VecDeque;
use std::{fmt, mem};
2018-09-13 03:47:39 +02:00
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
use actix_service::{IntoService, Service};
2019-01-27 06:41:28 +01:00
use futures::task::AtomicTask;
use futures::unsync::mpsc;
use futures::{Async, Future, Poll, Sink, Stream};
2018-12-17 01:26:24 +01:00
use log::debug;
2018-09-13 03:47:39 +02:00
2019-01-27 06:41:28 +01:00
use crate::cell::Cell;
type Request<U> = <U as Decoder>::Item;
type Response<U> = <U as Encoder>::Item;
2018-09-13 03:47:39 +02:00
/// Framed transport errors
pub enum FramedTransportError<E, U: Encoder + Decoder> {
Service(E),
Encoder(<U as Encoder>::Error),
Decoder(<U as Decoder>::Error),
2018-09-13 03:47:39 +02:00
}
impl<E, U: Encoder + Decoder> From<E> for FramedTransportError<E, U> {
fn from(err: E) -> Self {
FramedTransportError::Service(err)
2018-09-13 03:47:39 +02:00
}
}
impl<E, U: Encoder + Decoder> fmt::Debug for FramedTransportError<E, U>
2018-09-13 03:47:39 +02:00
where
E: fmt::Debug,
<U as Encoder>::Error: fmt::Debug,
<U as Decoder>::Error: fmt::Debug,
2018-09-13 03:47:39 +02:00
{
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match *self {
FramedTransportError::Service(ref e) => {
write!(fmt, "FramedTransportError::Service({:?})", e)
}
FramedTransportError::Encoder(ref e) => {
write!(fmt, "FramedTransportError::Encoder({:?})", e)
}
FramedTransportError::Decoder(ref e) => {
write!(fmt, "FramedTransportError::Encoder({:?})", e)
}
2018-09-13 03:47:39 +02:00
}
}
}
impl<E, U: Encoder + Decoder> fmt::Display for FramedTransportError<E, U>
2018-09-13 03:47:39 +02:00
where
E: fmt::Display,
<U as Encoder>::Error: fmt::Debug,
<U as Decoder>::Error: fmt::Debug,
2018-09-13 03:47:39 +02:00
{
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match *self {
FramedTransportError::Service(ref e) => write!(fmt, "{}", e),
FramedTransportError::Encoder(ref e) => write!(fmt, "{:?}", e),
FramedTransportError::Decoder(ref e) => write!(fmt, "{:?}", e),
2018-09-13 03:47:39 +02:00
}
}
}
pub enum FramedMessage<T> {
Message(T),
Close,
}
/// FramedTransport - is a future that reads frames from Framed object
2018-09-13 03:47:39 +02:00
/// and pass then to the service.
2018-09-25 05:40:31 +02:00
pub struct FramedTransport<S, T, U>
2018-09-13 03:47:39 +02:00
where
2019-03-09 16:27:35 +01:00
S: Service<Request = Request<U>, Response = Response<U>>,
2019-01-27 07:07:27 +01:00
S::Error: 'static,
S::Future: 'static,
T: AsyncRead + AsyncWrite,
U: Encoder + Decoder,
<U as Encoder>::Item: 'static,
2019-01-27 06:41:28 +01:00
<U as Encoder>::Error: std::fmt::Debug,
2018-09-13 03:47:39 +02:00
{
2019-01-27 07:07:27 +01:00
service: S,
state: TransportState<S, U>,
framed: Framed<T, U>,
rx: Option<mpsc::UnboundedReceiver<FramedMessage<<U as Encoder>::Item>>>,
2019-01-27 07:07:27 +01:00
inner: Cell<FramedTransportInner<<U as Encoder>::Item, S::Error>>,
2018-09-13 03:47:39 +02:00
}
2019-03-09 16:27:35 +01:00
enum TransportState<S: Service, U: Encoder + Decoder> {
Processing,
2018-09-25 07:31:05 +02:00
Error(FramedTransportError<S::Error, U>),
2018-12-21 22:00:26 +01:00
FramedError(FramedTransportError<S::Error, U>),
FlushAndStop,
Stopping,
}
2019-01-27 07:07:27 +01:00
struct FramedTransportInner<I, E> {
buf: VecDeque<Result<I, E>>,
2019-01-27 06:41:28 +01:00
task: AtomicTask,
2018-09-13 03:47:39 +02:00
}
2019-01-27 07:07:27 +01:00
impl<S, T, U> FramedTransport<S, T, U>
2018-09-13 03:47:39 +02:00
where
2019-03-09 16:27:35 +01:00
S: Service<Request = Request<U>, Response = Response<U>>,
2019-01-27 07:07:27 +01:00
S::Error: 'static,
S::Future: 'static,
T: AsyncRead + AsyncWrite,
U: Decoder + Encoder,
<U as Encoder>::Item: 'static,
2019-01-27 06:41:28 +01:00
<U as Encoder>::Error: std::fmt::Debug,
2018-09-13 03:47:39 +02:00
{
2019-02-01 23:48:09 +01:00
fn poll_read(&mut self) -> bool {
2019-01-27 06:41:28 +01:00
loop {
match self.service.poll_ready() {
Ok(Async::Ready(_)) => {
2018-09-27 05:40:45 +02:00
let item = match self.framed.poll() {
Ok(Async::Ready(Some(el))) => el,
Err(err) => {
2018-09-25 05:40:31 +02:00
self.state =
2018-12-21 22:00:26 +01:00
TransportState::FramedError(FramedTransportError::Decoder(err));
return true;
2018-09-13 03:47:39 +02:00
}
Ok(Async::NotReady) => return false,
Ok(Async::Ready(None)) => {
self.state = TransportState::Stopping;
return true;
2018-09-13 03:47:39 +02:00
}
2018-09-27 05:40:45 +02:00
};
2019-01-27 07:07:27 +01:00
let mut cell = self.inner.clone();
cell.get_mut().task.register();
2019-01-27 06:41:28 +01:00
tokio_current_thread::spawn(self.service.call(item).then(move |item| {
let inner = cell.get_mut();
inner.buf.push_back(item);
inner.task.notify();
Ok(())
}));
}
2019-01-27 06:41:28 +01:00
Ok(Async::NotReady) => return false,
Err(err) => {
self.state = TransportState::Error(FramedTransportError::Service(err));
return true;
2018-09-13 03:47:39 +02:00
}
}
2018-09-13 03:47:39 +02:00
}
}
2018-09-13 03:47:39 +02:00
2019-02-01 23:48:09 +01:00
/// write to framed object
fn poll_write(&mut self) -> bool {
2019-01-27 07:07:27 +01:00
let inner = self.inner.get_mut();
let mut rx_done = self.rx.is_none();
let mut buf_empty = inner.buf.is_empty();
2018-09-13 03:47:39 +02:00
loop {
2018-12-17 01:26:24 +01:00
while !self.framed.is_write_buf_full() {
if !buf_empty {
match inner.buf.pop_front().unwrap() {
2018-12-17 01:26:24 +01:00
Ok(msg) => {
if let Err(err) = self.framed.force_send(msg) {
2018-12-21 22:00:26 +01:00
self.state = TransportState::FramedError(
2018-12-17 01:26:24 +01:00
FramedTransportError::Encoder(err),
);
return true;
}
buf_empty = inner.buf.is_empty();
2018-12-17 01:26:24 +01:00
}
Err(err) => {
self.state =
TransportState::Error(FramedTransportError::Service(err));
return true;
}
2019-01-27 06:41:28 +01:00
}
}
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.state = TransportState::FramedError(
FramedTransportError::Encoder(err),
);
return true;
}
}
Ok(Async::Ready(Some(FramedMessage::Close))) => {
self.state = TransportState::FlushAndStop;
return true;
}
Ok(Async::Ready(None)) => {
let _ = self.rx.take();
}
Ok(Async::NotReady) => rx_done = true,
Err(_e) => {
let _ = self.rx.take();
}
}
}
if rx_done && buf_empty {
2019-01-27 06:41:28 +01:00
break;
2018-09-13 03:47:39 +02:00
}
2018-12-17 01:26:24 +01:00
}
2018-09-13 03:47:39 +02:00
2018-12-17 01:26:24 +01:00
if !self.framed.is_write_buf_empty() {
2018-09-13 03:47:39 +02:00
match self.framed.poll_complete() {
Ok(Async::NotReady) => break,
Err(err) => {
2018-12-17 01:26:24 +01:00
debug!("Error sending data: {:?}", err);
2018-09-25 05:40:31 +02:00
self.state =
2018-12-21 22:00:26 +01:00
TransportState::FramedError(FramedTransportError::Encoder(err));
return true;
2018-09-13 03:47:39 +02:00
}
2018-12-17 01:26:24 +01:00
Ok(Async::Ready(_)) => (),
2018-09-13 03:47:39 +02:00
}
} else {
break;
}
}
false
}
}
2019-01-27 06:41:28 +01:00
impl<S, T, U> FramedTransport<S, T, U>
where
2019-03-09 16:27:35 +01:00
S: Service<Request = Request<U>, Response = Response<U>>,
2019-01-27 07:07:27 +01:00
S::Error: 'static,
S::Future: 'static,
T: AsyncRead + AsyncWrite,
U: Decoder + Encoder,
<U as Encoder>::Item: 'static,
2019-01-27 06:41:28 +01:00
<U as Encoder>::Error: std::fmt::Debug,
{
2019-03-09 16:27:35 +01:00
pub fn new<F: IntoService<S>>(framed: Framed<T, U>, service: F) -> Self {
2019-01-27 07:07:27 +01:00
FramedTransport {
2019-01-27 06:41:28 +01:00
framed,
rx: None,
2019-01-27 06:41:28 +01:00
service: service.into_service(),
state: TransportState::Processing,
2019-01-27 07:07:27 +01:00
inner: Cell::new(FramedTransportInner {
buf: VecDeque::new(),
task: AtomicTask::new(),
}),
2019-01-27 06:41:28 +01:00
}
}
/// Get Sender
pub fn set_receiver(
mut self,
rx: mpsc::UnboundedReceiver<FramedMessage<<U as Encoder>::Item>>,
) -> Self {
self.rx = Some(rx);
self
}
2019-01-27 06:41:28 +01:00
/// Get reference to a service wrapped by `FramedTransport` instance.
pub fn get_ref(&self) -> &S {
2019-01-27 07:07:27 +01:00
&self.service
2019-01-27 06:41:28 +01:00
}
/// Get mutable reference to a service wrapped by `FramedTransport`
/// instance.
pub fn get_mut(&mut self) -> &mut S {
2019-01-27 07:07:27 +01:00
&mut self.service
2019-01-27 06:41:28 +01:00
}
/// Get reference to a framed instance wrapped by `FramedTransport`
/// instance.
pub fn get_framed(&self) -> &Framed<T, U> {
2019-01-27 07:07:27 +01:00
&self.framed
2019-01-27 06:41:28 +01:00
}
/// Get mutable reference to a framed instance wrapped by `FramedTransport`
/// instance.
pub fn get_framed_mut(&mut self) -> &mut Framed<T, U> {
2019-01-27 07:07:27 +01:00
&mut self.framed
2019-01-27 06:41:28 +01:00
}
}
2018-09-25 05:40:31 +02:00
impl<S, T, U> Future for FramedTransport<S, T, U>
where
2019-03-09 16:27:35 +01:00
S: Service<Request = Request<U>, Response = Response<U>>,
2019-01-27 07:07:27 +01:00
S::Error: 'static,
S::Future: 'static,
T: AsyncRead + AsyncWrite,
U: Decoder + Encoder,
<U as Encoder>::Item: 'static,
2019-01-27 06:41:28 +01:00
<U as Encoder>::Error: std::fmt::Debug,
{
type Item = ();
2018-09-25 07:31:05 +02:00
type Error = FramedTransportError<S::Error, U>;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
2019-01-27 07:07:27 +01:00
match mem::replace(&mut self.state, TransportState::Processing) {
TransportState::Processing => {
2019-02-01 23:48:09 +01:00
if self.poll_read() || self.poll_write() {
2018-12-06 23:04:42 +01:00
self.poll()
} else {
Ok(Async::NotReady)
}
}
2018-09-25 05:40:31 +02:00
TransportState::Error(err) => {
2019-01-27 07:07:27 +01:00
if self.framed.is_write_buf_empty()
2019-02-01 23:48:09 +01:00
|| (self.poll_write() || self.framed.is_write_buf_empty())
2018-12-26 20:50:07 +01:00
{
2018-12-06 23:04:42 +01:00
Err(err)
} else {
2019-01-27 07:07:27 +01:00
self.state = TransportState::Error(err);
2018-12-06 23:04:42 +01:00
Ok(Async::NotReady)
}
}
TransportState::FlushAndStop => {
if !self.framed.is_write_buf_empty() {
match self.framed.poll_complete() {
Err(err) => {
debug!("Error sending data: {:?}", err);
Ok(Async::Ready(()))
}
Ok(Async::NotReady) => Ok(Async::NotReady),
Ok(Async::Ready(_)) => Ok(Async::Ready(())),
}
} else {
Ok(Async::Ready(()))
}
}
2018-12-21 22:00:26 +01:00
TransportState::FramedError(err) => Err(err),
2018-12-06 23:04:42 +01:00
TransportState::Stopping => Ok(Async::Ready(())),
2018-09-25 05:40:31 +02:00
}
2018-09-13 03:47:39 +02:00
}
}