1
0
mirror of https://github.com/fafhrd91/actix-net synced 2025-08-16 02:13:52 +02:00

Compare commits

..

9 Commits

Author SHA1 Message Date
Nikolay Kim
9957f28137 prepare actix-testing release 2019-12-11 14:49:26 +06:00
Nikolay Kim
9d84d14ef4 update deps 2019-12-11 14:47:30 +06:00
Nikolay Kim
60bfa1bfb1 prepare actix-server release 2019-12-11 14:43:26 +06:00
Nikolay Kim
2c81c22b3e refactor ioframe dispatcher 2019-12-11 14:36:11 +06:00
Nikolay Kim
dded482514 allow to close mpsc sender 2019-12-11 14:36:00 +06:00
Nikolay Kim
631cb86947 refactor framed and stream dispatchers 2019-12-11 12:42:07 +06:00
Nikolay Kim
2e5e69c9ba Simplify oneshot and mpsc implementations 2019-12-11 11:28:09 +06:00
Nikolay Kim
e315cf2893 prep actix-rt release; update deps 2019-12-11 10:34:50 +06:00
Nikolay Kim
13fd615966 actix-macros release 2019-12-11 10:32:01 +06:00
26 changed files with 731 additions and 967 deletions

View File

@@ -33,10 +33,10 @@ rustls = ["rust-tls", "tokio-rustls", "webpki"]
uri = ["http"] uri = ["http"]
[dependencies] [dependencies]
actix-service = "1.0.0-alpha.3" actix-service = "1.0.0"
actix-codec = "0.2.0" actix-codec = "0.2.0"
actix-utils = "1.0.0-alpha.3" actix-utils = "1.0.0"
actix-rt = "1.0.0-alpha.3" actix-rt = "1.0.0"
derive_more = "0.99.2" derive_more = "0.99.2"
either = "1.5.2" either = "1.5.2"
futures = "0.3.1" futures = "0.3.1"
@@ -55,4 +55,4 @@ webpki = { version = "0.21", optional = true }
[dev-dependencies] [dev-dependencies]
bytes = "0.5.2" bytes = "0.5.2"
actix-testing = { version="1.0.0-alpha.2" } actix-testing = { version="1.0.0" }

View File

@@ -18,10 +18,10 @@ name = "actix_ioframe"
path = "src/lib.rs" path = "src/lib.rs"
[dependencies] [dependencies]
actix-service = "1.0.0-alpha.3" actix-service = "1.0.0"
actix-codec = "0.2.0" actix-codec = "0.2.0"
actix-utils = "1.0.0-alpha.2" actix-utils = "1.0.0"
actix-rt = "1.0.0-alpha.2" actix-rt = "1.0.0"
bytes = "0.5" bytes = "0.5"
either = "1.5.2" either = "1.5.2"
futures = "0.3.1" futures = "0.3.1"
@@ -30,4 +30,4 @@ log = "0.4"
[dev-dependencies] [dev-dependencies]
actix-connect = "1.0.0-alpha.2" actix-connect = "1.0.0-alpha.2"
actix-testing = "1.0.0-alpha.2" actix-testing = "1.0.0"

View File

@@ -1,39 +0,0 @@
//! Custom cell impl
use std::cell::UnsafeCell;
use std::fmt;
use std::rc::Rc;
pub(crate) struct Cell<T> {
inner: Rc<UnsafeCell<T>>,
}
impl<T> Clone for Cell<T> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
}
}
}
impl<T: fmt::Debug> fmt::Debug for Cell<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.inner.fmt(f)
}
}
impl<T> Cell<T> {
pub fn new(inner: T) -> Self {
Self {
inner: Rc::new(UnsafeCell::new(inner)),
}
}
pub(crate) unsafe fn get_ref(&mut self) -> &T {
&*self.inner.as_ref().get()
}
pub(crate) unsafe fn get_mut(&mut self) -> &mut T {
&mut *self.inner.as_ref().get()
}
}

View File

@@ -3,55 +3,51 @@ use std::pin::Pin;
use std::task::{Context, Poll}; use std::task::{Context, Poll};
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed}; use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
use actix_utils::mpsc;
use futures::Stream; use futures::Stream;
use crate::dispatcher::FramedMessage;
use crate::sink::Sink; use crate::sink::Sink;
pub struct Connect<Io, St = (), Codec = ()> { pub struct Connect<Io, Codec, Err, St = ()>
where
Codec: Encoder + Decoder,
{
io: Io, io: Io,
sink: Sink<<Codec as Encoder>::Item, Err>,
_t: PhantomData<(St, Codec)>, _t: PhantomData<(St, Codec)>,
} }
impl<Io> Connect<Io> impl<Io, Codec, Err> Connect<Io, Codec, Err>
where where
Io: AsyncRead + AsyncWrite, Io: AsyncRead + AsyncWrite,
Codec: Encoder + Decoder,
{ {
pub(crate) fn new(io: Io) -> Self { pub(crate) fn new(io: Io, sink: Sink<<Codec as Encoder>::Item, Err>) -> Self {
Self { Self {
io, io,
sink,
_t: PhantomData, _t: PhantomData,
} }
} }
pub fn codec<Codec>(self, codec: Codec) -> ConnectResult<Io, (), Codec> pub fn codec(self, codec: Codec) -> ConnectResult<Io, (), Codec, Err> {
where
Codec: Encoder + Decoder,
{
let (tx, rx) = mpsc::channel();
let sink = Sink::new(tx);
ConnectResult { ConnectResult {
state: (), state: (),
sink: self.sink,
framed: Framed::new(self.io, codec), framed: Framed::new(self.io, codec),
rx,
sink,
} }
} }
} }
#[pin_project::pin_project] #[pin_project::pin_project]
pub struct ConnectResult<Io, St, Codec: Encoder + Decoder> { pub struct ConnectResult<Io, St, Codec: Encoder + Decoder, Err> {
pub(crate) state: St, pub(crate) state: St,
pub(crate) framed: Framed<Io, Codec>, pub(crate) framed: Framed<Io, Codec>,
pub(crate) rx: mpsc::Receiver<FramedMessage<<Codec as Encoder>::Item>>, pub(crate) sink: Sink<<Codec as Encoder>::Item, Err>,
pub(crate) sink: Sink<<Codec as Encoder>::Item>,
} }
impl<Io, St, Codec: Encoder + Decoder> ConnectResult<Io, St, Codec> { impl<Io, St, Codec: Encoder + Decoder, Err> ConnectResult<Io, St, Codec, Err> {
#[inline] #[inline]
pub fn sink(&self) -> &Sink<<Codec as Encoder>::Item> { pub fn sink(&self) -> &Sink<<Codec as Encoder>::Item, Err> {
&self.sink &self.sink
} }
@@ -66,17 +62,16 @@ impl<Io, St, Codec: Encoder + Decoder> ConnectResult<Io, St, Codec> {
} }
#[inline] #[inline]
pub fn state<S>(self, state: S) -> ConnectResult<Io, S, Codec> { pub fn state<S>(self, state: S) -> ConnectResult<Io, S, Codec, Err> {
ConnectResult { ConnectResult {
state, state,
framed: self.framed, framed: self.framed,
rx: self.rx,
sink: self.sink, sink: self.sink,
} }
} }
} }
impl<Io, St, Codec> Stream for ConnectResult<Io, St, Codec> impl<Io, St, Codec, Err> Stream for ConnectResult<Io, St, Codec, Err>
where where
Io: AsyncRead + AsyncWrite, Io: AsyncRead + AsyncWrite,
Codec: Encoder + Decoder, Codec: Encoder + Decoder,
@@ -88,7 +83,8 @@ where
} }
} }
impl<Io, St, Codec> futures::Sink<<Codec as Encoder>::Item> for ConnectResult<Io, St, Codec> impl<Io, St, Codec, Err> futures::Sink<<Codec as Encoder>::Item>
for ConnectResult<Io, St, Codec, Err>
where where
Io: AsyncRead + AsyncWrite, Io: AsyncRead + AsyncWrite,
Codec: Encoder + Decoder, Codec: Encoder + Decoder,

View File

