mirror of
https://github.com/fafhrd91/actix-net
synced 2025-08-12 13:27:04 +02:00
Compare commits
14 Commits
rt-1.0.0
...
utils-v1.0
Author | SHA1 | Date | |
---|---|---|---|
|
52ecb4bcc5 | ||
|
b28f32e82c | ||
|
081205a02f | ||
|
8bb81c0768 | ||
|
c7a8743bf9 | ||
|
f26fcc703b | ||
|
ce4587df82 | ||
|
9957f28137 | ||
|
9d84d14ef4 | ||
|
60bfa1bfb1 | ||
|
2c81c22b3e | ||
|
dded482514 | ||
|
631cb86947 | ||
|
2e5e69c9ba |
@@ -1,5 +1,9 @@
|
||||
# Changes
|
||||
|
||||
## [1.0.0] - 2019-12-11
|
||||
|
||||
* Release
|
||||
|
||||
## [1.0.0-alpha.3] - 2019-12-07
|
||||
|
||||
### Changed
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-connect"
|
||||
version = "1.0.0-alpha.3"
|
||||
version = "1.0.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix connect - tcp connector service"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
@@ -9,7 +9,6 @@ repository = "https://github.com/actix/actix-net.git"
|
||||
documentation = "https://docs.rs/actix-connect/"
|
||||
categories = ["network-programming", "asynchronous"]
|
||||
license = "MIT/Apache-2.0"
|
||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||
edition = "2018"
|
||||
workspace = ".."
|
||||
|
||||
@@ -35,8 +34,8 @@ uri = ["http"]
|
||||
[dependencies]
|
||||
actix-service = "1.0.0"
|
||||
actix-codec = "0.2.0"
|
||||
actix-utils = "1.0.0-alpha.3"
|
||||
actix-rt = "1.0.0-alpha.3"
|
||||
actix-utils = "1.0.0"
|
||||
actix-rt = "1.0.0"
|
||||
derive_more = "0.99.2"
|
||||
either = "1.5.2"
|
||||
futures = "0.3.1"
|
||||
@@ -55,4 +54,4 @@ webpki = { version = "0.21", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
bytes = "0.5.2"
|
||||
actix-testing = { version="1.0.0-alpha.2" }
|
||||
actix-testing = { version="1.0.0" }
|
||||
|
@@ -1,5 +1,13 @@
|
||||
# Changes
|
||||
|
||||
## [0.4.1] - 2019-12-11
|
||||
|
||||
* Disconnect callback accepts owned state
|
||||
|
||||
## [0.4.0] - 2019-12-11
|
||||
|
||||
* Remove `E` param
|
||||
|
||||
## [0.3.0-alpha.3] - 2019-12-07
|
||||
|
||||
* Migrate to tokio 0.2
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-ioframe"
|
||||
version = "0.3.0-alpha.3"
|
||||
version = "0.4.1"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix framed service"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
@@ -9,7 +9,6 @@ repository = "https://github.com/actix/actix-net.git"
|
||||
documentation = "https://docs.rs/actix-ioframe/"
|
||||
categories = ["network-programming", "asynchronous"]
|
||||
license = "MIT/Apache-2.0"
|
||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||
edition = "2018"
|
||||
workspace = ".."
|
||||
|
||||
@@ -20,8 +19,8 @@ path = "src/lib.rs"
|
||||
[dependencies]
|
||||
actix-service = "1.0.0"
|
||||
actix-codec = "0.2.0"
|
||||
actix-utils = "1.0.0-alpha.2"
|
||||
actix-rt = "1.0.0-alpha.2"
|
||||
actix-utils = "1.0.1"
|
||||
actix-rt = "1.0.0"
|
||||
bytes = "0.5"
|
||||
either = "1.5.2"
|
||||
futures = "0.3.1"
|
||||
@@ -29,5 +28,5 @@ pin-project = "0.4.6"
|
||||
log = "0.4"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-connect = "1.0.0-alpha.2"
|
||||
actix-testing = "1.0.0-alpha.2"
|
||||
actix-connect = "1.0.0"
|
||||
actix-testing = "1.0.0"
|
||||
|
@@ -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()
|
||||
}
|
||||
}
|
@@ -3,40 +3,37 @@ use std::pin::Pin;
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
|
||||
use actix_utils::mpsc;
|
||||
use futures::Stream;
|
||||
|
||||
use crate::dispatcher::FramedMessage;
|
||||
use crate::sink::Sink;
|
||||
|
||||
pub struct Connect<Io, St = (), Codec = ()> {
|
||||
pub struct Connect<Io, Codec, St = ()>
|
||||
where
|
||||
Codec: Encoder + Decoder,
|
||||
{
|
||||
io: Io,
|
||||
sink: Sink<<Codec as Encoder>::Item>,
|
||||
_t: PhantomData<(St, Codec)>,
|
||||
}
|
||||
|
||||
impl<Io> Connect<Io>
|
||||
impl<Io, Codec> Connect<Io, Codec>
|
||||
where
|
||||
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>) -> Self {
|
||||
Self {
|
||||
io,
|
||||
sink,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn codec<Codec>(self, codec: Codec) -> ConnectResult<Io, (), Codec>
|
||||
where
|
||||
Codec: Encoder + Decoder,
|
||||
{
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let sink = Sink::new(tx);
|
||||
|
||||
pub fn codec(self, codec: Codec) -> ConnectResult<Io, (), Codec> {
|
||||
ConnectResult {
|
||||
state: (),
|
||||
sink: self.sink,
|
||||
framed: Framed::new(self.io, codec),
|
||||
rx,
|
||||
sink,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -45,7 +42,6 @@ where
|
||||
pub struct ConnectResult<Io, St, Codec: Encoder + Decoder> {
|
||||
pub(crate) state: St,
|
||||
pub(crate) framed: Framed<Io, Codec>,
|
||||
pub(crate) rx: mpsc::Receiver<FramedMessage<<Codec as Encoder>::Item>>,
|
||||
pub(crate) sink: Sink<<Codec as Encoder>::Item>,
|
||||
}
|
||||
|
||||
@@ -70,7 +66,6 @@ impl<Io, St, Codec: Encoder + Decoder> ConnectResult<Io, St, Codec> {
|
||||
ConnectResult {
|
||||
state,
|
||||
framed: self.framed,
|
||||
rx: self.rx,
|
||||
sink: self.sink,
|
||||
}
|
||||
}
|
||||
|
@@ -1,19 +1,14 @@
|
||||
//! Framed dispatcher service and related utilities
|
||||
use std::collections::VecDeque;
|
||||
use std::mem;
|
||||
use std::pin::Pin;
|
||||
use std::rc::Rc;
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
|
||||
use actix_service::{IntoService, Service};
|
||||
use actix_utils::task::LocalWaker;
|
||||
use actix_utils::{mpsc, oneshot};
|
||||
use futures::future::ready;
|
||||
use futures::{FutureExt, Sink as FutureSink, Stream};
|
||||
use futures::{FutureExt, Stream};
|
||||
use log::debug;
|
||||
|
||||
use crate::cell::Cell;
|
||||
use crate::error::ServiceError;
|
||||
use crate::item::Item;
|
||||
use crate::sink::Sink;
|
||||
@@ -21,16 +16,16 @@ use crate::sink::Sink;
|
||||
type Request<S, U> = Item<S, U>;
|
||||
type Response<U> = <U as Encoder>::Item;
|
||||
|
||||
pub(crate) enum FramedMessage<T> {
|
||||
Message(T),
|
||||
Close,
|
||||
pub(crate) enum Message<T> {
|
||||
Item(T),
|
||||
WaitClose(oneshot::Sender<()>),
|
||||
Close,
|
||||
}
|
||||
|
||||
/// FramedTransport - is a future that reads frames from Framed object
|
||||
/// and pass then to the service.
|
||||
#[pin_project::pin_project]
|
||||
pub(crate) struct FramedDispatcher<St, S, T, U>
|
||||
pub(crate) struct Dispatcher<St, S, T, U>
|
||||
where
|
||||
St: Clone,
|
||||
S: Service<Request = Request<St, U>, Response = Option<Response<U>>>,
|
||||
@@ -46,12 +41,12 @@ where
|
||||
state: St,
|
||||
dispatch_state: FramedState<S, U>,
|
||||
framed: Framed<T, U>,
|
||||
rx: Option<mpsc::Receiver<FramedMessage<<U as Encoder>::Item>>>,
|
||||
inner: Cell<FramedDispatcherInner<<U as Encoder>::Item, S::Error>>,
|
||||
disconnect: Option<Rc<dyn Fn(&mut St, bool)>>,
|
||||
rx: mpsc::Receiver<Result<Message<<U as Encoder>::Item>, S::Error>>,
|
||||
tx: mpsc::Sender<Result<Message<<U as Encoder>::Item>, S::Error>>,
|
||||
disconnect: Option<Rc<dyn Fn(St, bool)>>,
|
||||
}
|
||||
|
||||
impl<St, S, T, U> FramedDispatcher<St, S, T, U>
|
||||
impl<St, S, T, U> Dispatcher<St, S, T, U>
|
||||
where
|
||||
St: Clone,
|
||||
S: Service<Request = Request<St, U>, Response = Option<Response<U>>>,
|
||||
@@ -66,22 +61,21 @@ where
|
||||
framed: Framed<T, U>,
|
||||
state: St,
|
||||
service: F,
|
||||
rx: mpsc::Receiver<FramedMessage<<U as Encoder>::Item>>,
|
||||
sink: Sink<<U as Encoder>::Item>,
|
||||
disconnect: Option<Rc<dyn Fn(&mut St, bool)>>,
|
||||
rx: mpsc::Receiver<Result<Message<<U as Encoder>::Item>, S::Error>>,
|
||||
disconnect: Option<Rc<dyn Fn(St, bool)>>,
|
||||
) -> Self {
|
||||
FramedDispatcher {
|
||||
let tx = rx.sender();
|
||||
|
||||
Dispatcher {
|
||||
framed,
|
||||
state,
|
||||
sink,
|
||||
disconnect,
|
||||
rx: Some(rx),
|
||||
rx,
|
||||
tx,
|
||||
service: service.into_service(),
|
||||
dispatch_state: FramedState::Processing,
|
||||
inner: Cell::new(FramedDispatcherInner {
|
||||
buf: VecDeque::new(),
|
||||
task: LocalWaker::new(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -116,14 +110,23 @@ 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!(),
|
||||
}
|
||||
}
|
||||
|
||||
fn take_framed_error(&mut self) -> ServiceError<S::Error, U> {
|
||||
match std::mem::replace(self, FramedState::Processing) {
|
||||
FramedState::FramedError(err) => err,
|
||||
_ => panic!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct FramedDispatcherInner<I, E> {
|
||||
buf: VecDeque<Result<I, E>>,
|
||||
task: LocalWaker,
|
||||
}
|
||||
|
||||
impl<St, S, T, U> FramedDispatcher<St, S, T, U>
|
||||
impl<St, S, T, U> Dispatcher<St, S, T, U>
|
||||
where
|
||||
St: Clone,
|
||||
S: Service<Request = Request<St, U>, Response = Option<Response<U>>>,
|
||||
@@ -134,263 +137,150 @@ where
|
||||
<U as Encoder>::Item: 'static,
|
||||
<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(
|
||||
&mut self,
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<Result<(), ServiceError<S::Error, U>>> {
|
||||
let this = self;
|
||||
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 => {
|
||||
if poll_read(cx, srv, state, sink, framed, dispatch_state, inner)
|
||||
|| poll_write(cx, framed, dispatch_state, rx, inner)
|
||||
{
|
||||
poll(
|
||||
cx,
|
||||
srv,
|
||||
state,
|
||||
sink,
|
||||
framed,
|
||||
dispatch_state,
|
||||
rx,
|
||||
inner,
|
||||
disconnect,
|
||||
)
|
||||
} else {
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
FramedState::Error(err) => {
|
||||
if framed.is_write_buf_empty()
|
||||
|| (poll_write(cx, framed, dispatch_state, rx, inner)
|
||||
|| framed.is_write_buf_empty())
|
||||
{
|
||||
if let Some(ref disconnect) = disconnect {
|
||||
(&*disconnect)(&mut *state, true);
|
||||
match self.dispatch_state {
|
||||
FramedState::Processing => {
|
||||
if self.poll_read(cx) || self.poll_write(cx) {
|
||||
self.poll(cx)
|
||||
} else {
|
||||
Poll::Pending
|
||||
}
|
||||
Poll::Ready(Err(err))
|
||||
} else {
|
||||
*dispatch_state = FramedState::Error(err);
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
FramedState::FlushAndStop(mut vec) => {
|
||||
if !framed.is_write_buf_empty() {
|
||||
match Pin::new(framed).poll_flush(cx) {
|
||||
Poll::Ready(Err(err)) => {
|
||||
debug!("Error sending data: {:?}", err);
|
||||
}
|
||||
Poll::Pending => {
|
||||
*dispatch_state = FramedState::FlushAndStop(vec);
|
||||
FramedState::Error(_) => {
|
||||
// flush write buffer
|
||||
if !self.framed.is_write_buf_empty() {
|
||||
if let Poll::Pending = self.framed.flush(cx) {
|
||||
return Poll::Pending;
|
||||
}
|
||||
Poll::Ready(_) => (),
|
||||
}
|
||||
};
|
||||
for tx in vec.drain(..) {
|
||||
let _ = tx.send(());
|
||||
if let Some(ref disconnect) = self.disconnect {
|
||||
(&*disconnect)(self.state.clone(), true);
|
||||
}
|
||||
Poll::Ready(Err(self.dispatch_state.take_error()))
|
||||
}
|
||||
if let Some(ref disconnect) = disconnect {
|
||||
(&*disconnect)(&mut *state, false);
|
||||
}
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
FramedState::FramedError(err) => {
|
||||
if let Some(ref disconnect) = disconnect {
|
||||
(&*disconnect)(&mut *state, true);
|
||||
}
|
||||
Poll::Ready(Err(err))
|
||||
}
|
||||
FramedState::Stopping => {
|
||||
if let Some(ref disconnect) = disconnect {
|
||||
(&*disconnect)(&mut *state, false);
|
||||
}
|
||||
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;
|
||||
FramedState::FlushAndStop(ref mut vec) => {
|
||||
if !self.framed.is_write_buf_empty() {
|
||||
match self.framed.flush(cx) {
|
||||
Poll::Ready(Err(err)) => {
|
||||
debug!("Error sending data: {:?}", err);
|
||||
}
|
||||
Poll::Pending => {
|
||||
return Poll::Pending;
|
||||
}
|
||||
Poll::Ready(_) => (),
|
||||
}
|
||||
};
|
||||
|
||||
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(())
|
||||
},
|
||||
));
|
||||
for tx in vec.drain(..) {
|
||||
let _ = tx.send(());
|
||||
}
|
||||
if let Some(ref disconnect) = self.disconnect {
|
||||
(&*disconnect)(self.state.clone(), false);
|
||||
}
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
Poll::Pending => return false,
|
||||
Poll::Ready(Err(err)) => {
|
||||
*dispatch_state = FramedState::Error(ServiceError::Service(err));
|
||||
return true;
|
||||
FramedState::FramedError(_) => {
|
||||
if let Some(ref disconnect) = self.disconnect {
|
||||
(&*disconnect)(self.state.clone(), true);
|
||||
}
|
||||
Poll::Ready(Err(self.dispatch_state.take_framed_error()))
|
||||
}
|
||||
FramedState::Stopping => {
|
||||
if let Some(ref disconnect) = self.disconnect {
|
||||
(&*disconnect)(self.state.clone(), false);
|
||||
}
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
|
@@ -77,6 +77,6 @@ where
|
||||
<Codec as Decoder>::Item: fmt::Debug,
|
||||
{
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
@@ -1,7 +1,6 @@
|
||||
#![deny(rust_2018_idioms, warnings)]
|
||||
#![allow(clippy::type_complexity, clippy::too_many_arguments)]
|
||||
|
||||
mod cell;
|
||||
mod connect;
|
||||
mod dispatcher;
|
||||
mod error;
|
||||
|
@@ -6,17 +6,20 @@ use std::task::{Context, Poll};
|
||||
|
||||
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder};
|
||||
use actix_service::{IntoService, IntoServiceFactory, Service, ServiceFactory};
|
||||
use actix_utils::mpsc;
|
||||
use either::Either;
|
||||
use futures::future::{FutureExt, LocalBoxFuture};
|
||||
use pin_project::project;
|
||||
|
||||
use crate::connect::{Connect, ConnectResult};
|
||||
use crate::dispatcher::FramedDispatcher;
|
||||
use crate::dispatcher::{Dispatcher, Message};
|
||||
use crate::error::ServiceError;
|
||||
use crate::item::Item;
|
||||
use crate::sink::Sink;
|
||||
|
||||
type RequestItem<S, U> = Item<S, U>;
|
||||
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
|
||||
/// for building instances for framed services.
|
||||
@@ -38,7 +41,7 @@ impl<St: Clone, Codec> Builder<St, Codec> {
|
||||
where
|
||||
F: IntoService<C>,
|
||||
Io: AsyncRead + AsyncWrite,
|
||||
C: Service<Request = Connect<Io>, Response = ConnectResult<Io, St, Codec>>,
|
||||
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec>>,
|
||||
Codec: Decoder + Encoder,
|
||||
{
|
||||
ServiceBuilder {
|
||||
@@ -55,7 +58,7 @@ impl<St: Clone, Codec> Builder<St, Codec> {
|
||||
Io: AsyncRead + AsyncWrite,
|
||||
C: ServiceFactory<
|
||||
Config = (),
|
||||
Request = Connect<Io>,
|
||||
Request = Connect<Io, Codec>,
|
||||
Response = ConnectResult<Io, St, Codec>,
|
||||
>,
|
||||
C::Error: 'static,
|
||||
@@ -72,15 +75,14 @@ impl<St: Clone, Codec> Builder<St, Codec> {
|
||||
|
||||
pub struct ServiceBuilder<St, C, Io, Codec> {
|
||||
connect: C,
|
||||
disconnect: Option<Rc<dyn Fn(&mut St, bool)>>,
|
||||
disconnect: Option<Rc<dyn Fn(St, bool)>>,
|
||||
_t: PhantomData<(St, Io, Codec)>,
|
||||
}
|
||||
|
||||
impl<St, C, Io, Codec> ServiceBuilder<St, C, Io, Codec>
|
||||
where
|
||||
St: Clone,
|
||||
C: Service<Request = Connect<Io>, Response = ConnectResult<Io, St, Codec>>,
|
||||
C::Error: 'static,
|
||||
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec>>,
|
||||
Io: AsyncRead + AsyncWrite,
|
||||
Codec: Decoder + Encoder,
|
||||
<Codec as Encoder>::Item: 'static,
|
||||
@@ -91,7 +93,7 @@ where
|
||||
/// Second parameter indicates error occured during disconnect.
|
||||
pub fn disconnect<F, Out>(mut self, disconnect: F) -> Self
|
||||
where
|
||||
F: Fn(&mut St, bool) + 'static,
|
||||
F: Fn(St, bool) + 'static,
|
||||
{
|
||||
self.disconnect = Some(Rc::new(disconnect));
|
||||
self
|
||||
@@ -102,12 +104,12 @@ where
|
||||
where
|
||||
F: IntoServiceFactory<T>,
|
||||
T: ServiceFactory<
|
||||
Config = St,
|
||||
Request = RequestItem<St, Codec>,
|
||||
Response = ResponseItem<Codec>,
|
||||
Error = C::Error,
|
||||
InitError = C::Error,
|
||||
> + 'static,
|
||||
Config = St,
|
||||
Request = RequestItem<St, Codec>,
|
||||
Response = ResponseItem<Codec>,
|
||||
Error = C::Error,
|
||||
InitError = C::Error,
|
||||
>,
|
||||
{
|
||||
FramedServiceImpl {
|
||||
connect: self.connect,
|
||||
@@ -120,7 +122,7 @@ where
|
||||
|
||||
pub struct NewServiceBuilder<St, C, Io, Codec> {
|
||||
connect: C,
|
||||
disconnect: Option<Rc<dyn Fn(&mut St, bool)>>,
|
||||
disconnect: Option<Rc<dyn Fn(St, bool)>>,
|
||||
_t: PhantomData<(St, Io, Codec)>,
|
||||
}
|
||||
|
||||
@@ -130,7 +132,7 @@ where
|
||||
Io: AsyncRead + AsyncWrite,
|
||||
C: ServiceFactory<
|
||||
Config = (),
|
||||
Request = Connect<Io>,
|
||||
Request = Connect<Io, Codec>,
|
||||
Response = ConnectResult<Io, St, Codec>,
|
||||
>,
|
||||
C::Error: 'static,
|
||||
@@ -144,7 +146,7 @@ where
|
||||
/// Second parameter indicates error occured during disconnect.
|
||||
pub fn disconnect<F>(mut self, disconnect: F) -> Self
|
||||
where
|
||||
F: Fn(&mut St, bool) + 'static,
|
||||
F: Fn(St, bool) + 'static,
|
||||
{
|
||||
self.disconnect = Some(Rc::new(disconnect));
|
||||
self
|
||||
@@ -173,7 +175,7 @@ where
|
||||
pub struct FramedService<St, C, T, Io, Codec, Cfg> {
|
||||
connect: C,
|
||||
handler: Rc<T>,
|
||||
disconnect: Option<Rc<dyn Fn(&mut St, bool)>>,
|
||||
disconnect: Option<Rc<dyn Fn(St, bool)>>,
|
||||
_t: PhantomData<(St, Io, Codec, Cfg)>,
|
||||
}
|
||||
|
||||
@@ -183,7 +185,7 @@ where
|
||||
Io: AsyncRead + AsyncWrite,
|
||||
C: ServiceFactory<
|
||||
Config = (),
|
||||
Request = Connect<Io>,
|
||||
Request = Connect<Io, Codec>,
|
||||
Response = ConnectResult<Io, St, Codec>,
|
||||
>,
|
||||
C::Error: 'static,
|
||||
@@ -230,7 +232,7 @@ where
|
||||
pub struct FramedServiceImpl<St, C, T, Io, Codec> {
|
||||
connect: C,
|
||||
handler: Rc<T>,
|
||||
disconnect: Option<Rc<dyn Fn(&mut St, bool)>>,
|
||||
disconnect: Option<Rc<dyn Fn(St, bool)>>,
|
||||
_t: PhantomData<(St, Io, Codec)>,
|
||||
}
|
||||
|
||||
@@ -238,7 +240,7 @@ impl<St, C, T, Io, Codec> Service for FramedServiceImpl<St, C, T, Io, Codec>
|
||||
where
|
||||
St: Clone,
|
||||
Io: AsyncRead + AsyncWrite,
|
||||
C: Service<Request = Connect<Io>, Response = ConnectResult<Io, St, Codec>>,
|
||||
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec>>,
|
||||
C::Error: 'static,
|
||||
T: ServiceFactory<
|
||||
Config = St,
|
||||
@@ -262,11 +264,16 @@ where
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Io) -> Self::Future {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let sink = Sink::new(Rc::new(move |msg| {
|
||||
let _ = tx.send(Ok(msg));
|
||||
}));
|
||||
FramedServiceImplResponse {
|
||||
inner: FramedServiceImplResponseInner::Connect(
|
||||
self.connect.call(Connect::new(req)),
|
||||
self.connect.call(Connect::new(req, sink.clone())),
|
||||
self.handler.clone(),
|
||||
self.disconnect.clone(),
|
||||
Some(rx),
|
||||
),
|
||||
}
|
||||
}
|
||||
@@ -276,7 +283,7 @@ where
|
||||
pub struct FramedServiceImplResponse<St, Io, Codec, C, T>
|
||||
where
|
||||
St: Clone,
|
||||
C: Service<Request = Connect<Io>, Response = ConnectResult<Io, St, Codec>>,
|
||||
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec>>,
|
||||
C::Error: 'static,
|
||||
T: ServiceFactory<
|
||||
Config = St,
|
||||
@@ -298,7 +305,7 @@ where
|
||||
impl<St, Io, Codec, C, T> Future for FramedServiceImplResponse<St, Io, Codec, C, T>
|
||||
where
|
||||
St: Clone,
|
||||
C: Service<Request = Connect<Io>, Response = ConnectResult<Io, St, Codec>>,
|
||||
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec>>,
|
||||
C::Error: 'static,
|
||||
T: ServiceFactory<
|
||||
Config = St,
|
||||
@@ -334,7 +341,7 @@ where
|
||||
enum FramedServiceImplResponseInner<St, Io, Codec, C, T>
|
||||
where
|
||||
St: Clone,
|
||||
C: Service<Request = Connect<Io>, Response = ConnectResult<Io, St, Codec>>,
|
||||
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec>>,
|
||||
C::Error: 'static,
|
||||
T: ServiceFactory<
|
||||
Config = St,
|
||||
@@ -349,19 +356,25 @@ where
|
||||
<Codec as Encoder>::Item: 'static,
|
||||
<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(St, bool)>>,
|
||||
Option<mpsc::Receiver<ServiceResult<Codec, C::Error>>>,
|
||||
),
|
||||
Handler(
|
||||
#[pin] T::Future,
|
||||
Option<ConnectResult<Io, St, Codec>>,
|
||||
Option<Rc<dyn Fn(&mut St, bool)>>,
|
||||
Option<Rc<dyn Fn(St, bool)>>,
|
||||
Option<mpsc::Receiver<ServiceResult<Codec, C::Error>>>,
|
||||
),
|
||||
Dispatcher(#[pin] FramedDispatcher<St, T::Service, Io, Codec>),
|
||||
Dispatcher(Dispatcher<St, T::Service, Io, Codec>),
|
||||
}
|
||||
|
||||
impl<St, Io, Codec, C, T> FramedServiceImplResponseInner<St, Io, Codec, C, T>
|
||||
where
|
||||
St: Clone,
|
||||
C: Service<Request = Connect<Io>, Response = ConnectResult<Io, St, Codec>>,
|
||||
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec>>,
|
||||
C::Error: 'static,
|
||||
T: ServiceFactory<
|
||||
Config = St,
|
||||
@@ -386,37 +399,39 @@ where
|
||||
> {
|
||||
#[project]
|
||||
match self.project() {
|
||||
FramedServiceImplResponseInner::Connect(fut, handler, disconnect) => {
|
||||
FramedServiceImplResponseInner::Connect(fut, handler, disconnect, rx) => {
|
||||
match fut.poll(cx) {
|
||||
Poll::Ready(Ok(res)) => {
|
||||
Either::Left(FramedServiceImplResponseInner::Handler(
|
||||
handler.new_service(res.state.clone()),
|
||||
Some(res),
|
||||
disconnect.take(),
|
||||
rx.take(),
|
||||
))
|
||||
}
|
||||
Poll::Pending => Either::Right(Poll::Pending),
|
||||
Poll::Ready(Err(e)) => Either::Right(Poll::Ready(Err(e.into()))),
|
||||
}
|
||||
}
|
||||
FramedServiceImplResponseInner::Handler(fut, res, disconnect) => match fut.poll(cx)
|
||||
{
|
||||
Poll::Ready(Ok(handler)) => {
|
||||
let res = res.take().unwrap();
|
||||
Either::Left(FramedServiceImplResponseInner::Dispatcher(
|
||||
FramedDispatcher::new(
|
||||
res.framed,
|
||||
res.state,
|
||||
handler,
|
||||
res.rx,
|
||||
res.sink,
|
||||
disconnect.take(),
|
||||
),
|
||||
))
|
||||
FramedServiceImplResponseInner::Handler(fut, res, disconnect, rx) => {
|
||||
match fut.poll(cx) {
|
||||
Poll::Ready(Ok(handler)) => {
|
||||
let res = res.take().unwrap();
|
||||
Either::Left(FramedServiceImplResponseInner::Dispatcher(
|
||||
Dispatcher::new(
|
||||
res.framed,
|
||||
res.state,
|
||||
handler,
|
||||
res.sink,
|
||||
rx.take().unwrap(),
|
||||
disconnect.take(),
|
||||
),
|
||||
))
|
||||
}
|
||||
Poll::Pending => Either::Right(Poll::Pending),
|
||||
Poll::Ready(Err(e)) => Either::Right(Poll::Ready(Err(e.into()))),
|
||||
}
|
||||
Poll::Pending => Either::Right(Poll::Pending),
|
||||
Poll::Ready(Err(e)) => Either::Right(Poll::Ready(Err(e.into()))),
|
||||
},
|
||||
}
|
||||
FramedServiceImplResponseInner::Dispatcher(ref mut fut) => {
|
||||
Either::Right(fut.poll(cx))
|
||||
}
|
||||
|
@@ -1,11 +1,12 @@
|
||||
use std::fmt;
|
||||
use std::rc::Rc;
|
||||
|
||||
use actix_utils::{mpsc, oneshot};
|
||||
use actix_utils::oneshot;
|
||||
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>(Rc<dyn Fn(Message<T>)>);
|
||||
|
||||
impl<T> Clone for Sink<T> {
|
||||
fn clone(&self) -> Self {
|
||||
@@ -14,26 +15,26 @@ impl<T> Clone for Sink<T> {
|
||||
}
|
||||
|
||||
impl<T> Sink<T> {
|
||||
pub(crate) fn new(tx: mpsc::Sender<FramedMessage<T>>) -> Self {
|
||||
pub(crate) fn new(tx: Rc<dyn Fn(Message<T>)>) -> Self {
|
||||
Sink(tx)
|
||||
}
|
||||
|
||||
/// Close connection
|
||||
pub fn close(&self) {
|
||||
let _ = self.0.send(FramedMessage::Close);
|
||||
(self.0)(Message::Close);
|
||||
}
|
||||
|
||||
/// Close connection
|
||||
pub fn wait_close(&self) -> impl Future<Output = ()> {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
let _ = self.0.send(FramedMessage::WaitClose(tx));
|
||||
(self.0)(Message::WaitClose(tx));
|
||||
|
||||
rx.map(|_| ())
|
||||
}
|
||||
|
||||
/// Send item
|
||||
pub fn send(&self, item: T) {
|
||||
let _ = self.0.send(FramedMessage::Message(item));
|
||||
(self.0)(Message::Item(item));
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -22,7 +22,7 @@ async fn test_disconnect() -> std::io::Result<()> {
|
||||
let disconnect1 = disconnect1.clone();
|
||||
|
||||
Builder::new()
|
||||
.factory(fn_service(|conn: Connect<_>| {
|
||||
.factory(fn_service(|conn: Connect<_, _>| {
|
||||
ok(conn.codec(BytesCodec).state(State))
|
||||
}))
|
||||
.disconnect(move |_, _| {
|
||||
@@ -32,7 +32,7 @@ async fn test_disconnect() -> std::io::Result<()> {
|
||||
});
|
||||
|
||||
let mut client = Builder::new()
|
||||
.service(|conn: Connect<_>| {
|
||||
.service(|conn: Connect<_, _>| {
|
||||
let conn = conn.codec(BytesCodec).state(State);
|
||||
conn.sink().close();
|
||||
ok(conn)
|
||||
|
@@ -18,4 +18,4 @@ quote = "^1"
|
||||
syn = { version = "^1", features = ["full"] }
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = { version = "1.0.0-alpha.3" }
|
||||
actix-rt = { version = "1.0.0" }
|
||||
|
@@ -1,5 +1,12 @@
|
||||
# Changes
|
||||
|
||||
## [1.0.0] - 2019-12-11
|
||||
|
||||
### Changed
|
||||
|
||||
* Use actix-net releases
|
||||
|
||||
|
||||
## [1.0.0-alpha.4] - 2019-12-08
|
||||
|
||||
### Changed
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-server"
|
||||
version = "1.0.0-alpha.4"
|
||||
version = "1.0.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix server - General purpose tcp server"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
@@ -22,12 +22,12 @@ default = []
|
||||
|
||||
[dependencies]
|
||||
actix-service = "1.0.0"
|
||||
actix-rt = "1.0.0-alpha.3"
|
||||
actix-rt = "1.0.0"
|
||||
actix-codec = "0.2.0"
|
||||
actix-utils = "1.0.0-alpha.3"
|
||||
actix-utils = "1.0.0"
|
||||
|
||||
log = "0.4"
|
||||
num_cpus = "1.0"
|
||||
num_cpus = "1.11"
|
||||
mio = "0.6.19"
|
||||
net2 = "0.2"
|
||||
futures = "0.3.1"
|
||||
@@ -39,4 +39,4 @@ mio-uds = { version = "0.6.7" }
|
||||
[dev-dependencies]
|
||||
bytes = "0.5"
|
||||
env_logger = "0.6"
|
||||
actix-testing = "1.0.0-alpha.3"
|
||||
actix-testing = "1.0.0"
|
@@ -26,4 +26,4 @@ futures-util = "0.3.1"
|
||||
pin-project = "0.4.6"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "1.0.0-alpha.3"
|
||||
actix-rt = "1.0.0"
|
||||
|
@@ -1,5 +1,9 @@
|
||||
# Changes
|
||||
|
||||
## [1.0.0] - 2019-12-11
|
||||
|
||||
* Update actix-server to 1.0.0
|
||||
|
||||
## [1.0.0-alpha.3] - 2019-12-07
|
||||
|
||||
* Migrate to tokio 0.2
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-testing"
|
||||
version = "1.0.0-alpha.3"
|
||||
version = "1.0.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix testing utils"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
@@ -17,9 +17,9 @@ name = "actix_testing"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-rt = "1.0.0-alpha.3"
|
||||
actix-rt = "1.0.0"
|
||||
actix-macros = "0.1.0"
|
||||
actix-server = "1.0.0-alpha.3"
|
||||
actix-server = "1.0.0"
|
||||
actix-service = "1.0.0"
|
||||
|
||||
log = "0.4"
|
||||
|
@@ -1,6 +1,10 @@
|
||||
# Changes
|
||||
|
||||
[1.0.0-alpha.3] - 2019-12-07
|
||||
## [1.0.0] - 2019-12-11
|
||||
|
||||
* 1.0.0 release
|
||||
|
||||
## [1.0.0-alpha.3] - 2019-12-07
|
||||
|
||||
### Changed
|
||||
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-tls"
|
||||
version = "1.0.0-alpha.3"
|
||||
version = "1.0.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix tls services"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
@@ -34,8 +34,8 @@ nativetls = ["native-tls", "tokio-tls"]
|
||||
[dependencies]
|
||||
actix-service = "1.0.0"
|
||||
actix-codec = "0.2.0"
|
||||
actix-utils = "1.0.0-alpha.3"
|
||||
actix-rt = "1.0.0-alpha.3"
|
||||
actix-utils = "1.0.0"
|
||||
actix-rt = "1.0.0"
|
||||
derive_more = "0.99.2"
|
||||
either = "1.5.2"
|
||||
futures = "0.3.1"
|
||||
@@ -57,4 +57,4 @@ tokio-tls = { version="0.3", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
bytes = "0.5"
|
||||
actix-testing = { version="1.0.0-alpha.3" }
|
||||
actix-testing = { version="1.0.0" }
|
||||
|
@@ -1,5 +1,19 @@
|
||||
# Changes
|
||||
|
||||
## [1.0.2] - 2019-12-11
|
||||
|
||||
* Allow to create `framed::Dispatcher` with custom `mpsc::Receiver`
|
||||
|
||||
* Add `oneshot::Sender::is_canceled()` method
|
||||
|
||||
## [1.0.1] - 2019-12-11
|
||||
|
||||
* Optimize InOrder service
|
||||
|
||||
## [1.0.0] - 2019-12-11
|
||||
|
||||
* Simplify oneshot and mpsc implementations
|
||||
|
||||
## [1.0.0-alpha.3] - 2019-12-07
|
||||
|
||||
* Migrate to tokio 0.2
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-utils"
|
||||
version = "1.0.0-alpha.3"
|
||||
version = "1.0.2"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix utils - various actix net related services"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
@@ -9,7 +9,6 @@ repository = "https://github.com/actix/actix-net.git"
|
||||
documentation = "https://docs.rs/actix-utils/"
|
||||
categories = ["network-programming", "asynchronous"]
|
||||
license = "MIT/Apache-2.0"
|
||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||
edition = "2018"
|
||||
workspace = ".."
|
||||
|
||||
@@ -19,7 +18,7 @@ path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-service = "1.0.0"
|
||||
actix-rt = "1.0.0-alpha.3"
|
||||
actix-rt = "1.0.0"
|
||||
actix-codec = "0.2.0"
|
||||
bytes = "0.5.2"
|
||||
either = "1.5.2"
|
||||
|
@@ -2,16 +2,12 @@
|
||||
|
||||
use std::cell::UnsafeCell;
|
||||
use std::fmt;
|
||||
use std::rc::{Rc, Weak};
|
||||
use std::rc::Rc;
|
||||
|
||||
pub(crate) struct Cell<T> {
|
||||
pub(crate) inner: Rc<UnsafeCell<T>>,
|
||||
}
|
||||
|
||||
pub(crate) struct WeakCell<T> {
|
||||
inner: Weak<UnsafeCell<T>>,
|
||||
}
|
||||
|
||||
impl<T> Clone for Cell<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
@@ -27,39 +23,26 @@ impl<T: fmt::Debug> fmt::Debug for Cell<T> {
|
||||
}
|
||||
|
||||
impl<T> Cell<T> {
|
||||
pub fn new(inner: T) -> Self {
|
||||
pub(crate) fn new(inner: T) -> Self {
|
||||
Self {
|
||||
inner: Rc::new(UnsafeCell::new(inner)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn downgrade(&self) -> WeakCell<T> {
|
||||
WeakCell {
|
||||
inner: Rc::downgrade(&self.inner),
|
||||
}
|
||||
pub(crate) fn strong_count(&self) -> usize {
|
||||
Rc::strong_count(&self.inner)
|
||||
}
|
||||
|
||||
pub fn get_ref(&self) -> &T {
|
||||
pub(crate) fn get_ref(&self) -> &T {
|
||||
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() }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> WeakCell<T> {
|
||||
pub fn upgrade(&self) -> Option<Cell<T>> {
|
||||
if let Some(inner) = self.inner.upgrade() {
|
||||
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)
|
||||
#[allow(clippy::mut_from_ref)]
|
||||
pub(crate) unsafe fn get_mut_unsafe(&self) -> &mut T {
|
||||
&mut *self.inner.as_ref().get()
|
||||
}
|
||||
}
|
||||
|
@@ -1,37 +1,33 @@
|
||||
//! Framed dispatcher service and related utilities
|
||||
#![allow(type_alias_bounds)]
|
||||
use std::collections::VecDeque;
|
||||
use std::pin::Pin;
|
||||
use std::task::{Context, Poll};
|
||||
use std::{fmt, mem};
|
||||
|
||||
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
|
||||
use actix_service::{IntoService, Service};
|
||||
use futures::future::{ready, FutureExt};
|
||||
use futures::{Future, Sink, Stream};
|
||||
use futures::{Future, FutureExt, Stream};
|
||||
use log::debug;
|
||||
|
||||
use crate::cell::Cell;
|
||||
use crate::mpsc;
|
||||
use crate::task::LocalWaker;
|
||||
|
||||
type Request<U> = <U as Decoder>::Item;
|
||||
type Response<U> = <U as Encoder>::Item;
|
||||
|
||||
/// Framed transport errors
|
||||
pub enum FramedTransportError<E, U: Encoder + Decoder> {
|
||||
pub enum DispatcherError<E, U: Encoder + Decoder> {
|
||||
Service(E),
|
||||
Encoder(<U as Encoder>::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 {
|
||||
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
|
||||
E: fmt::Debug,
|
||||
<U as Encoder>::Error: fmt::Debug,
|
||||
@@ -39,20 +35,14 @@ where
|
||||
{
|
||||
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)
|
||||
}
|
||||
DispatcherError::Service(ref e) => write!(fmt, "DispatcherError::Service({:?})", e),
|
||||
DispatcherError::Encoder(ref e) => write!(fmt, "DispatcherError::Encoder({:?})", e),
|
||||
DispatcherError::Decoder(ref e) => write!(fmt, "DispatcherError::Decoder({:?})", e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, U: Encoder + Decoder> fmt::Display for FramedTransportError<E, U>
|
||||
impl<E, U: Encoder + Decoder> fmt::Display for DispatcherError<E, U>
|
||||
where
|
||||
E: fmt::Display,
|
||||
<U as Encoder>::Error: fmt::Debug,
|
||||
@@ -60,25 +50,22 @@ where
|
||||
{
|
||||
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),
|
||||
DispatcherError::Service(ref e) => write!(fmt, "{}", e),
|
||||
DispatcherError::Encoder(ref e) => write!(fmt, "{:?}", e),
|
||||
DispatcherError::Decoder(ref e) => write!(fmt, "{:?}", e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub enum FramedMessage<T> {
|
||||
Message(T),
|
||||
pub enum Message<T> {
|
||||
Item(T),
|
||||
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
|
||||
/// and pass then to the service.
|
||||
#[pin_project::pin_project]
|
||||
pub struct FramedTransport<S, T, U>
|
||||
pub struct Dispatcher<S, T, U>
|
||||
where
|
||||
S: Service<Request = Request<U>, Response = Response<U>>,
|
||||
S::Error: 'static,
|
||||
@@ -89,26 +76,37 @@ where
|
||||
<U as Encoder>::Error: std::fmt::Debug,
|
||||
{
|
||||
service: S,
|
||||
state: TransportState<S, U>,
|
||||
state: State<S, U>,
|
||||
framed: Framed<T, U>,
|
||||
rx: Option<mpsc::Receiver<FramedMessage<<U as Encoder>::Item>>>,
|
||||
inner: Cell<FramedTransportInner<<U as Encoder>::Item, S::Error>>,
|
||||
rx: mpsc::Receiver<Result<Message<<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,
|
||||
Error(FramedTransportError<S::Error, U>),
|
||||
FramedError(FramedTransportError<S::Error, U>),
|
||||
Error(DispatcherError<S::Error, U>),
|
||||
FramedError(DispatcherError<S::Error, U>),
|
||||
FlushAndStop,
|
||||
Stopping,
|
||||
}
|
||||
|
||||
struct FramedTransportInner<I, E> {
|
||||
buf: VecDeque<Result<I, E>>,
|
||||
task: LocalWaker,
|
||||
impl<S: Service, U: Encoder + Decoder> State<S, U> {
|
||||
fn take_error(&mut self) -> DispatcherError<S::Error, U> {
|
||||
match mem::replace(self, State::Processing) {
|
||||
State::Error(err) => err,
|
||||
_ => panic!(),
|
||||
}
|
||||
}
|
||||
|
||||
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> FramedTransport<S, T, U>
|
||||
impl<S, T, U> Dispatcher<S, T, U>
|
||||
where
|
||||
S: Service<Request = Request<U>, Response = Response<U>>,
|
||||
S::Error: 'static,
|
||||
@@ -119,52 +117,150 @@ where
|
||||
<U as Encoder>::Error: std::fmt::Debug,
|
||||
{
|
||||
pub fn new<F: IntoService<S>>(framed: Framed<T, U>, service: F) -> Self {
|
||||
FramedTransport {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
Dispatcher {
|
||||
framed,
|
||||
rx: None,
|
||||
rx,
|
||||
tx,
|
||||
service: service.into_service(),
|
||||
state: TransportState::Processing,
|
||||
inner: Cell::new(FramedTransportInner {
|
||||
buf: VecDeque::new(),
|
||||
task: LocalWaker::new(),
|
||||
}),
|
||||
state: State::Processing,
|
||||
}
|
||||
}
|
||||
|
||||
/// Get Sender
|
||||
pub fn set_receiver(
|
||||
mut self,
|
||||
rx: mpsc::Receiver<FramedMessage<<U as Encoder>::Item>>,
|
||||
/// Construct new `Dispatcher` instance with customer `mpsc::Receiver`
|
||||
pub fn with_rx<F: IntoService<S>>(
|
||||
framed: Framed<T, U>,
|
||||
service: F,
|
||||
rx: mpsc::Receiver<Result<Message<<U as Encoder>::Item>, S::Error>>,
|
||||
) -> Self {
|
||||
self.rx = Some(rx);
|
||||
self
|
||||
let tx = rx.sender();
|
||||
Dispatcher {
|
||||
framed,
|
||||
rx,
|
||||
tx,
|
||||
service: service.into_service(),
|
||||
state: State::Processing,
|
||||
}
|
||||
}
|
||||
|
||||
/// Get reference to a service wrapped by `FramedTransport` instance.
|
||||
/// Get sink
|
||||
pub fn get_sink(&self) -> mpsc::Sender<Result<Message<<U as Encoder>::Item>, S::Error>> {
|
||||
self.tx.clone()
|
||||
}
|
||||
|
||||
/// Get reference to a service wrapped by `Dispatcher` instance.
|
||||
pub fn get_ref(&self) -> &S {
|
||||
&self.service
|
||||
}
|
||||
|
||||
/// Get mutable reference to a service wrapped by `FramedTransport`
|
||||
/// instance.
|
||||
/// Get mutable reference to a service wrapped by `Dispatcher` instance.
|
||||
pub fn get_mut(&mut self) -> &mut S {
|
||||
&mut self.service
|
||||
}
|
||||
|
||||
/// Get reference to a framed instance wrapped by `FramedTransport`
|
||||
/// Get reference to a framed instance wrapped by `Dispatcher`
|
||||
/// instance.
|
||||
pub fn get_framed(&self) -> &Framed<T, U> {
|
||||
&self.framed
|
||||
}
|
||||
|
||||
/// Get mutable reference to a framed instance wrapped by `FramedTransport`
|
||||
/// instance.
|
||||
/// Get mutable reference to a framed instance wrapped by `Dispatcher` instance.
|
||||
pub fn get_framed_mut(&mut self) -> &mut Framed<T, U> {
|
||||
&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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 FramedTransport<S, T, U>
|
||||
impl<S, T, U> Future for Dispatcher<S, T, U>
|
||||
where
|
||||
S: Service<Request = Request<U>, Response = Response<U>>,
|
||||
S::Error: 'static,
|
||||
@@ -175,210 +271,46 @@ where
|
||||
<U as Encoder>::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> {
|
||||
self.inner.get_ref().task.register(cx.waker());
|
||||
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
loop {
|
||||
let this = self.as_mut().project();
|
||||
|
||||
let this = self.project();
|
||||
poll(
|
||||
cx,
|
||||
this.service,
|
||||
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 {
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
TransportState::Error(err) => {
|
||||
let is_empty = framed.is_write_buf_empty();
|
||||
if is_empty || poll_write(cx, state, framed, rx, inner) {
|
||||
Poll::Ready(Err(err))
|
||||
} else {
|
||||
*state = TransportState::Error(err);
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
TransportState::FlushAndStop => {
|
||||
if !framed.is_write_buf_empty() {
|
||||
match Pin::new(framed).poll_flush(cx) {
|
||||
Poll::Ready(Err(err)) => {
|
||||
debug!("Error sending data: {:?}", err);
|
||||
return match this.state {
|
||||
State::Processing => {
|
||||
if self.poll_read(cx) || self.poll_write(cx) {
|
||||
continue;
|
||||
} else {
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
State::Error(_) => {
|
||||
// flush write buffer
|
||||
if !self.framed.is_write_buf_empty() {
|
||||
if let Poll::Pending = self.framed.flush(cx) {
|
||||
return Poll::Pending;
|
||||
}
|
||||
}
|
||||
Poll::Ready(Err(self.state.take_error()))
|
||||
}
|
||||
State::FlushAndStop => {
|
||||
if !this.framed.is_write_buf_empty() {
|
||||
match this.framed.flush(cx) {
|
||||
Poll::Ready(Err(err)) => {
|
||||
debug!("Error sending data: {:?}", err);
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
Poll::Pending => Poll::Pending,
|
||||
Poll::Ready(Ok(_)) => Poll::Ready(Ok(())),
|
||||
}
|
||||
} else {
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
Poll::Pending => Poll::Pending,
|
||||
Poll::Ready(Ok(_)) => Poll::Ready(Ok(())),
|
||||
}
|
||||
} else {
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
}
|
||||
TransportState::FramedError(err) => Poll::Ready(Err(err)),
|
||||
TransportState::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;
|
||||
}
|
||||
State::FramedError(_) => Poll::Ready(Err(this.state.take_framed_error())),
|
||||
State::Stopping => Poll::Ready(Ok(())),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
|
@@ -1,34 +1,27 @@
|
||||
//! A multi-producer, single-consumer, futures-aware, FIFO queue with back
|
||||
//! 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.
|
||||
|
||||
//! A multi-producer, single-consumer, futures-aware, FIFO queue.
|
||||
use std::any::Any;
|
||||
use std::cell::RefCell;
|
||||
use std::collections::VecDeque;
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::pin::Pin;
|
||||
use std::rc::{Rc, Weak};
|
||||
use std::task::{Context, Poll};
|
||||
use std::{fmt, mem};
|
||||
|
||||
use futures::{Sink, Stream};
|
||||
|
||||
use crate::cell::Cell;
|
||||
use crate::task::LocalWaker;
|
||||
|
||||
/// Creates a unbounded in-memory channel with buffered storage.
|
||||
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(),
|
||||
blocked_recv: LocalWaker::new(),
|
||||
}));
|
||||
});
|
||||
let sender = Sender {
|
||||
shared: Rc::downgrade(&shared),
|
||||
};
|
||||
let receiver = Receiver {
|
||||
state: State::Open(shared),
|
||||
shared: shared.clone(),
|
||||
};
|
||||
let receiver = Receiver { shared };
|
||||
(sender, receiver)
|
||||
}
|
||||
|
||||
@@ -36,6 +29,7 @@ pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
|
||||
struct Shared<T> {
|
||||
buffer: VecDeque<T>,
|
||||
blocked_recv: LocalWaker,
|
||||
has_receiver: bool,
|
||||
}
|
||||
|
||||
/// The transmission end of a channel.
|
||||
@@ -43,22 +37,30 @@ struct Shared<T> {
|
||||
/// This is created by the `channel` function.
|
||||
#[derive(Debug)]
|
||||
pub struct Sender<T> {
|
||||
shared: Weak<RefCell<Shared<T>>>,
|
||||
shared: Cell<Shared<T>>,
|
||||
}
|
||||
|
||||
impl<T> Unpin for Sender<T> {}
|
||||
|
||||
impl<T> Sender<T> {
|
||||
/// Sends the provided message along this channel.
|
||||
pub fn send(&self, item: T) -> Result<(), SendError<T>> {
|
||||
let shared = match self.shared.upgrade() {
|
||||
Some(shared) => shared,
|
||||
None => return Err(SendError(item)), // receiver was dropped
|
||||
let shared = unsafe { self.shared.get_mut_unsafe() };
|
||||
if !shared.has_receiver {
|
||||
return Err(SendError(item)); // receiver was dropped
|
||||
};
|
||||
let mut shared = shared.borrow_mut();
|
||||
|
||||
shared.buffer.push_back(item);
|
||||
shared.blocked_recv.wake();
|
||||
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> {
|
||||
@@ -91,17 +93,13 @@ impl<T> Sink<T> for Sender<T> {
|
||||
|
||||
impl<T> Drop for Sender<T> {
|
||||
fn drop(&mut self) {
|
||||
let shared = match self.shared.upgrade() {
|
||||
Some(shared) => shared,
|
||||
None => return,
|
||||
};
|
||||
// The number of existing `Weak` indicates if we are possibly the last
|
||||
// `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 {
|
||||
let count = self.shared.strong_count();
|
||||
let shared = self.shared.get_mut();
|
||||
|
||||
// check is last sender is about to drop
|
||||
if shared.has_receiver && count == 2 {
|
||||
// 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.
|
||||
#[derive(Debug)]
|
||||
pub struct Receiver<T> {
|
||||
state: State<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>),
|
||||
shared: Cell<Shared<T>>,
|
||||
}
|
||||
|
||||
impl<T> Receiver<T> {
|
||||
/// Closes the receiving 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) {
|
||||
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);
|
||||
/// Create Sender
|
||||
pub fn sender(&self) -> Sender<T> {
|
||||
Sender {
|
||||
shared: self.shared.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Unpin for Receiver<T> {}
|
||||
|
||||
impl<T> Stream for Receiver<T> {
|
||||
type Item = T;
|
||||
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
let me = match self.state {
|
||||
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) {
|
||||
if self.shared.strong_count() == 1 {
|
||||
// All senders have been dropped, so drain the buffer and end the
|
||||
// stream.
|
||||
return Poll::Ready(shared.borrow_mut().buffer.pop_front());
|
||||
}
|
||||
|
||||
let mut shared = me.borrow_mut();
|
||||
if let Some(msg) = shared.buffer.pop_front() {
|
||||
Poll::Ready(self.shared.get_mut().buffer.pop_front())
|
||||
} else if let Some(msg) = self.shared.get_mut().buffer.pop_front() {
|
||||
Poll::Ready(Some(msg))
|
||||
} else {
|
||||
shared.blocked_recv.register(cx.waker());
|
||||
self.shared.get_mut().blocked_recv.register(cx.waker());
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
@@ -168,7 +142,9 @@ impl<T> Stream for Receiver<T> {
|
||||
|
||||
impl<T> Drop for Receiver<T> {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
#[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());
|
||||
}
|
||||
}
|
||||
|
@@ -1,69 +1,45 @@
|
||||
//! A one-shot, futures-aware channel
|
||||
//!
|
||||
//! This channel is similar to that in `sync::oneshot` but cannot be sent across
|
||||
//! threads.
|
||||
|
||||
//! A one-shot, futures-aware channel.
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::rc::Rc;
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
pub use futures::channel::oneshot::Canceled;
|
||||
|
||||
use crate::cell::{Cell, WeakCell};
|
||||
use crate::cell::Cell;
|
||||
use crate::task::LocalWaker;
|
||||
|
||||
/// 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>) {
|
||||
let inner = Cell::new(Inner {
|
||||
value: None,
|
||||
rx_task: LocalWaker::new(),
|
||||
});
|
||||
let tx = Sender {
|
||||
inner: inner.downgrade(),
|
||||
};
|
||||
let rx = Receiver {
|
||||
state: State::Open(inner),
|
||||
inner: inner.clone(),
|
||||
};
|
||||
let rx = Receiver { inner };
|
||||
(tx, rx)
|
||||
}
|
||||
|
||||
/// Represents the completion half of a oneshot through which the result of a
|
||||
/// 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)]
|
||||
pub struct Sender<T> {
|
||||
inner: WeakCell<Inner<T>>,
|
||||
inner: Cell<Inner<T>>,
|
||||
}
|
||||
|
||||
/// A future representing the completion of a computation happening elsewhere in
|
||||
/// 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)]
|
||||
#[must_use = "futures do nothing unless polled"]
|
||||
pub struct Receiver<T> {
|
||||
state: State<T>,
|
||||
inner: Cell<Inner<T>>,
|
||||
}
|
||||
|
||||
// The channels do not ever project Pin to the inner T
|
||||
impl<T> Unpin for Receiver<T> {}
|
||||
impl<T> Unpin for Sender<T> {}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum State<T> {
|
||||
Open(Cell<Inner<T>>),
|
||||
Closed(Option<T>),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Inner<T> {
|
||||
value: Option<T>,
|
||||
@@ -78,12 +54,12 @@ impl<T> Sender<T> {
|
||||
/// represents.
|
||||
///
|
||||
/// 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
|
||||
/// provided.
|
||||
pub fn send(self, val: T) -> Result<(), T> {
|
||||
if let Some(mut inner) = self.inner.upgrade() {
|
||||
let inner = inner.get_mut();
|
||||
pub fn send(mut self, val: T) -> Result<(), T> {
|
||||
if self.inner.strong_count() == 2 {
|
||||
let inner = self.inner.get_mut();
|
||||
inner.value = Some(val);
|
||||
inner.rx_task.wake();
|
||||
Ok(())
|
||||
@@ -94,44 +70,15 @@ impl<T> Sender<T> {
|
||||
|
||||
/// 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()
|
||||
self.inner.strong_count() == 1
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Drop for Sender<T> {
|
||||
fn drop(&mut self) {
|
||||
if let Some(inner) = self.inner.upgrade() {
|
||||
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(_) => {}
|
||||
if self.inner.strong_count() == 2 {
|
||||
self.inner.get_ref().rx_task.wake();
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -142,33 +89,50 @@ impl<T> Future for Receiver<T> {
|
||||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
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 let Some(val) = inner.get_mut().value.take() {
|
||||
if let Some(val) = this.inner.get_mut().value.take() {
|
||||
return Poll::Ready(Ok(val));
|
||||
}
|
||||
|
||||
// If we can get mutable access, then the sender has gone away. We
|
||||
// didn't see a value above, so we're canceled. Otherwise we park
|
||||
// our task and wait for a value to come in.
|
||||
if Rc::get_mut(&mut inner.inner).is_some() {
|
||||
// Check if sender is dropped and return error if it is.
|
||||
if this.inner.strong_count() == 1 {
|
||||
Poll::Ready(Err(Canceled))
|
||||
} else {
|
||||
inner.get_ref().rx_task.register(cx.waker());
|
||||
this.inner.get_ref().rx_task.register(cx.waker());
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Drop for Receiver<T> {
|
||||
fn drop(&mut self) {
|
||||
self.close();
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
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();
|
||||
assert!(!tx.is_canceled());
|
||||
drop(rx);
|
||||
assert!(tx.is_canceled());
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
@@ -4,14 +4,12 @@ use std::fmt;
|
||||
use std::future::Future;
|
||||
use std::marker::PhantomData;
|
||||
use std::pin::Pin;
|
||||
use std::rc::Rc;
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
use actix_service::{IntoService, Service, Transform};
|
||||
use futures::future::{ok, Ready};
|
||||
|
||||
use crate::oneshot;
|
||||
use crate::task::LocalWaker;
|
||||
|
||||
struct Record<I, E> {
|
||||
rx: oneshot::Receiver<Result<I, E>>,
|
||||
@@ -105,7 +103,6 @@ where
|
||||
|
||||
pub struct InOrderService<S: Service> {
|
||||
service: S,
|
||||
task: Rc<LocalWaker>,
|
||||
acks: VecDeque<Record<S::Response, S::Error>>,
|
||||
}
|
||||
|
||||
@@ -123,7 +120,6 @@ where
|
||||
Self {
|
||||
service: service.into_service(),
|
||||
acks: VecDeque::new(),
|
||||
task: Rc::new(LocalWaker::new()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -141,9 +137,6 @@ where
|
||||
type Future = InOrderServiceResponse<S>;
|
||||
|
||||
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
// poll_ready could be called from different task
|
||||
self.task.register(cx.waker());
|
||||
|
||||
// check acks
|
||||
while !self.acks.is_empty() {
|
||||
let rec = self.acks.front_mut().unwrap();
|
||||
@@ -172,11 +165,9 @@ where
|
||||
let (tx2, rx2) = oneshot::channel();
|
||||
self.acks.push_back(Record { rx: rx1, tx: tx2 });
|
||||
|
||||
let task = self.task.clone();
|
||||
let fut = self.service.call(request);
|
||||
actix_rt::spawn(async move {
|
||||
let res = fut.await;
|
||||
task.wake();
|
||||
let _ = tx1.send(res);
|
||||
});
|
||||
|
||||
|
@@ -3,12 +3,12 @@ use std::pin::Pin;
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
use actix_service::{IntoService, Service};
|
||||
use futures::Stream;
|
||||
use futures::{FutureExt, Stream};
|
||||
|
||||
use crate::mpsc;
|
||||
|
||||
#[pin_project::pin_project]
|
||||
pub struct StreamDispatcher<S, T>
|
||||
pub struct Dispatcher<S, T>
|
||||
where
|
||||
S: Stream,
|
||||
T: Service<Request = S::Item, Response = ()> + 'static,
|
||||
@@ -20,7 +20,7 @@ where
|
||||
err_tx: mpsc::Sender<T::Error>,
|
||||
}
|
||||
|
||||
impl<S, T> StreamDispatcher<S, T>
|
||||
impl<S, T> Dispatcher<S, T>
|
||||
where
|
||||
S: Stream,
|
||||
T: Service<Request = S::Item, Response = ()> + 'static,
|
||||
@@ -30,7 +30,7 @@ where
|
||||
F: IntoService<T>,
|
||||
{
|
||||
let (err_tx, err_rx) = mpsc::channel();
|
||||
StreamDispatcher {
|
||||
Dispatcher {
|
||||
err_rx,
|
||||
err_tx,
|
||||
stream,
|
||||
@@ -39,7 +39,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, T> Future for StreamDispatcher<S, T>
|
||||
impl<S, T> Future for Dispatcher<S, T>
|
||||
where
|
||||
S: Stream,
|
||||
T: Service<Request = S::Item, Response = ()> + 'static,
|
||||
@@ -54,47 +54,23 @@ where
|
||||
}
|
||||
|
||||
loop {
|
||||
match this.service.poll_ready(cx)? {
|
||||
return match this.service.poll_ready(cx)? {
|
||||
Poll::Ready(_) => match this.stream.poll_next(cx) {
|
||||
Poll::Ready(Some(item)) => {
|
||||
actix_rt::spawn(StreamDispatcherService {
|
||||
fut: this.service.call(item),
|
||||
stop: self.err_tx.clone(),
|
||||
});
|
||||
let stop = this.err_tx.clone();
|
||||
actix_rt::spawn(this.service.call(item).map(move |res| {
|
||||
if let Err(e) = res {
|
||||
let _ = stop.send(e);
|
||||
}
|
||||
}));
|
||||
this = self.as_mut().project();
|
||||
continue;
|
||||
}
|
||||
Poll::Pending => return Poll::Pending,
|
||||
Poll::Ready(None) => return Poll::Ready(Ok(())),
|
||||
Poll::Pending => Poll::Pending,
|
||||
Poll::Ready(None) => 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::Ready(Err(e)) => {
|
||||
let _ = this.stop.send(e);
|
||||
Poll::Ready(())
|
||||
}
|
||||
Poll::Pending => Poll::Pending,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user