@@ -1,39 +1,34 @@
//! Framed dispatcher service and related utilities //! Framed dispatcher service and related utilities
use std::collections::VecDeque;
use std::mem;
use std::pin::Pin; use std::pin::Pin;
use std::rc::Rc; use std::rc::Rc;
use std::task::{Context, Poll}; use std::task::{Context, Poll};
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed}; use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
use actix_service::{IntoService, Service}; use actix_service::{IntoService, Service};
use actix_utils::task::LocalWaker;
use actix_utils::{mpsc, oneshot}; use actix_utils::{mpsc, oneshot};
use futures::future::ready; use futures::{FutureExt, Stream};
use futures::{FutureExt, Sink as FutureSink, Stream};
use log::debug; use log::debug;
use crate::cell::Cell;
use crate::error::ServiceError; use crate::error::ServiceError;
use crate::item::Item; use crate::item::Item;
use crate::sink::Sink; use crate::sink::Sink;
type Request<S, U> = Item<S, U>; type Request<S, U, E> = Item<S, U, E>;
type Response<U> = <U as Encoder>::Item; type Response<U> = <U as Encoder>::Item;
pub(crate) enum FramedMessage<T> { pub(crate) enum Message<T> {
Message(T), Item(T),
Close,
WaitClose(oneshot::Sender<()>), WaitClose(oneshot::Sender<()>),
Close,
} }
/// FramedTransport - is a future that reads frames from Framed object /// FramedTransport - is a future that reads frames from Framed object
/// and pass then to the service. /// and pass then to the service.
#[pin_project::pin_project] #[pin_project::pin_project]
pub(crate) struct FramedDispatcher<St, S, T, U> pub(crate) struct Dispatcher<St, S, T, U, E>
where where
St: Clone, St: Clone,
S: Service<Request = Request<St, U>, Response = Option<Response<U>>>, S: Service<Request = Request<St, U, E>, Response = Option<Response<U>>, Error = E>,
S::Error: 'static, S::Error: 'static,
S::Future: 'static, S::Future: 'static,
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
@@ -42,19 +37,19 @@ where
<U as Encoder>::Error: std::fmt::Debug, <U as Encoder>::Error: std::fmt::Debug,
{ {
service: S, service: S,
sink: Sink<<U as Encoder>::Item>, sink: Sink<<U as Encoder>::Item, E>,
state: St, state: St,
dispatch_state: FramedState<S, U>, dispatch_state: FramedState<S, U>,
framed: Framed<T, U>, framed: Framed<T, U>,
rx: Option<mpsc::Receiver<FramedMessage<<U as Encoder>::Item>>>, rx: mpsc::Receiver<Result<Message<<U as Encoder>::Item>, E>>,
inner: Cell<FramedDispatcherInner<<U as Encoder>::Item, S::Error>>, tx: mpsc::Sender<Result<Message<<U as Encoder>::Item>, E>>,
disconnect: Option<Rc<dyn Fn(&mut St, bool)>>, disconnect: Option<Rc<dyn Fn(&mut St, bool)>>,
} }
impl<St, S, T, U> FramedDispatcher<St, S, T, U> impl<St, S, T, U, E> Dispatcher<St, S, T, U, E>
where where
St: Clone, St: Clone,
S: Service<Request = Request<St, U>, Response = Option<Response<U>>>, S: Service<Request = Request<St, U, E>, Response = Option<Response<U>>, Error = E>,
S::Error: 'static, S::Error: 'static,
S::Future: 'static, S::Future: 'static,
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
@@ -66,22 +61,21 @@ where
framed: Framed<T, U>, framed: Framed<T, U>,
state: St, state: St,
service: F, service: F,
rx: mpsc::Receiver<FramedMessage<<U as Encoder>::Item>>, sink: Sink<<U as Encoder>::Item, E>,
sink: Sink<<U as Encoder>::Item>, rx: mpsc::Receiver<Result<Message<<U as Encoder>::Item>, E>>,
disconnect: Option<Rc<dyn Fn(&mut St, bool)>>, disconnect: Option<Rc<dyn Fn(&mut St, bool)>>,
) -> Self { ) -> Self {
FramedDispatcher { let tx = rx.sender();
Dispatcher {
framed, framed,
state, state,
sink, sink,
disconnect, disconnect,
rx: Some(rx), rx,
tx,
service: service.into_service(), service: service.into_service(),
dispatch_state: FramedState::Processing, dispatch_state: FramedState::Processing,
inner: Cell::new(FramedDispatcherInner {
buf: VecDeque::new(),
task: LocalWaker::new(),
}),
} }
} }
} }
@@ -116,17 +110,26 @@ impl<S: Service, U: Encoder + Decoder> FramedState<S, U> {
} }
} }
} }
fn take_error(&mut self) -> ServiceError<S::Error, U> {
match std::mem::replace(self, FramedState::Processing) {
FramedState::Error(err) => err,
_ => panic!(),
}
} }
struct FramedDispatcherInner<I, E> { fn take_framed_error(&mut self) -> ServiceError<S::Error, U> {
buf: VecDeque<Result<I, E>>, match std::mem::replace(self, FramedState::Processing) {
task: LocalWaker, FramedState::FramedError(err) => err,
_ => panic!(),
}
}
} }
impl<St, S, T, U> FramedDispatcher<St, S, T, U> impl<St, S, T, U, E> Dispatcher<St, S, T, U, E>
where where
St: Clone, St: Clone,
S: Service<Request = Request<St, U>, Response = Option<Response<U>>>, S: Service<Request = Request<St, U, E>, Response = Option<Response<U>>, Error = E>,
S::Error: 'static, S::Error: 'static,
S::Future: 'static, S::Future: 'static,
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
@@ -134,90 +137,125 @@ where
<U as Encoder>::Item: 'static, <U as Encoder>::Item: 'static,
<U as Encoder>::Error: std::fmt::Debug, <U as Encoder>::Error: std::fmt::Debug,
{ {
fn poll_read(&mut self, cx: &mut Context<'_>) -> bool {
loop {
match self.service.poll_ready(cx) {
Poll::Ready(Ok(_)) => {
let item = match self.framed.next_item(cx) {
Poll::Ready(Some(Ok(el))) => el,
Poll::Ready(Some(Err(err))) => {
self.dispatch_state =
FramedState::FramedError(ServiceError::Decoder(err));
return true;
}
Poll::Pending => return false,
Poll::Ready(None) => {
log::trace!("Client disconnected");
self.dispatch_state = FramedState::Stopping;
return true;
}
};
let tx = self.tx.clone();
actix_rt::spawn(
self.service
.call(Item::new(self.state.clone(), self.sink.clone(), item))
.map(move |item| {
let item = match item {
Ok(Some(item)) => Ok(Message::Item(item)),
Ok(None) => return,
Err(err) => Err(err),
};
let _ = tx.send(item);
}),
);
}
Poll::Pending => return false,
Poll::Ready(Err(err)) => {
self.dispatch_state = FramedState::Error(ServiceError::Service(err));
return true;
}
}
}
}
/// write to framed object
fn poll_write(&mut self, cx: &mut Context<'_>) -> bool {
loop {
while !self.framed.is_write_buf_full() {
match Pin::new(&mut self.rx).poll_next(cx) {
Poll::Ready(Some(Ok(Message::Item(msg)))) => {
if let Err(err) = self.framed.write(msg) {
self.dispatch_state =
FramedState::FramedError(ServiceError::Encoder(err));
return true;
}
}
Poll::Ready(Some(Ok(Message::Close))) => {
self.dispatch_state.stop(None);
return true;
}
Poll::Ready(Some(Ok(Message::WaitClose(tx)))) => {
self.dispatch_state.stop(Some(tx));
return true;
}
Poll::Ready(Some(Err(err))) => {
self.dispatch_state = FramedState::Error(ServiceError::Service(err));
return true;
}
Poll::Ready(None) | Poll::Pending => break,
}
}
if !self.framed.is_write_buf_empty() {
match self.framed.flush(cx) {
Poll::Pending => break,
Poll::Ready(Ok(_)) => (),
Poll::Ready(Err(err)) => {
debug!("Error sending data: {:?}", err);
self.dispatch_state =
FramedState::FramedError(ServiceError::Encoder(err));
return true;
}
}
} else {
break;
}
}
false
}
pub(crate) fn poll( pub(crate) fn poll(
&mut self, &mut self,
cx: &mut Context<'_>, cx: &mut Context<'_>,
) -> Poll<Result<(), ServiceError<S::Error, U>>> { ) -> Poll<Result<(), ServiceError<S::Error, U>>> {
let this = self; match self.dispatch_state {
unsafe { this.inner.get_ref().task.register(cx.waker()) };
poll(
cx,
&mut this.service,
&mut this.state,
&mut this.sink,
&mut this.framed,
&mut this.dispatch_state,
&mut this.rx,
&mut this.inner,
&mut this.disconnect,
)
}
}
fn poll<St, S, T, U>(
cx: &mut Context<'_>,
srv: &mut S,
state: &mut St,
sink: &mut Sink<<U as Encoder>::Item>,
framed: &mut Framed<T, U>,
dispatch_state: &mut FramedState<S, U>,
rx: &mut Option<mpsc::Receiver<FramedMessage<<U as Encoder>::Item>>>,
inner: &mut Cell<FramedDispatcherInner<<U as Encoder>::Item, S::Error>>,
disconnect: &mut Option<Rc<dyn Fn(&mut St, bool)>>,
) -> Poll<Result<(), ServiceError<S::Error, U>>>
where
St: Clone,
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,
{
match mem::replace(dispatch_state, FramedState::Processing) {
FramedState::Processing => { FramedState::Processing => {
if poll_read(cx, srv, state, sink, framed, dispatch_state, inner) if self.poll_read(cx) || self.poll_write(cx) {
|| poll_write(cx, framed, dispatch_state, rx, inner) self.poll(cx)
{
poll(
cx,
srv,
state,
sink,
framed,
dispatch_state,
rx,
inner,
disconnect,
)
} else { } else {
Poll::Pending Poll::Pending
} }
} }
FramedState::Error(err) => { FramedState::Error(_) => {
if framed.is_write_buf_empty() // flush write buffer
|| (poll_write(cx, framed, dispatch_state, rx, inner) if !self.framed.is_write_buf_empty() {
|| framed.is_write_buf_empty()) if let Poll::Pending = self.framed.flush(cx) {
{ return Poll::Pending;
if let Some(ref disconnect) = disconnect {
(&*disconnect)(&mut *state, true);
}
Poll::Ready(Err(err))
} else {
*dispatch_state = FramedState::Error(err);
Poll::Pending
} }
} }
FramedState::FlushAndStop(mut vec) => { if let Some(ref disconnect) = self.disconnect {
if !framed.is_write_buf_empty() { (&*disconnect)(&mut self.state, true);
match Pin::new(framed).poll_flush(cx) { }
Poll::Ready(Err(self.dispatch_state.take_error()))
}
FramedState::FlushAndStop(ref mut vec) => {
if !self.framed.is_write_buf_empty() {
match self.framed.flush(cx) {
Poll::Ready(Err(err)) => { Poll::Ready(Err(err)) => {
debug!("Error sending data: {:?}", err); debug!("Error sending data: {:?}", err);
} }
Poll::Pending => { Poll::Pending => {
*dispatch_state = FramedState::FlushAndStop(vec);
return Poll::Pending; return Poll::Pending;
} }
Poll::Ready(_) => (), Poll::Ready(_) => (),
@@ -226,171 +264,23 @@ where
for tx in vec.drain(..) { for tx in vec.drain(..) {
let _ = tx.send(()); let _ = tx.send(());
} }
if let Some(ref disconnect) = disconnect { if let Some(ref disconnect) = self.disconnect {
(&*disconnect)(&mut *state, false); (&*disconnect)(&mut self.state, false);
} }
Poll::Ready(Ok(())) Poll::Ready(Ok(()))
} }
FramedState::FramedError(err) => { FramedState::FramedError(_) => {
if let Some(ref disconnect) = disconnect { if let Some(ref disconnect) = self.disconnect {
(&*disconnect)(&mut *state, true); (&*disconnect)(&mut self.state, true);
} }
Poll::Ready(Err(err)) Poll::Ready(Err(self.dispatch_state.take_framed_error()))
} }
FramedState::Stopping => { FramedState::Stopping => {
if let Some(ref disconnect) = disconnect { if let Some(ref disconnect) = self.disconnect {
(&*disconnect)(&mut *state, false); (&*disconnect)(&mut self.state, false);
} }
Poll::Ready(Ok(())) Poll::Ready(Ok(()))
} }
} }
} }
fn poll_read<St, S, T, U>(
cx: &mut Context<'_>,
srv: &mut S,
state: &mut St,
sink: &mut Sink<<U as Encoder>::Item>,
framed: &mut Framed<T, U>,
dispatch_state: &mut FramedState<S, U>,
inner: &mut Cell<FramedDispatcherInner<<U as Encoder>::Item, S::Error>>,
) -> bool
where
St: Clone,
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,
{
loop {
match srv.poll_ready(cx) {
Poll::Ready(Ok(_)) => {
let item = match framed.next_item(cx) {
Poll::Ready(Some(Ok(el))) => el,
Poll::Ready(Some(Err(err))) => {
*dispatch_state = FramedState::FramedError(ServiceError::Decoder(err));
return true;
}
Poll::Pending => return false,
Poll::Ready(None) => {
log::trace!("Client disconnected");
*dispatch_state = FramedState::Stopping;
return true;
}
};
let mut cell = inner.clone();
actix_rt::spawn(srv.call(Item::new(state.clone(), sink.clone(), item)).then(
move |item| {
let item = match item {
Ok(Some(item)) => Ok(item),
Ok(None) => return ready(()),
Err(err) => Err(err),
};
unsafe {
let inner = cell.get_mut();
inner.buf.push_back(item);
inner.task.wake();
}
ready(())
},
));
}
Poll::Pending => return false,
Poll::Ready(Err(err)) => {
*dispatch_state = FramedState::Error(ServiceError::Service(err));
return true;
}
}
}
}
/// write to framed object
fn poll_write<St, S, T, U>(
cx: &mut Context<'_>,
framed: &mut Framed<T, U>,
dispatch_state: &mut FramedState<S, U>,
rx: &mut Option<mpsc::Receiver<FramedMessage<<U as Encoder>::Item>>>,
inner: &mut Cell<FramedDispatcherInner<<U as Encoder>::Item, S::Error>>,
) -> bool
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,
{
let inner = unsafe { inner.get_mut() };
let mut rx_done = rx.is_none();
let mut buf_empty = inner.buf.is_empty();
loop {
while !framed.is_write_buf_full() {
if !buf_empty {
match inner.buf.pop_front().unwrap() {
Ok(msg) => {
if let Err(err) = framed.write(msg) {
*dispatch_state =
FramedState::FramedError(ServiceError::Encoder(err));
return true;
}
buf_empty = inner.buf.is_empty();
}
Err(err) => {
*dispatch_state = FramedState::Error(ServiceError::Service(err));
return true;
}
}
}
if !rx_done && rx.is_some() {
match Pin::new(rx.as_mut().unwrap()).poll_next(cx) {
Poll::Ready(Some(FramedMessage::Message(msg))) => {
if let Err(err) = framed.write(msg) {
*dispatch_state =
FramedState::FramedError(ServiceError::Encoder(err));
return true;
}
}
Poll::Ready(Some(FramedMessage::Close)) => {
dispatch_state.stop(None);
return true;
}
Poll::Ready(Some(FramedMessage::WaitClose(tx))) => {
dispatch_state.stop(Some(tx));
return true;
}
Poll::Ready(None) => {
rx_done = true;
let _ = rx.take();
}
Poll::Pending => rx_done = true,
}
}
if rx_done && buf_empty {
break;
}
}
if !framed.is_write_buf_empty() {
match framed.flush(cx) {
Poll::Pending => break,
Poll::Ready(Err(err)) => {
debug!("Error sending data: {:?}", err);
*dispatch_state = FramedState::FramedError(ServiceError::Encoder(err));
return true;
}
Poll::Ready(_) => (),
}
} else {
break;
}
}
false
} }

View File

@@ -5,19 +5,19 @@ use actix_codec::{Decoder, Encoder};
use crate::sink::Sink; use crate::sink::Sink;
pub struct Item<St, Codec: Encoder + Decoder> { pub struct Item<St, Codec: Encoder + Decoder, E> {
state: St, state: St,
sink: Sink<<Codec as Encoder>::Item>, sink: Sink<<Codec as Encoder>::Item, E>,
item: <Codec as Decoder>::Item, item: <Codec as Decoder>::Item,
} }
impl<St, Codec> Item<St, Codec> impl<St, Codec, E> Item<St, Codec, E>
where where
Codec: Encoder + Decoder, Codec: Encoder + Decoder,
{ {
pub(crate) fn new( pub(crate) fn new(
state: St, state: St,
sink: Sink<<Codec as Encoder>::Item>, sink: Sink<<Codec as Encoder>::Item, E>,
item: <Codec as Decoder>::Item, item: <Codec as Decoder>::Item,
) -> Self { ) -> Self {
Item { state, sink, item } Item { state, sink, item }
@@ -34,7 +34,7 @@ where
} }
#[inline] #[inline]
pub fn sink(&self) -> &Sink<<Codec as Encoder>::Item> { pub fn sink(&self) -> &Sink<<Codec as Encoder>::Item, E> {
&self.sink &self.sink
} }
@@ -44,12 +44,18 @@ where
} }
#[inline] #[inline]
pub fn into_parts(self) -> (St, Sink<<Codec as Encoder>::Item>, <Codec as Decoder>::Item) { pub fn into_parts(
self,
) -> (
St,
Sink<<Codec as Encoder>::Item, E>,
<Codec as Decoder>::Item,
) {
(self.state, self.sink, self.item) (self.state, self.sink, self.item)
} }
} }
impl<St, Codec> Deref for Item<St, Codec> impl<St, Codec, E> Deref for Item<St, Codec, E>
where where
Codec: Encoder + Decoder, Codec: Encoder + Decoder,
{ {
@@ -61,7 +67,7 @@ where
} }
} }
impl<St, Codec> DerefMut for Item<St, Codec> impl<St, Codec, E> DerefMut for Item<St, Codec, E>
where where
Codec: Encoder + Decoder, Codec: Encoder + Decoder,
{ {
@@ -71,12 +77,12 @@ where
} }
} }
impl<St, Codec> fmt::Debug for Item<St, Codec> impl<St, Codec, E> fmt::Debug for Item<St, Codec, E>
where where
Codec: Encoder + Decoder, Codec: Encoder + Decoder,
<Codec as Decoder>::Item: fmt::Debug, <Codec as Decoder>::Item: fmt::Debug,
{ {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("FramedItem").field(&self.item).finish() f.debug_tuple("Item").field(&self.item).finish()
} }
} }

View File

@@ -1,7 +1,6 @@
#![deny(rust_2018_idioms, warnings)] #![deny(rust_2018_idioms, warnings)]
#![allow(clippy::type_complexity, clippy::too_many_arguments)] #![allow(clippy::type_complexity, clippy::too_many_arguments)]
mod cell;
mod connect; mod connect;
mod dispatcher; mod dispatcher;
mod error; mod error;

View File

@@ -6,17 +6,20 @@ use std::task::{Context, Poll};
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder}; use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder};
use actix_service::{IntoService, IntoServiceFactory, Service, ServiceFactory}; use actix_service::{IntoService, IntoServiceFactory, Service, ServiceFactory};
use actix_utils::mpsc;
use either::Either; use either::Either;
use futures::future::{FutureExt, LocalBoxFuture}; use futures::future::{FutureExt, LocalBoxFuture};
use pin_project::project; use pin_project::project;
use crate::connect::{Connect, ConnectResult}; use crate::connect::{Connect, ConnectResult};
use crate::dispatcher::FramedDispatcher; use crate::dispatcher::{Dispatcher, Message};
use crate::error::ServiceError; use crate::error::ServiceError;
use crate::item::Item; use crate::item::Item;
use crate::sink::Sink;
type RequestItem<S, U> = Item<S, U>; type RequestItem<S, U, E> = Item<S, U, E>;
type ResponseItem<U> = Option<<U as Encoder>::Item>; type ResponseItem<U> = Option<<U as Encoder>::Item>;
type ServiceResult<U, E> = Result<Message<<U as Encoder>::Item>, E>;
/// Service builder - structure that follows the builder pattern /// Service builder - structure that follows the builder pattern
/// for building instances for framed services. /// for building instances for framed services.
@@ -34,11 +37,15 @@ impl<St: Clone, Codec> Builder<St, Codec> {
} }
/// Construct framed handler service with specified connect service /// Construct framed handler service with specified connect service
pub fn service<Io, C, F>(self, connect: F) -> ServiceBuilder<St, C, Io, Codec> pub fn service<Io, C, F, E>(self, connect: F) -> ServiceBuilder<St, C, Io, Codec, E>
where where
F: IntoService<C>, F: IntoService<C>,
Io: AsyncRead + AsyncWrite, Io: AsyncRead + AsyncWrite,
C: Service<Request = Connect<Io>, Response = ConnectResult<Io, St, Codec>>, C: Service<
Request = Connect<Io, Codec, E>,
Response = ConnectResult<Io, St, Codec, E>,
Error = E,
>,
Codec: Decoder + Encoder, Codec: Decoder + Encoder,
{ {
ServiceBuilder { ServiceBuilder {
@@ -49,16 +56,17 @@ impl<St: Clone, Codec> Builder<St, Codec> {
} }
/// Construct framed handler new service with specified connect service /// Construct framed handler new service with specified connect service
pub fn factory<Io, C, F>(self, connect: F) -> NewServiceBuilder<St, C, Io, Codec> pub fn factory<Io, C, F, E>(self, connect: F) -> NewServiceBuilder<St, C, Io, Codec, E>
where where
F: IntoServiceFactory<C>, F: IntoServiceFactory<C>,
E: 'static,
Io: AsyncRead + AsyncWrite, Io: AsyncRead + AsyncWrite,
C: ServiceFactory< C: ServiceFactory<
Config = (), Config = (),
Request = Connect<Io>, Request = Connect<Io, Codec, E>,
Response = ConnectResult<Io, St, Codec>, Response = ConnectResult<Io, St, Codec, E>,
Error = E,
>, >,
C::Error: 'static,
C::Future: 'static, C::Future: 'static,
Codec: Decoder + Encoder, Codec: Decoder + Encoder,
{ {
@@ -70,17 +78,20 @@ impl<St: Clone, Codec> Builder<St, Codec> {
} }
} }
pub struct ServiceBuilder<St, C, Io, Codec> { pub struct ServiceBuilder<St, C, Io, Codec, Err> {
connect: C, connect: C,
disconnect: Option<Rc<dyn Fn(&mut St, bool)>>, disconnect: Option<Rc<dyn Fn(&mut St, bool)>>,
_t: PhantomData<(St, Io, Codec)>, _t: PhantomData<(St, Io, Codec, Err)>,
} }
impl<St, C, Io, Codec> ServiceBuilder<St, C, Io, Codec> impl<St, C, Io, Codec, Err> ServiceBuilder<St, C, Io, Codec, Err>
where where
St: Clone, St: Clone,
C: Service<Request = Connect<Io>, Response = ConnectResult<Io, St, Codec>>, C: Service<
C::Error: 'static, Request = Connect<Io, Codec, Err>,
Response = ConnectResult<Io, St, Codec, Err>,
Error = Err,
>,
Io: AsyncRead + AsyncWrite, Io: AsyncRead + AsyncWrite,
Codec: Decoder + Encoder, Codec: Decoder + Encoder,
<Codec as Encoder>::Item: 'static, <Codec as Encoder>::Item: 'static,
@@ -98,16 +109,16 @@ where
} }
/// Provide stream items handler service and construct service factory. /// Provide stream items handler service and construct service factory.
pub fn finish<F, T>(self, service: F) -> FramedServiceImpl<St, C, T, Io, Codec> pub fn finish<F, T>(self, service: F) -> FramedServiceImpl<St, C, T, Io, Codec, Err>
where where
F: IntoServiceFactory<T>, F: IntoServiceFactory<T>,
T: ServiceFactory< T: ServiceFactory<
Config = St, Config = St,
Request = RequestItem<St, Codec>, Request = RequestItem<St, Codec, Err>,
Response = ResponseItem<Codec>, Response = ResponseItem<Codec>,
Error = C::Error, Error = Err,
InitError = C::Error, InitError = Err,
> + 'static, >,
{ {
FramedServiceImpl { FramedServiceImpl {
connect: self.connect, connect: self.connect,
@@ -118,22 +129,23 @@ where
} }
} }
pub struct NewServiceBuilder<St, C, Io, Codec> { pub struct NewServiceBuilder<St, C, Io, Codec, Err> {
connect: C, connect: C,
disconnect: Option<Rc<dyn Fn(&mut St, bool)>>, disconnect: Option<Rc<dyn Fn(&mut St, bool)>>,
_t: PhantomData<(St, Io, Codec)>, _t: PhantomData<(St, Io, Codec, Err)>,
} }
impl<St, C, Io, Codec> NewServiceBuilder<St, C, Io, Codec> impl<St, C, Io, Codec, Err> NewServiceBuilder<St, C, Io, Codec, Err>
where where
St: Clone, St: Clone,
Io: AsyncRead + AsyncWrite, Io: AsyncRead + AsyncWrite,
Err: 'static,
C: ServiceFactory< C: ServiceFactory<
Config = (), Config = (),
Request = Connect<Io>, Request = Connect<Io, Codec, Err>,
Response = ConnectResult<Io, St, Codec>, Response = ConnectResult<Io, St, Codec, Err>,
Error = Err,
>, >,
C::Error: 'static,
C::Future: 'static, C::Future: 'static,
Codec: Decoder + Encoder, Codec: Decoder + Encoder,
<Codec as Encoder>::Item: 'static, <Codec as Encoder>::Item: 'static,
@@ -150,15 +162,15 @@ where
self self
} }
pub fn finish<F, T, Cfg>(self, service: F) -> FramedService<St, C, T, Io, Codec, Cfg> pub fn finish<F, T, Cfg>(self, service: F) -> FramedService<St, C, T, Io, Codec, Err, Cfg>
where where
F: IntoServiceFactory<T>, F: IntoServiceFactory<T>,
T: ServiceFactory< T: ServiceFactory<
Config = St, Config = St,
Request = RequestItem<St, Codec>, Request = RequestItem<St, Codec, Err>,
Response = ResponseItem<Codec>, Response = ResponseItem<Codec>,
Error = C::Error, Error = Err,
InitError = C::Error, InitError = Err,
> + 'static, > + 'static,
{ {
FramedService { FramedService {
@@ -170,32 +182,34 @@ where
} }
} }
pub struct FramedService<St, C, T, Io, Codec, Cfg> { pub struct FramedService<St, C, T, Io, Codec, Err, Cfg> {
connect: C, connect: C,
handler: Rc<T>, handler: Rc<T>,
disconnect: Option<Rc<dyn Fn(&mut St, bool)>>, disconnect: Option<Rc<dyn Fn(&mut St, bool)>>,
_t: PhantomData<(St, Io, Codec, Cfg)>, _t: PhantomData<(St, Io, Codec, Err, Cfg)>,
} }
impl<St, C, T, Io, Codec, Cfg> ServiceFactory for FramedService<St, C, T, Io, Codec, Cfg> impl<St, C, T, Io, Codec, Err, Cfg> ServiceFactory
for FramedService<St, C, T, Io, Codec, Err, Cfg>
where where
St: Clone + 'static, St: Clone + 'static,
Io: AsyncRead + AsyncWrite, Io: AsyncRead + AsyncWrite,
C: ServiceFactory< C: ServiceFactory<
Config = (), Config = (),
Request = Connect<Io>, Request = Connect<Io, Codec, Err>,
Response = ConnectResult<Io, St, Codec>, Response = ConnectResult<Io, St, Codec, Err>,
Error = Err,
>, >,
C::Error: 'static,
C::Future: 'static, C::Future: 'static,
T: ServiceFactory< T: ServiceFactory<
Config = St, Config = St,
Request = RequestItem<St, Codec>, Request = RequestItem<St, Codec, Err>,
Response = ResponseItem<Codec>, Response = ResponseItem<Codec>,
Error = C::Error, Error = Err,
InitError = C::Error, InitError = Err,
> + 'static, > + 'static,
<T::Service as Service>::Future: 'static, <T::Service as Service>::Future: 'static,
Err: 'static,
Codec: Decoder + Encoder, Codec: Decoder + Encoder,
<Codec as Encoder>::Item: 'static, <Codec as Encoder>::Item: 'static,
<Codec as Encoder>::Error: std::fmt::Debug, <Codec as Encoder>::Error: std::fmt::Debug,
@@ -205,7 +219,7 @@ where
type Response = (); type Response = ();
type Error = ServiceError<C::Error, Codec>; type Error = ServiceError<C::Error, Codec>;
type InitError = C::InitError; type InitError = C::InitError;
type Service = FramedServiceImpl<St, C::Service, T, Io, Codec>; type Service = FramedServiceImpl<St, C::Service, T, Io, Codec, Err>;
type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>; type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>;
fn new_service(&self, _: Cfg) -> Self::Future { fn new_service(&self, _: Cfg) -> Self::Future {
@@ -227,25 +241,29 @@ where
} }
} }
pub struct FramedServiceImpl<St, C, T, Io, Codec> { pub struct FramedServiceImpl<St, C, T, Io, Codec, Err> {
connect: C, connect: C,
handler: Rc<T>, handler: Rc<T>,
disconnect: Option<Rc<dyn Fn(&mut St, bool)>>, disconnect: Option<Rc<dyn Fn(&mut St, bool)>>,
_t: PhantomData<(St, Io, Codec)>, _t: PhantomData<(St, Io, Codec, Err)>,
} }
impl<St, C, T, Io, Codec> Service for FramedServiceImpl<St, C, T, Io, Codec> impl<St, C, T, Io, Codec, Err> Service for FramedServiceImpl<St, C, T, Io, Codec, Err>
where where
St: Clone, St: Clone,
Io: AsyncRead + AsyncWrite, Io: AsyncRead + AsyncWrite,
C: Service<Request = Connect<Io>, Response = ConnectResult<Io, St, Codec>>, C: Service<
C::Error: 'static, Request = Connect<Io, Codec, Err>,
Response = ConnectResult<Io, St, Codec, Err>,
Error = Err,
>,
Err: 'static,
T: ServiceFactory< T: ServiceFactory<
Config = St, Config = St,
Request = RequestItem<St, Codec>, Request = RequestItem<St, Codec, Err>,
Response = ResponseItem<Codec>, Response = ResponseItem<Codec>,
Error = C::Error, Error = Err,
InitError = C::Error, InitError = Err,
>, >,
<T::Service as Service>::Future: 'static, <T::Service as Service>::Future: 'static,
Codec: Decoder + Encoder, Codec: Decoder + Encoder,
@@ -254,36 +272,43 @@ where
{ {
type Request = Io; type Request = Io;
type Response = (); type Response = ();
type Error = ServiceError<C::Error, Codec>; type Error = ServiceError<Err, Codec>;
type Future = FramedServiceImplResponse<St, Io, Codec, C, T>; type Future = FramedServiceImplResponse<St, Io, Codec, Err, C, T>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.connect.poll_ready(cx).map_err(|e| e.into()) self.connect.poll_ready(cx).map_err(|e| e.into())
} }
fn call(&mut self, req: Io) -> Self::Future { fn call(&mut self, req: Io) -> Self::Future {
let (tx, rx) = mpsc::channel();
let sink = Sink::new(tx);
FramedServiceImplResponse { FramedServiceImplResponse {
inner: FramedServiceImplResponseInner::Connect( inner: FramedServiceImplResponseInner::Connect(
self.connect.call(Connect::new(req)), self.connect.call(Connect::new(req, sink.clone())),
self.handler.clone(), self.handler.clone(),
self.disconnect.clone(), self.disconnect.clone(),
Some(rx),
), ),
} }
} }
} }
#[pin_project::pin_project] #[pin_project::pin_project]
pub struct FramedServiceImplResponse<St, Io, Codec, C, T> pub struct FramedServiceImplResponse<St, Io, Codec, Err, C, T>
where where
St: Clone, St: Clone,
C: Service<Request = Connect<Io>, Response = ConnectResult<Io, St, Codec>>, C: Service<
C::Error: 'static, Request = Connect<Io, Codec, Err>,
Response = ConnectResult<Io, St, Codec, Err>,
Error = Err,
>,
Err: 'static,
T: ServiceFactory< T: ServiceFactory<
Config = St, Config = St,
Request = RequestItem<St, Codec>, Request = RequestItem<St, Codec, Err>,
Response = ResponseItem<Codec>, Response = ResponseItem<Codec>,
Error = C::Error, Error = Err,
InitError = C::Error, InitError = Err,
>, >,
<T::Service as Service>::Future: 'static, <T::Service as Service>::Future: 'static,
Io: AsyncRead + AsyncWrite, Io: AsyncRead + AsyncWrite,
@@ -292,20 +317,24 @@ where
<Codec as Encoder>::Error: std::fmt::Debug, <Codec as Encoder>::Error: std::fmt::Debug,
{ {
#[pin] #[pin]
inner: FramedServiceImplResponseInner<St, Io, Codec, C, T>, inner: FramedServiceImplResponseInner<St, Io, Codec, Err, C, T>,
} }
impl<St, Io, Codec, C, T> Future for FramedServiceImplResponse<St, Io, Codec, C, T> impl<St, Io, Codec, Err, C, T> Future for FramedServiceImplResponse<St, Io, Codec, Err, C, T>
where where
St: Clone, St: Clone,
C: Service<Request = Connect<Io>, Response = ConnectResult<Io, St, Codec>>, C: Service<
C::Error: 'static, Request = Connect<Io, Codec, Err>,
Response = ConnectResult<Io, St, Codec, Err>,
Error = Err,
>,
Err: 'static,
T: ServiceFactory< T: ServiceFactory<
Config = St, Config = St,
Request = RequestItem<St, Codec>, Request = RequestItem<St, Codec, Err>,
Response = ResponseItem<Codec>, Response = ResponseItem<Codec>,
Error = C::Error, Error = Err,
InitError = C::Error, InitError = Err,
>, >,
<T::Service as Service>::Future: 'static, <T::Service as Service>::Future: 'static,
Io: AsyncRead + AsyncWrite, Io: AsyncRead + AsyncWrite,
@@ -313,7 +342,7 @@ where
<Codec as Encoder>::Item: 'static, <Codec as Encoder>::Item: 'static,
<Codec as Encoder>::Error: std::fmt::Debug, <Codec as Encoder>::Error: std::fmt::Debug,
{ {
type Output = Result<(), ServiceError<C::Error, Codec>>; type Output = Result<(), ServiceError<Err, Codec>>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut this = self.as_mut().project(); let mut this = self.as_mut().project();
@@ -331,17 +360,21 @@ where
} }
#[pin_project::pin_project] #[pin_project::pin_project]
enum FramedServiceImplResponseInner<St, Io, Codec, C, T> enum FramedServiceImplResponseInner<St, Io, Codec, Err, C, T>
where where
St: Clone, St: Clone,
C: Service<Request = Connect<Io>, Response = ConnectResult<Io, St, Codec>>, C: Service<
C::Error: 'static, Request = Connect<Io, Codec, Err>,
Response = ConnectResult<Io, St, Codec, Err>,
Error = Err,
>,
Err: 'static,
T: ServiceFactory< T: ServiceFactory<
Config = St, Config = St,
Request = RequestItem<St, Codec>, Request = RequestItem<St, Codec, Err>,
Response = ResponseItem<Codec>, Response = ResponseItem<Codec>,
Error = C::Error, Error = Err,
InitError = C::Error, InitError = Err,
>, >,
<T::Service as Service>::Future: 'static, <T::Service as Service>::Future: 'static,
Io: AsyncRead + AsyncWrite, Io: AsyncRead + AsyncWrite,
@@ -349,26 +382,36 @@ where
<Codec as Encoder>::Item: 'static, <Codec as Encoder>::Item: 'static,
<Codec as Encoder>::Error: std::fmt::Debug, <Codec as Encoder>::Error: std::fmt::Debug,
{ {
Connect(#[pin] C::Future, Rc<T>, Option<Rc<dyn Fn(&mut St, bool)>>), Connect(
#[pin] C::Future,
Rc<T>,
Option<Rc<dyn Fn(&mut St, bool)>>,
Option<mpsc::Receiver<ServiceResult<Codec, Err>>>,
),
Handler( Handler(
#[pin] T::Future, #[pin] T::Future,
Option<ConnectResult<Io, St, Codec>>, Option<ConnectResult<Io, St, Codec, Err>>,
Option<Rc<dyn Fn(&mut St, bool)>>, Option<Rc<dyn Fn(&mut St, bool)>>,
Option<mpsc::Receiver<ServiceResult<Codec, Err>>>,
), ),
Dispatcher(#[pin] FramedDispatcher<St, T::Service, Io, Codec>), Dispatcher(Dispatcher<St, T::Service, Io, Codec, Err>),
} }
impl<St, Io, Codec, C, T> FramedServiceImplResponseInner<St, Io, Codec, C, T> impl<St, Io, Codec, Err, C, T> FramedServiceImplResponseInner<St, Io, Codec, Err, C, T>
where where
St: Clone, St: Clone,
C: Service<Request = Connect<Io>, Response = ConnectResult<Io, St, Codec>>, C: Service<
C::Error: 'static, Request = Connect<Io, Codec, Err>,
Response = ConnectResult<Io, St, Codec, Err>,
Error = Err,
>,
Err: 'static,
T: ServiceFactory< T: ServiceFactory<
Config = St, Config = St,
Request = RequestItem<St, Codec>, Request = RequestItem<St, Codec, Err>,
Response = ResponseItem<Codec>, Response = ResponseItem<Codec>,
Error = C::Error, Error = Err,
InitError = C::Error, InitError = Err,
>, >,
<T::Service as Service>::Future: 'static, <T::Service as Service>::Future: 'static,
Io: AsyncRead + AsyncWrite, Io: AsyncRead + AsyncWrite,
@@ -381,42 +424,44 @@ where
self: Pin<&mut Self>, self: Pin<&mut Self>,
cx: &mut Context<'_>, cx: &mut Context<'_>,
) -> Either< ) -> Either<
FramedServiceImplResponseInner<St, Io, Codec, C, T>, FramedServiceImplResponseInner<St, Io, Codec, Err, C, T>,
Poll<Result<(), ServiceError<C::Error, Codec>>>, Poll<Result<(), ServiceError<Err, Codec>>>,
> { > {
#[project] #[project]
match self.project() { match self.project() {
FramedServiceImplResponseInner::Connect(fut, handler, disconnect) => { FramedServiceImplResponseInner::Connect(fut, handler, disconnect, rx) => {
match fut.poll(cx) { match fut.poll(cx) {
Poll::Ready(Ok(res)) => { Poll::Ready(Ok(res)) => {
Either::Left(FramedServiceImplResponseInner::Handler( Either::Left(FramedServiceImplResponseInner::Handler(
handler.new_service(res.state.clone()), handler.new_service(res.state.clone()),
Some(res), Some(res),
disconnect.take(), disconnect.take(),
rx.take(),
)) ))
} }
Poll::Pending => Either::Right(Poll::Pending), Poll::Pending => Either::Right(Poll::Pending),
Poll::Ready(Err(e)) => Either::Right(Poll::Ready(Err(e.into()))), Poll::Ready(Err(e)) => Either::Right(Poll::Ready(Err(e.into()))),
} }
} }
FramedServiceImplResponseInner::Handler(fut, res, disconnect) => match fut.poll(cx) FramedServiceImplResponseInner::Handler(fut, res, disconnect, rx) => {
{ match fut.poll(cx) {
Poll::Ready(Ok(handler)) => { Poll::Ready(Ok(handler)) => {
let res = res.take().unwrap(); let res = res.take().unwrap();
Either::Left(FramedServiceImplResponseInner::Dispatcher( Either::Left(FramedServiceImplResponseInner::Dispatcher(
FramedDispatcher::new( Dispatcher::new(
res.framed, res.framed,
res.state, res.state,
handler, handler,
res.rx,
res.sink, res.sink,
rx.take().unwrap(),
disconnect.take(), disconnect.take(),
), ),
)) ))
} }
Poll::Pending => Either::Right(Poll::Pending), Poll::Pending => Either::Right(Poll::Pending),
Poll::Ready(Err(e)) => Either::Right(Poll::Ready(Err(e.into()))), Poll::Ready(Err(e)) => Either::Right(Poll::Ready(Err(e.into()))),
}, }
}
FramedServiceImplResponseInner::Dispatcher(ref mut fut) => { FramedServiceImplResponseInner::Dispatcher(ref mut fut) => {
Either::Right(fut.poll(cx)) Either::Right(fut.poll(cx))
} }

View File

@@ -3,41 +3,41 @@ use std::fmt;
use actix_utils::{mpsc, oneshot}; use actix_utils::{mpsc, oneshot};
use futures::future::{Future, FutureExt}; use futures::future::{Future, FutureExt};
use crate::dispatcher::FramedMessage; use crate::dispatcher::Message;
pub struct Sink<T>(mpsc::Sender<FramedMessage<T>>); pub struct Sink<T, E>(mpsc::Sender<Result<Message<T>, E>>);
impl<T> Clone for Sink<T> { impl<T, E> Clone for Sink<T, E> {
fn clone(&self) -> Self { fn clone(&self) -> Self {
Sink(self.0.clone()) Sink(self.0.clone())
} }
} }
impl<T> Sink<T> { impl<T, E> Sink<T, E> {
pub(crate) fn new(tx: mpsc::Sender<FramedMessage<T>>) -> Self { pub(crate) fn new(tx: mpsc::Sender<Result<Message<T>, E>>) -> Self {
Sink(tx) Sink(tx)
} }
/// Close connection /// Close connection
pub fn close(&self) { pub fn close(&self) {
let _ = self.0.send(FramedMessage::Close); let _ = self.0.send(Ok(Message::Close));
} }
/// Close connection /// Close connection
pub fn wait_close(&self) -> impl Future<Output = ()> { pub fn wait_close(&self) -> impl Future<Output = ()> {
let (tx, rx) = oneshot::channel(); let (tx, rx) = oneshot::channel();
let _ = self.0.send(FramedMessage::WaitClose(tx)); let _ = self.0.send(Ok(Message::WaitClose(tx)));
rx.map(|_| ()) rx.map(|_| ())
} }
/// Send item /// Send item
pub fn send(&self, item: T) { pub fn send(&self, item: T) {
let _ = self.0.send(FramedMessage::Message(item)); let _ = self.0.send(Ok(Message::Item(item)));
} }
} }
impl<T> fmt::Debug for Sink<T> { impl<T, E> fmt::Debug for Sink<T, E> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct("Sink").finish() fmt.debug_struct("Sink").finish()
} }

View File

@@ -22,7 +22,7 @@ async fn test_disconnect() -> std::io::Result<()> {
let disconnect1 = disconnect1.clone(); let disconnect1 = disconnect1.clone();
Builder::new() Builder::new()
.factory(fn_service(|conn: Connect<_>| { .factory(fn_service(|conn: Connect<_, _, _>| {
ok(conn.codec(BytesCodec).state(State)) ok(conn.codec(BytesCodec).state(State))
})) }))
.disconnect(move |_, _| { .disconnect(move |_, _| {
@@ -32,7 +32,7 @@ async fn test_disconnect() -> std::io::Result<()> {
}); });
let mut client = Builder::new() let mut client = Builder::new()
.service(|conn: Connect<_>| { .service(|conn: Connect<_, _, _>| {
let conn = conn.codec(BytesCodec).state(State); let conn = conn.codec(BytesCodec).state(State);
conn.sink().close(); conn.sink().close();
ok(conn) ok(conn)

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "actix-macros" name = "actix-macros"
version = "0.1.0-alpha.1" version = "0.1.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix runtime macros" description = "Actix runtime macros"
repository = "https://github.com/actix/actix-net" repository = "https://github.com/actix/actix-net"
@@ -18,4 +18,4 @@ quote = "^1"
syn = { version = "^1", features = ["full"] } syn = { version = "^1", features = ["full"] }
[dev-dependencies] [dev-dependencies]
actix-rt = { version = "1.0.0-alpha.1" } actix-rt = { version = "1.0.0" }

View File

@@ -1,5 +1,9 @@
# Changes # Changes
## [1.0.0] - 2019-12-11
* Update dependencies
## [1.0.0-alpha.3] - 2019-12-07 ## [1.0.0-alpha.3] - 2019-12-07
### Fixed ### Fixed

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "actix-rt" name = "actix-rt"
version = "1.0.0-alpha.3" version = "1.0.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix runtime" description = "Actix runtime"
keywords = ["network", "framework", "async", "futures"] keywords = ["network", "framework", "async", "futures"]
@@ -9,7 +9,6 @@ repository = "https://github.com/actix/actix-net.git"
documentation = "https://docs.rs/actix-rt/" documentation = "https://docs.rs/actix-rt/"
categories = ["network-programming", "asynchronous"] categories = ["network-programming", "asynchronous"]
license = "MIT/Apache-2.0" license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
edition = "2018" edition = "2018"
workspace = ".." workspace = ".."
@@ -18,7 +17,7 @@ name = "actix_rt"
path = "src/lib.rs" path = "src/lib.rs"
[dependencies] [dependencies]
actix-macros = "0.1.0-alpha.1" actix-macros = "0.1.0"
actix-threadpool = "0.3" actix-threadpool = "0.3"
futures = "0.3.1" futures = "0.3.1"
copyless = "0.1.4" copyless = "0.1.4"

View File

@@ -1,5 +1,12 @@
# Changes # Changes
## [1.0.0] - 2019-12-11
### Changed
* Use actix-net releases
## [1.0.0-alpha.4] - 2019-12-08 ## [1.0.0-alpha.4] - 2019-12-08
### Changed ### Changed

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "actix-server" name = "actix-server"
version = "1.0.0-alpha.4" version = "1.0.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix server - General purpose tcp server" description = "Actix server - General purpose tcp server"
keywords = ["network", "framework", "async", "futures"] keywords = ["network", "framework", "async", "futures"]
@@ -21,13 +21,13 @@ path = "src/lib.rs"
default = [] default = []
[dependencies] [dependencies]
actix-service = "1.0.0-alpha.4" actix-service = "1.0.0"
actix-rt = "1.0.0-alpha.3" actix-rt = "1.0.0"
actix-codec = "0.2.0" actix-codec = "0.2.0"
actix-utils = "1.0.0-alpha.3" actix-utils = "1.0.0"
log = "0.4" log = "0.4"
num_cpus = "1.0" num_cpus = "1.11"
mio = "0.6.19" mio = "0.6.19"
net2 = "0.2" net2 = "0.2"
futures = "0.3.1" futures = "0.3.1"
@@ -39,4 +39,4 @@ mio-uds = { version = "0.6.7" }
[dev-dependencies] [dev-dependencies]
bytes = "0.5" bytes = "0.5"
env_logger = "0.6" env_logger = "0.6"
actix-testing = "1.0.0-alpha.3" actix-testing = "1.0.0"

View File

@@ -26,4 +26,4 @@ futures-util = "0.3.1"
pin-project = "0.4.6" pin-project = "0.4.6"
[dev-dependencies] [dev-dependencies]
actix-rt = "1.0.0-alpha.3" actix-rt = "1.0.0"

View File

@@ -1,5 +1,9 @@
# Changes # Changes
## [1.0.0] - 2019-12-11
* Update actix-server to 1.0.0
## [1.0.0-alpha.3] - 2019-12-07 ## [1.0.0-alpha.3] - 2019-12-07
* Migrate to tokio 0.2 * Migrate to tokio 0.2

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "actix-testing" name = "actix-testing"
version = "1.0.0-alpha.3" version = "1.0.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix testing utils" description = "Actix testing utils"
keywords = ["network", "framework", "async", "futures"] keywords = ["network", "framework", "async", "futures"]
@@ -17,10 +17,10 @@ name = "actix_testing"
path = "src/lib.rs" path = "src/lib.rs"
[dependencies] [dependencies]
actix-rt = "1.0.0-alpha.3" actix-rt = "1.0.0"
actix-macros = "0.1.0-alpha.1" actix-macros = "0.1.0"
actix-server = "1.0.0-alpha.3" actix-server = "1.0.0"
actix-service = "1.0.0-alpha.3" actix-service = "1.0.0"
log = "0.4" log = "0.4"
net2 = "0.2" net2 = "0.2"

View File

@@ -32,10 +32,10 @@ rustls = ["rust-tls", "webpki", "webpki-roots", "tokio-rustls"]
nativetls = ["native-tls", "tokio-tls"] nativetls = ["native-tls", "tokio-tls"]
[dependencies] [dependencies]
actix-service = "1.0.0-alpha.3" actix-service = "1.0.0"
actix-codec = "0.2.0" actix-codec = "0.2.0"
actix-utils = "1.0.0-alpha.3" actix-utils = "1.0.0"
actix-rt = "1.0.0-alpha.3" actix-rt = "1.0.0"
derive_more = "0.99.2" derive_more = "0.99.2"
either = "1.5.2" either = "1.5.2"
futures = "0.3.1" futures = "0.3.1"
@@ -57,4 +57,4 @@ tokio-tls = { version="0.3", optional = true }
[dev-dependencies] [dev-dependencies]
bytes = "0.5" bytes = "0.5"
actix-testing = { version="1.0.0-alpha.3" } actix-testing = { version="1.0.0" }

View File

@@ -1,5 +1,9 @@
# Changes # Changes
## [1.0.0] - 2019-12-11
* Simplify oneshot and mpsc implementations
## [1.0.0-alpha.3] - 2019-12-07 ## [1.0.0-alpha.3] - 2019-12-07
* Migrate to tokio 0.2 * Migrate to tokio 0.2

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "actix-utils" name = "actix-utils"
version = "1.0.0-alpha.3" version = "1.0.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix utils - various actix net related services" description = "Actix utils - various actix net related services"
keywords = ["network", "framework", "async", "futures"] keywords = ["network", "framework", "async", "futures"]
@@ -9,7 +9,6 @@ repository = "https://github.com/actix/actix-net.git"
documentation = "https://docs.rs/actix-utils/" documentation = "https://docs.rs/actix-utils/"
categories = ["network-programming", "asynchronous"] categories = ["network-programming", "asynchronous"]
license = "MIT/Apache-2.0" license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
edition = "2018" edition = "2018"
workspace = ".." workspace = ".."
@@ -18,8 +17,8 @@ name = "actix_utils"
path = "src/lib.rs" path = "src/lib.rs"
[dependencies] [dependencies]
actix-service = "1.0.0-alpha.3" actix-service = "1.0.0"
actix-rt = "1.0.0-alpha.3" actix-rt = "1.0.0"
actix-codec = "0.2.0" actix-codec = "0.2.0"
bytes = "0.5.2" bytes = "0.5.2"
either = "1.5.2" either = "1.5.2"

View File

@@ -2,16 +2,12 @@
use std::cell::UnsafeCell; use std::cell::UnsafeCell;
use std::fmt; use std::fmt;
use std::rc::{Rc, Weak}; use std::rc::Rc;
pub(crate) struct Cell<T> { pub(crate) struct Cell<T> {
pub(crate) inner: Rc<UnsafeCell<T>>, pub(crate) inner: Rc<UnsafeCell<T>>,
} }
pub(crate) struct WeakCell<T> {
inner: Weak<UnsafeCell<T>>,
}
impl<T> Clone for Cell<T> { impl<T> Clone for Cell<T> {
fn clone(&self) -> Self { fn clone(&self) -> Self {
Self { Self {
@@ -27,39 +23,26 @@ impl<T: fmt::Debug> fmt::Debug for Cell<T> {
} }
impl<T> Cell<T> { impl<T> Cell<T> {
pub fn new(inner: T) -> Self { pub(crate) fn new(inner: T) -> Self {
Self { Self {
inner: Rc::new(UnsafeCell::new(inner)), inner: Rc::new(UnsafeCell::new(inner)),
} }
} }
pub fn downgrade(&self) -> WeakCell<T> { pub(crate) fn strong_count(&self) -> usize {
WeakCell { Rc::strong_count(&self.inner)
inner: Rc::downgrade(&self.inner),
}
} }
pub fn get_ref(&self) -> &T { pub(crate) fn get_ref(&self) -> &T {
unsafe { &*self.inner.as_ref().get() } unsafe { &*self.inner.as_ref().get() }
} }
pub fn get_mut(&mut self) -> &mut T { pub(crate) fn get_mut(&mut self) -> &mut T {
unsafe { &mut *self.inner.as_ref().get() } unsafe { &mut *self.inner.as_ref().get() }
} }
}
impl<T> WeakCell<T> { #[allow(clippy::mut_from_ref)]
pub fn upgrade(&self) -> Option<Cell<T>> { pub(crate) unsafe fn get_mut_unsafe(&self) -> &mut T {
if let Some(inner) = self.inner.upgrade() { &mut *self.inner.as_ref().get()
Some(Cell { inner })
} else {
None
}
}
}
impl<T: fmt::Debug> fmt::Debug for WeakCell<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.inner.fmt(f)
} }
} }

View File

@@ -1,37 +1,33 @@
//! Framed dispatcher service and related utilities //! Framed dispatcher service and related utilities
#![allow(type_alias_bounds)] #![allow(type_alias_bounds)]
use std::collections::VecDeque;
use std::pin::Pin; use std::pin::Pin;
use std::task::{Context, Poll}; use std::task::{Context, Poll};
use std::{fmt, mem}; use std::{fmt, mem};
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed}; use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
use actix_service::{IntoService, Service}; use actix_service::{IntoService, Service};
use futures::future::{ready, FutureExt}; use futures::{Future, FutureExt, Stream};
use futures::{Future, Sink, Stream};
use log::debug; use log::debug;
use crate::cell::Cell;
use crate::mpsc; use crate::mpsc;
use crate::task::LocalWaker;
type Request<U> = <U as Decoder>::Item; type Request<U> = <U as Decoder>::Item;
type Response<U> = <U as Encoder>::Item; type Response<U> = <U as Encoder>::Item;
/// Framed transport errors /// Framed transport errors
pub enum FramedTransportError<E, U: Encoder + Decoder> { pub enum DispatcherError<E, U: Encoder + Decoder> {
Service(E), Service(E),
Encoder(<U as Encoder>::Error), Encoder(<U as Encoder>::Error),
Decoder(<U as Decoder>::Error), Decoder(<U as Decoder>::Error),
} }
impl<E, U: Encoder + Decoder> From<E> for FramedTransportError<E, U> { impl<E, U: Encoder + Decoder> From<E> for DispatcherError<E, U> {
fn from(err: E) -> Self { fn from(err: E) -> Self {
FramedTransportError::Service(err) DispatcherError::Service(err)
} }
} }
impl<E, U: Encoder + Decoder> fmt::Debug for FramedTransportError<E, U> impl<E, U: Encoder + Decoder> fmt::Debug for DispatcherError<E, U>
where where
E: fmt::Debug, E: fmt::Debug,
<U as Encoder>::Error: fmt::Debug, <U as Encoder>::Error: fmt::Debug,
@@ -39,20 +35,14 @@ where
{ {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self { match *self {
FramedTransportError::Service(ref e) => { DispatcherError::Service(ref e) => write!(fmt, "DispatcherError::Service({:?})", e),
write!(fmt, "FramedTransportError::Service({:?})", e) DispatcherError::Encoder(ref e) => write!(fmt, "DispatcherError::Encoder({:?})", e),
} DispatcherError::Decoder(ref e) => write!(fmt, "DispatcherError::Decoder({:?})", e),
FramedTransportError::Encoder(ref e) => {
write!(fmt, "FramedTransportError::Encoder({:?})", e)
}
FramedTransportError::Decoder(ref e) => {
write!(fmt, "FramedTransportError::Encoder({:?})", e)
}
} }
} }
} }
impl<E, U: Encoder + Decoder> fmt::Display for FramedTransportError<E, U> impl<E, U: Encoder + Decoder> fmt::Display for DispatcherError<E, U>
where where
E: fmt::Display, E: fmt::Display,
<U as Encoder>::Error: fmt::Debug, <U as Encoder>::Error: fmt::Debug,
@@ -60,25 +50,22 @@ where
{ {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self { match *self {
FramedTransportError::Service(ref e) => write!(fmt, "{}", e), DispatcherError::Service(ref e) => write!(fmt, "{}", e),
FramedTransportError::Encoder(ref e) => write!(fmt, "{:?}", e), DispatcherError::Encoder(ref e) => write!(fmt, "{:?}", e),
FramedTransportError::Decoder(ref e) => write!(fmt, "{:?}", e), DispatcherError::Decoder(ref e) => write!(fmt, "{:?}", e),
} }
} }
} }
pub enum FramedMessage<T> { pub enum Message<T> {
Message(T), Item(T),
Close, Close,
} }
type Rx<U> = Option<mpsc::Receiver<FramedMessage<<U as Encoder>::Item>>>;
type Inner<S: Service, U> = Cell<FramedTransportInner<<U as Encoder>::Item, S::Error>>;
/// FramedTransport - is a future that reads frames from Framed object /// FramedTransport - is a future that reads frames from Framed object
/// and pass then to the service. /// and pass then to the service.
#[pin_project::pin_project] #[pin_project::pin_project]
pub struct FramedTransport<S, T, U> pub struct Dispatcher<S, T, U>
where where
S: Service<Request = Request<U>, Response = Response<U>>, S: Service<Request = Request<U>, Response = Response<U>>,
S::Error: 'static, S::Error: 'static,
@@ -89,26 +76,37 @@ where
<U as Encoder>::Error: std::fmt::Debug, <U as Encoder>::Error: std::fmt::Debug,
{ {
service: S, service: S,
state: TransportState<S, U>, state: State<S, U>,
framed: Framed<T, U>, framed: Framed<T, U>,
rx: Option<mpsc::Receiver<FramedMessage<<U as Encoder>::Item>>>, rx: mpsc::Receiver<Result<Message<<U as Encoder>::Item>, S::Error>>,
inner: Cell<FramedTransportInner<<U as Encoder>::Item, S::Error>>, tx: mpsc::Sender<Result<Message<<U as Encoder>::Item>, S::Error>>,
} }
enum TransportState<S: Service, U: Encoder + Decoder> { enum State<S: Service, U: Encoder + Decoder> {
Processing, Processing,
Error(FramedTransportError<S::Error, U>), Error(DispatcherError<S::Error, U>),
FramedError(FramedTransportError<S::Error, U>), FramedError(DispatcherError<S::Error, U>),
FlushAndStop, FlushAndStop,
Stopping, Stopping,
} }
struct FramedTransportInner<I, E> { impl<S: Service, U: Encoder + Decoder> State<S, U> {
buf: VecDeque<Result<I, E>>, fn take_error(&mut self) -> DispatcherError<S::Error, U> {
task: LocalWaker, match mem::replace(self, State::Processing) {
State::Error(err) => err,
_ => panic!(),
}
} }
impl<S, T, U> FramedTransport<S, T, U> fn take_framed_error(&mut self) -> DispatcherError<S::Error, U> {
match mem::replace(self, State::Processing) {
State::FramedError(err) => err,
_ => panic!(),
}
}
}
impl<S, T, U> Dispatcher<S, T, U>
where where
S: Service<Request = Request<U>, Response = Response<U>>, S: Service<Request = Request<U>, Response = Response<U>>,
S::Error: 'static, S::Error: 'static,
@@ -119,25 +117,19 @@ where
<U as Encoder>::Error: std::fmt::Debug, <U as Encoder>::Error: std::fmt::Debug,
{ {
pub fn new<F: IntoService<S>>(framed: Framed<T, U>, service: F) -> Self { pub fn new<F: IntoService<S>>(framed: Framed<T, U>, service: F) -> Self {
FramedTransport { let (tx, rx) = mpsc::channel();
Dispatcher {
framed, framed,
rx: None, rx,
tx,
service: service.into_service(), service: service.into_service(),
state: TransportState::Processing, state: State::Processing,
inner: Cell::new(FramedTransportInner {
buf: VecDeque::new(),
task: LocalWaker::new(),
}),
} }
} }
/// Get Sender /// Get sink
pub fn set_receiver( pub fn get_sink(&self) -> mpsc::Sender<Result<Message<<U as Encoder>::Item>, S::Error>> {
mut self, self.tx.clone()
rx: mpsc::Receiver<FramedMessage<<U as Encoder>::Item>>,
) -> Self {
self.rx = Some(rx);
self
} }
/// Get reference to a service wrapped by `FramedTransport` instance. /// Get reference to a service wrapped by `FramedTransport` instance.
@@ -162,9 +154,99 @@ where
pub fn get_framed_mut(&mut self) -> &mut Framed<T, U> { pub fn get_framed_mut(&mut self) -> &mut Framed<T, U> {
&mut self.framed &mut self.framed
} }
fn poll_read(&mut self, cx: &mut Context<'_>) -> bool
where
S: Service<Request = Request<U>, Response = 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,
{
loop {
match self.service.poll_ready(cx) {
Poll::Ready(Ok(_)) => {
let item = match self.framed.next_item(cx) {
Poll::Ready(Some(Ok(el))) => el,
Poll::Ready(Some(Err(err))) => {
self.state = State::FramedError(DispatcherError::Decoder(err));
return true;
}
Poll::Pending => return false,
Poll::Ready(None) => {
self.state = State::Stopping;
return true;
}
};
let tx = self.tx.clone();
actix_rt::spawn(self.service.call(item).map(move |item| {
let _ = tx.send(item.map(Message::Item));
}));
}
Poll::Pending => return false,
Poll::Ready(Err(err)) => {
self.state = State::Error(DispatcherError::Service(err));
return true;
}
}
}
} }
impl<S, T, U> Future for FramedTransport<S, T, U> /// write to framed object
fn poll_write(&mut self, cx: &mut Context<'_>) -> bool
where
S: Service<Request = Request<U>, Response = 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,
{
loop {
while !self.framed.is_write_buf_full() {
match Pin::new(&mut self.rx).poll_next(cx) {
Poll::Ready(Some(Ok(Message::Item(msg)))) => {
if let Err(err) = self.framed.write(msg) {
self.state = State::FramedError(DispatcherError::Encoder(err));
return true;
}
}
Poll::Ready(Some(Ok(Message::Close))) => {
self.state = State::FlushAndStop;
return true;
}
Poll::Ready(Some(Err(err))) => {
self.state = State::Error(DispatcherError::Service(err));
return true;
}
Poll::Ready(None) | Poll::Pending => break,
}
}
if !self.framed.is_write_buf_empty() {
match self.framed.flush(cx) {
Poll::Pending => break,
Poll::Ready(Ok(_)) => (),
Poll::Ready(Err(err)) => {
debug!("Error sending data: {:?}", err);
self.state = State::FramedError(DispatcherError::Encoder(err));
return true;
}
}
} else {
break;
}
}
false
}
}
impl<S, T, U> Future for Dispatcher<S, T, U>
where where
S: Service<Request = Request<U>, Response = Response<U>>, S: Service<Request = Request<U>, Response = Response<U>>,
S::Error: 'static, S::Error: 'static,
@@ -175,62 +257,32 @@ where
<U as Encoder>::Error: std::fmt::Debug, <U as Encoder>::Error: std::fmt::Debug,
<U as Decoder>::Error: std::fmt::Debug, <U as Decoder>::Error: std::fmt::Debug,
{ {
type Output = Result<(), FramedTransportError<S::Error, U>>; type Output = Result<(), DispatcherError<S::Error, U>>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.inner.get_ref().task.register(cx.waker()); loop {
let this = self.as_mut().project();
let this = self.project(); return match this.state {
poll( State::Processing => {
cx, if self.poll_read(cx) || self.poll_write(cx) {
this.service, continue;
this.state,
this.framed,
this.rx,
this.inner,
)
}
}
fn poll<S, T, U>(
cx: &mut Context<'_>,
srv: &mut S,
state: &mut TransportState<S, U>,
framed: &mut Framed<T, U>,
rx: &mut Rx<U>,
inner: &mut Inner<S, U>,
) -> Poll<Result<(), FramedTransportError<S::Error, U>>>
where
S: Service<Request = Request<U>, Response = 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,
{
match mem::replace(state, TransportState::Processing) {
TransportState::Processing => {
if poll_read(cx, srv, state, framed, inner)
|| poll_write(cx, state, framed, rx, inner)
{
poll(cx, srv, state, framed, rx, inner)
} else { } else {
Poll::Pending Poll::Pending
} }
} }
TransportState::Error(err) => { State::Error(_) => {
let is_empty = framed.is_write_buf_empty(); // flush write buffer
if is_empty || poll_write(cx, state, framed, rx, inner) { if !self.framed.is_write_buf_empty() {
Poll::Ready(Err(err)) if let Poll::Pending = self.framed.flush(cx) {
} else { return Poll::Pending;
*state = TransportState::Error(err);
Poll::Pending
} }
} }
TransportState::FlushAndStop => { Poll::Ready(Err(self.state.take_error()))
if !framed.is_write_buf_empty() { }
match Pin::new(framed).poll_flush(cx) { State::FlushAndStop => {
if !this.framed.is_write_buf_empty() {
match this.framed.flush(cx) {
Poll::Ready(Err(err)) => { Poll::Ready(Err(err)) => {
debug!("Error sending data: {:?}", err); debug!("Error sending data: {:?}", err);
Poll::Ready(Ok(())) Poll::Ready(Ok(()))
@@ -242,143 +294,9 @@ where
Poll::Ready(Ok(())) Poll::Ready(Ok(()))
} }
} }
TransportState::FramedError(err) => Poll::Ready(Err(err)), State::FramedError(_) => Poll::Ready(Err(this.state.take_framed_error())),
TransportState::Stopping => Poll::Ready(Ok(())), State::Stopping => Poll::Ready(Ok(())),
}
}
fn poll_read<S, T, U>(
cx: &mut Context<'_>,
srv: &mut S,
state: &mut TransportState<S, U>,
framed: &mut Framed<T, U>,
inner: &mut Inner<S, U>,
) -> bool
where
S: Service<Request = Request<U>, Response = 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,
{
loop {
match srv.poll_ready(cx) {
Poll::Ready(Ok(_)) => {
let item = match framed.next_item(cx) {
Poll::Ready(Some(Ok(el))) => el,
Poll::Ready(Some(Err(err))) => {
*state =
TransportState::FramedError(FramedTransportError::Decoder(err));
return true;
}
Poll::Pending => return false,
Poll::Ready(None) => {
*state = TransportState::Stopping;
return true;
}
}; };
let mut cell = inner.clone();
let fut = srv.call(item).then(move |item| {
let inner = cell.get_mut();
inner.buf.push_back(item);
inner.task.wake();
ready(())
});
actix_rt::spawn(fut);
}
Poll::Pending => return false,
Poll::Ready(Err(err)) => {
*state = TransportState::Error(FramedTransportError::Service(err));
return true;
} }
} }
} }
}
/// write to framed object
fn poll_write<S, T, U>(
cx: &mut Context<'_>,
state: &mut TransportState<S, U>,
framed: &mut Framed<T, U>,
rx: &mut Rx<U>,
inner: &mut Inner<S, U>,
) -> bool
where
S: Service<Request = Request<U>, Response = 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,
{
// let this = self.project();
let inner = inner.get_mut();
let mut rx_done = rx.is_none();
let mut buf_empty = inner.buf.is_empty();
loop {
while !framed.is_write_buf_full() {
if !buf_empty {
match inner.buf.pop_front().unwrap() {
Ok(msg) => {
if let Err(err) = framed.write(msg) {
*state =
TransportState::FramedError(FramedTransportError::Encoder(err));
return true;
}
buf_empty = inner.buf.is_empty();
}
Err(err) => {
*state = TransportState::Error(FramedTransportError::Service(err));
return true;
}
}
}
if !rx_done && rx.is_some() {
match Pin::new(rx.as_mut().unwrap()).poll_next(cx) {
Poll::Ready(Some(FramedMessage::Message(msg))) => {
if let Err(err) = framed.write(msg) {
*state =
TransportState::FramedError(FramedTransportError::Encoder(err));
return true;
}
}
Poll::Ready(Some(FramedMessage::Close)) => {
*state = TransportState::FlushAndStop;
return true;
}
Poll::Ready(None) => {
rx_done = true;
let _ = rx.take();
}
Poll::Pending => rx_done = true,
}
}
if rx_done && buf_empty {
break;
}
}
if !framed.is_write_buf_empty() {
match framed.flush(cx) {
Poll::Pending => break,
Poll::Ready(Err(err)) => {
debug!("Error sending data: {:?}", err);
*state = TransportState::FramedError(FramedTransportError::Encoder(err));
return true;
}
Poll::Ready(Ok(_)) => (),
}
} else {
break;
}
}
false
}

View File

@@ -1,34 +1,27 @@
//! A multi-producer, single-consumer, futures-aware, FIFO queue with back //! A multi-producer, single-consumer, futures-aware, FIFO queue.
//! pressure, for use communicating between tasks on the same thread.
//!
//! These queues are the same as those in `futures::sync`, except they're not
//! intended to be sent across threads.
use std::any::Any; use std::any::Any;
use std::cell::RefCell;
use std::collections::VecDeque; use std::collections::VecDeque;
use std::error::Error; use std::error::Error;
use std::fmt;
use std::pin::Pin; use std::pin::Pin;
use std::rc::{Rc, Weak};
use std::task::{Context, Poll}; use std::task::{Context, Poll};
use std::{fmt, mem};
use futures::{Sink, Stream}; use futures::{Sink, Stream};
use crate::cell::Cell;
use crate::task::LocalWaker; use crate::task::LocalWaker;
/// Creates a unbounded in-memory channel with buffered storage. /// Creates a unbounded in-memory channel with buffered storage.
pub fn channel<T>() -> (Sender<T>, Receiver<T>) { pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
let shared = Rc::new(RefCell::new(Shared { let shared = Cell::new(Shared {
has_receiver: true,
buffer: VecDeque::new(), buffer: VecDeque::new(),
blocked_recv: LocalWaker::new(), blocked_recv: LocalWaker::new(),
})); });
let sender = Sender { let sender = Sender {
shared: Rc::downgrade(&shared), shared: shared.clone(),
};
let receiver = Receiver {
state: State::Open(shared),
}; };
let receiver = Receiver { shared };
(sender, receiver) (sender, receiver)
} }
@@ -36,6 +29,7 @@ pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
struct Shared<T> { struct Shared<T> {
buffer: VecDeque<T>, buffer: VecDeque<T>,
blocked_recv: LocalWaker, blocked_recv: LocalWaker,
has_receiver: bool,
} }
/// The transmission end of a channel. /// The transmission end of a channel.
@@ -43,22 +37,30 @@ struct Shared<T> {
/// This is created by the `channel` function. /// This is created by the `channel` function.
#[derive(Debug)] #[derive(Debug)]
pub struct Sender<T> { pub struct Sender<T> {
shared: Weak<RefCell<Shared<T>>>, shared: Cell<Shared<T>>,
} }
impl<T> Unpin for Sender<T> {}
impl<T> Sender<T> { impl<T> Sender<T> {
/// Sends the provided message along this channel. /// Sends the provided message along this channel.
pub fn send(&self, item: T) -> Result<(), SendError<T>> { pub fn send(&self, item: T) -> Result<(), SendError<T>> {
let shared = match self.shared.upgrade() { let shared = unsafe { self.shared.get_mut_unsafe() };
Some(shared) => shared, if !shared.has_receiver {
None => return Err(SendError(item)), // receiver was dropped return Err(SendError(item)); // receiver was dropped
}; };
let mut shared = shared.borrow_mut();
shared.buffer.push_back(item); shared.buffer.push_back(item);
shared.blocked_recv.wake(); shared.blocked_recv.wake();
Ok(()) Ok(())
} }
/// Closes the sender half
///
/// This prevents any further messages from being sent on the channel while
/// still enabling the receiver to drain messages that are buffered.
pub fn close(&mut self) {
self.shared.get_mut().has_receiver = false;
}
} }
impl<T> Clone for Sender<T> { impl<T> Clone for Sender<T> {
@@ -91,17 +93,13 @@ impl<T> Sink<T> for Sender<T> {
impl<T> Drop for Sender<T> { impl<T> Drop for Sender<T> {
fn drop(&mut self) { fn drop(&mut self) {
let shared = match self.shared.upgrade() { let count = self.shared.strong_count();
Some(shared) => shared, let shared = self.shared.get_mut();
None => return,
}; // check is last sender is about to drop
// The number of existing `Weak` indicates if we are possibly the last if shared.has_receiver && count == 2 {
// `Sender`. If we are the last, we possibly must notify a blocked
// `Receiver`. `self.shared` is always one of the `Weak` to this shared
// data. Therefore the smallest possible Rc::weak_count(&shared) is 1.
if Rc::weak_count(&shared) == 1 {
// Wake up receiver as its stream has ended // Wake up receiver as its stream has ended
shared.borrow_mut().blocked_recv.wake(); shared.blocked_recv.wake();
} }
} }
} }
@@ -111,56 +109,32 @@ impl<T> Drop for Sender<T> {
/// This is created by the `channel` function. /// This is created by the `channel` function.
#[derive(Debug)] #[derive(Debug)]
pub struct Receiver<T> { pub struct Receiver<T> {
state: State<T>, shared: Cell<Shared<T>>,
}
impl<T> Unpin for Receiver<T> {}
/// Possible states of a receiver. We're either Open (can receive more messages)
/// or we're closed with a list of messages we have left to receive.
#[derive(Debug)]
enum State<T> {
Open(Rc<RefCell<Shared<T>>>),
Closed(VecDeque<T>),
} }
impl<T> Receiver<T> { impl<T> Receiver<T> {
/// Closes the receiving half /// Create Sender
/// pub fn sender(&self) -> Sender<T> {
/// This prevents any further messages from being sent on the channel while Sender {
/// still enabling the receiver to drain messages that are buffered. shared: self.shared.clone(),
pub fn close(&mut self) {
let items = match self.state {
State::Open(ref state) => {
let mut state = state.borrow_mut();
mem::replace(&mut state.buffer, VecDeque::new())
}
State::Closed(_) => return,
};
self.state = State::Closed(items);
} }
} }
}
impl<T> Unpin for Receiver<T> {}
impl<T> Stream for Receiver<T> { impl<T> Stream for Receiver<T> {
type Item = T; type Item = T;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let me = match self.state { if self.shared.strong_count() == 1 {
State::Open(ref mut me) => me,
State::Closed(ref mut items) => return Poll::Ready(items.pop_front()),
};
if let Some(shared) = Rc::get_mut(me) {
// All senders have been dropped, so drain the buffer and end the // All senders have been dropped, so drain the buffer and end the
// stream. // stream.
return Poll::Ready(shared.borrow_mut().buffer.pop_front()); Poll::Ready(self.shared.get_mut().buffer.pop_front())
} } else if let Some(msg) = self.shared.get_mut().buffer.pop_front() {
let mut shared = me.borrow_mut();
if let Some(msg) = shared.buffer.pop_front() {
Poll::Ready(Some(msg)) Poll::Ready(Some(msg))
} else { } else {
shared.blocked_recv.register(cx.waker()); self.shared.get_mut().blocked_recv.register(cx.waker());
Poll::Pending Poll::Pending
} }
} }
@@ -168,7 +142,9 @@ impl<T> Stream for Receiver<T> {
impl<T> Drop for Receiver<T> { impl<T> Drop for Receiver<T> {
fn drop(&mut self) { fn drop(&mut self) {
self.close(); let shared = self.shared.get_mut();
shared.buffer.clear();
shared.has_receiver = false;
} }
} }
@@ -200,3 +176,44 @@ impl<T> SendError<T> {
self.0 self.0
} }
} }
#[cfg(test)]
mod tests {
use super::*;
use futures::future::lazy;
use futures::{Stream, StreamExt};
#[actix_rt::test]
async fn test_mpsc() {
let (tx, mut rx) = channel();
tx.send("test").unwrap();
assert_eq!(rx.next().await.unwrap(), "test");
let tx2 = tx.clone();
tx2.send("test2").unwrap();
assert_eq!(rx.next().await.unwrap(), "test2");
assert_eq!(
lazy(|cx| Pin::new(&mut rx).poll_next(cx)).await,
Poll::Pending
);
drop(tx2);
assert_eq!(
lazy(|cx| Pin::new(&mut rx).poll_next(cx)).await,
Poll::Pending
);
drop(tx);
assert_eq!(rx.next().await, None);
let (tx, rx) = channel();
tx.send("test").unwrap();
drop(rx);
assert!(tx.send("test").is_err());
let (mut tx, _) = channel();
let tx2 = tx.clone();
tx.close();
assert!(tx.send("test").is_err());
assert!(tx2.send("test").is_err());
}
}

View File

@@ -1,69 +1,45 @@
//! A one-shot, futures-aware channel //! A one-shot, futures-aware channel.
//!
//! This channel is similar to that in `sync::oneshot` but cannot be sent across
//! threads.
use std::future::Future; use std::future::Future;
use std::pin::Pin; use std::pin::Pin;
use std::rc::Rc;
use std::task::{Context, Poll}; use std::task::{Context, Poll};
pub use futures::channel::oneshot::Canceled; pub use futures::channel::oneshot::Canceled;
use crate::cell::{Cell, WeakCell}; use crate::cell::Cell;
use crate::task::LocalWaker; use crate::task::LocalWaker;
/// Creates a new futures-aware, one-shot channel. /// Creates a new futures-aware, one-shot channel.
///
/// This function is the same as `sync::oneshot::channel` except that the
/// returned values cannot be sent across threads.
pub fn channel<T>() -> (Sender<T>, Receiver<T>) { pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
let inner = Cell::new(Inner { let inner = Cell::new(Inner {
value: None, value: None,
rx_task: LocalWaker::new(), rx_task: LocalWaker::new(),
}); });
let tx = Sender { let tx = Sender {
inner: inner.downgrade(), inner: inner.clone(),
};
let rx = Receiver {
state: State::Open(inner),
}; };
let rx = Receiver { inner };
(tx, rx) (tx, rx)
} }
/// Represents the completion half of a oneshot through which the result of a /// Represents the completion half of a oneshot through which the result of a
/// computation is signaled. /// computation is signaled.
///
/// This is created by the `unsync::oneshot::channel` function and is equivalent
/// in functionality to `sync::oneshot::Sender` except that it cannot be sent
/// across threads.
#[derive(Debug)] #[derive(Debug)]
pub struct Sender<T> { pub struct Sender<T> {
inner: WeakCell<Inner<T>>, inner: Cell<Inner<T>>,
} }
/// A future representing the completion of a computation happening elsewhere in /// A future representing the completion of a computation happening elsewhere in
/// memory. /// memory.
///
/// This is created by the `unsync::oneshot::channel` function and is equivalent
/// in functionality to `sync::oneshot::Receiver` except that it cannot be sent
/// across threads.
#[derive(Debug)] #[derive(Debug)]
#[must_use = "futures do nothing unless polled"] #[must_use = "futures do nothing unless polled"]
pub struct Receiver<T> { pub struct Receiver<T> {
state: State<T>, inner: Cell<Inner<T>>,
} }
// The channels do not ever project Pin to the inner T // The channels do not ever project Pin to the inner T
impl<T> Unpin for Receiver<T> {} impl<T> Unpin for Receiver<T> {}
impl<T> Unpin for Sender<T> {} impl<T> Unpin for Sender<T> {}
#[derive(Debug)]
enum State<T> {
Open(Cell<Inner<T>>),
Closed(Option<T>),
}
#[derive(Debug)] #[derive(Debug)]
struct Inner<T> { struct Inner<T> {
value: Option<T>, value: Option<T>,
@@ -78,12 +54,12 @@ impl<T> Sender<T> {
/// represents. /// represents.
/// ///
/// If the value is successfully enqueued for the remote end to receive, /// If the value is successfully enqueued for the remote end to receive,
/// then `Ok(())` is returned. If the receiving end was deallocated before /// then `Ok(())` is returned. If the receiving end was dropped before
/// this function was called, however, then `Err` is returned with the value /// this function was called, however, then `Err` is returned with the value
/// provided. /// provided.
pub fn send(self, val: T) -> Result<(), T> { pub fn send(mut self, val: T) -> Result<(), T> {
if let Some(mut inner) = self.inner.upgrade() { if self.inner.strong_count() == 2 {
let inner = inner.get_mut(); let inner = self.inner.get_mut();
inner.value = Some(val); inner.value = Some(val);
inner.rx_task.wake(); inner.rx_task.wake();
Ok(()) Ok(())
@@ -91,47 +67,12 @@ impl<T> Sender<T> {
Err(val) Err(val)
} }
} }
/// Tests to see whether this `Sender`'s corresponding `Receiver`
/// has gone away.
///
/// This function can be used to learn about when the `Receiver` (consumer)
/// half has gone away and nothing will be able to receive a message sent
/// from `send`.
///
/// Note that this function is intended to *not* be used in the context of a
/// future. If you're implementing a future you probably want to call the
/// `poll_cancel` function which will block the current task if the
/// cancellation hasn't happened yet. This can be useful when working on a
/// non-futures related thread, though, which would otherwise panic if
/// `poll_cancel` were called.
pub fn is_canceled(&self) -> bool {
self.inner.upgrade().is_none()
}
} }
impl<T> Drop for Sender<T> { impl<T> Drop for Sender<T> {
fn drop(&mut self) { fn drop(&mut self) {
if let Some(inner) = self.inner.upgrade() { if self.inner.strong_count() == 2 {
inner.get_ref().rx_task.wake(); self.inner.get_ref().rx_task.wake();
};
}
}
impl<T> Receiver<T> {
/// Gracefully close this receiver, preventing sending any future messages.
///
/// Any `send` operation which happens after this method returns is
/// guaranteed to fail. Once this method is called the normal `poll` method
/// can be used to determine whether a message was actually sent or not. If
/// `Canceled` is returned from `poll` then no message was sent.
pub fn close(&mut self) {
match self.state {
State::Open(ref mut inner) => {
let value = inner.get_mut().value.take();
self.state = State::Closed(value);
}
State::Closed(_) => {}
}; };
} }
} }
@@ -142,33 +83,48 @@ impl<T> Future for Receiver<T> {
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.get_mut(); let this = self.get_mut();
let inner = match this.state {
State::Open(ref mut inner) => inner,
State::Closed(ref mut item) => match item.take() {
Some(item) => return Poll::Ready(Ok(item)),
None => return Poll::Ready(Err(Canceled)),
},
};
// If we've got a value, then skip the logic below as we're done. // If we've got a value, then skip the logic below as we're done.
if let Some(val) = inner.get_mut().value.take() { if let Some(val) = this.inner.get_mut().value.take() {
return Poll::Ready(Ok(val)); return Poll::Ready(Ok(val));
} }
// If we can get mutable access, then the sender has gone away. We // Check if sender is dropped and return error if it is.
// didn't see a value above, so we're canceled. Otherwise we park if this.inner.strong_count() == 1 {
// our task and wait for a value to come in.
if Rc::get_mut(&mut inner.inner).is_some() {
Poll::Ready(Err(Canceled)) Poll::Ready(Err(Canceled))
} else { } else {
inner.get_ref().rx_task.register(cx.waker()); this.inner.get_ref().rx_task.register(cx.waker());
Poll::Pending Poll::Pending
} }
} }
} }
impl<T> Drop for Receiver<T> { #[cfg(test)]
fn drop(&mut self) { mod tests {
self.close(); use super::*;
use futures::future::lazy;
#[actix_rt::test]
async fn test_oneshot() {
let (tx, rx) = channel();
tx.send("test").unwrap();
assert_eq!(rx.await.unwrap(), "test");
let (tx, rx) = channel();
drop(rx);
assert!(tx.send("test").is_err());
let (tx, rx) = channel::<&'static str>();
drop(tx);
assert!(rx.await.is_err());
let (tx, mut rx) = channel::<&'static str>();
assert_eq!(lazy(|cx| Pin::new(&mut rx).poll(cx)).await, Poll::Pending);
tx.send("test").unwrap();
assert_eq!(rx.await.unwrap(), "test");
let (tx, mut rx) = channel::<&'static str>();
assert_eq!(lazy(|cx| Pin::new(&mut rx).poll(cx)).await, Poll::Pending);
drop(tx);
assert!(rx.await.is_err());
} }
} }

View File

@@ -3,12 +3,12 @@ use std::pin::Pin;
use std::task::{Context, Poll}; use std::task::{Context, Poll};
use actix_service::{IntoService, Service}; use actix_service::{IntoService, Service};
use futures::Stream; use futures::{FutureExt, Stream};
use crate::mpsc; use crate::mpsc;
#[pin_project::pin_project] #[pin_project::pin_project]
pub struct StreamDispatcher<S, T> pub struct Dispatcher<S, T>
where where
S: Stream, S: Stream,
T: Service<Request = S::Item, Response = ()> + 'static, T: Service<Request = S::Item, Response = ()> + 'static,
@@ -20,7 +20,7 @@ where
err_tx: mpsc::Sender<T::Error>, err_tx: mpsc::Sender<T::Error>,
} }
impl<S, T> StreamDispatcher<S, T> impl<S, T> Dispatcher<S, T>
where where
S: Stream, S: Stream,
T: Service<Request = S::Item, Response = ()> + 'static, T: Service<Request = S::Item, Response = ()> + 'static,
@@ -30,7 +30,7 @@ where
F: IntoService<T>, F: IntoService<T>,
{ {
let (err_tx, err_rx) = mpsc::channel(); let (err_tx, err_rx) = mpsc::channel();
StreamDispatcher { Dispatcher {
err_rx, err_rx,
err_tx, err_tx,
stream, stream,
@@ -39,7 +39,7 @@ where
} }
} }
impl<S, T> Future for StreamDispatcher<S, T> impl<S, T> Future for Dispatcher<S, T>
where where
S: Stream, S: Stream,
T: Service<Request = S::Item, Response = ()> + 'static, T: Service<Request = S::Item, Response = ()> + 'static,
@@ -54,47 +54,23 @@ where
} }
loop { loop {
match this.service.poll_ready(cx)? { return match this.service.poll_ready(cx)? {
Poll::Ready(_) => match this.stream.poll_next(cx) { Poll::Ready(_) => match this.stream.poll_next(cx) {
Poll::Ready(Some(item)) => { Poll::Ready(Some(item)) => {
actix_rt::spawn(StreamDispatcherService { let stop = this.err_tx.clone();
fut: this.service.call(item), actix_rt::spawn(this.service.call(item).map(move |res| {
stop: self.err_tx.clone(), if let Err(e) = res {
}); let _ = stop.send(e);
}
}));
this = self.as_mut().project(); this = self.as_mut().project();
continue;
} }
Poll::Pending => return Poll::Pending,
Poll::Ready(None) => return Poll::Ready(Ok(())),
},
Poll::Pending => return Poll::Pending,
}
}
}
}
#[pin_project::pin_project]
struct StreamDispatcherService<F: Future, E> {
#[pin]
fut: F,
stop: mpsc::Sender<E>,
}
impl<F, E> Future for StreamDispatcherService<F, E>
where
F: Future<Output = Result<(), E>>,
{
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
match this.fut.poll(cx) {
Poll::Ready(Ok(_)) => Poll::Ready(()),
Poll::Pending => Poll::Pending, Poll::Pending => Poll::Pending,
Poll::Ready(Err(e)) => { Poll::Ready(None) => Poll::Ready(Ok(())),
let _ = this.stop.send(e); },
Poll::Ready(()) Poll::Pending => Poll::Pending,
} };
} }
} }
} }