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

Compare commits

...

64 Commits

Author SHA1 Message Date
Nikolay Kim
5940731ef0 Fix actix-service 1.0.3 compatibility 2020-01-15 11:58:06 -08:00
Rajasekharan Vengalil
aed5fecc8a Add support for tokio tracing for actix Service. (#86)
* Add support for tokio tracing for actix Service.

* Address comments

* Change trace's return type to ApplyTransform

* Remove redundant type args

* Remove reference to MakeSpan from docs
2020-01-15 11:43:52 -08:00
Nikolay Kim
a751899aad Fixed unsoundness in AndThenService impl #83 2020-01-15 11:40:15 -08:00
Nikolay Kim
fa800aeba3 Fix AsRef<str> impl 2020-01-14 15:06:02 -08:00
Nikolay Kim
2f89483635 Merge branch 'master' of github.com:actix/actix-net 2020-01-14 00:42:29 -08:00
Nikolay Kim
3048073919 Add PartialEq<T: AsRef<str>>, AsRef<[u8]> impls 2020-01-13 11:58:31 +06:00
amosonn
4bbba803c1 Fix Service documentation (#85) 2020-01-12 07:44:01 +09:00
Sven-Hendrik Haase
4dcdeb6795 Merge pull request #84 from currency-engineering/master
Minor grammatical fix to docs.
2020-01-10 15:28:19 +01:00
Eric Findlay
3b4f222242 Minor grammatical fix to docs. 2020-01-10 20:52:49 +09:00
Nikolay Kim
7c5fa25b23 Add into_service helper function 2020-01-08 18:31:50 +06:00
Nikolay Kim
3551d6674d Add Clone impl for condition::Waiter 2020-01-08 11:18:56 +06:00
Nikolay Kim
9f00daea80 add Condition and Pool 2020-01-08 10:59:27 +06:00
Nikolay Kim
7dddeab2a8 Add ResourceDef::resource_path_named() path generation method 2019-12-31 18:02:43 +06:00
Nikolay Kim
dcbcc40da2 Revert "Support named parameters for ResourceDef::resource_path() in form of ((&k, &v), ...)"
This reverts commit b0d44198ba.
2019-12-31 15:14:53 +06:00
Nikolay Kim
b0d44198ba Support named parameters for ResourceDef::resource_path() in form of ((&k, &v), ...) 2019-12-31 14:53:30 +06:00
Nikolay Kim
974bd6b01e leak string instead of rc 2019-12-31 12:04:35 +06:00
Nikolay Kim
5779da0f49 refactor service and state manahement 2019-12-29 13:42:42 +06:00
Nikolay Kim
1918c8d4f8 rename .run to .start() 2019-12-29 10:07:46 +06:00
Nikolay Kim
e21c58930b Add impl IntoPattern for &String 2019-12-25 21:34:14 +04:00
Nikolay Kim
59c5e9be6a Use IntoPattern for RouterBuilder::path() 2019-12-25 21:01:07 +04:00
Nikolay Kim
a2a9d9764d introduce IntoPattern trait 2019-12-25 19:54:20 +04:00
Nikolay Kim
bf0a9d2f6e Add IntoPatterns trait 2019-12-25 15:34:21 +04:00
Nikolay Kim
119027f822 fmt 2019-12-25 15:10:13 +04:00
Nikolay Kim
0fe8038d23 allow specify set of resource patters 2019-12-25 15:10:01 +04:00
Nikolay Kim
b599bc4a0c map_config() and unit_config() accepts IntoServiceFactory type 2019-12-22 16:30:49 +04:00
Nikolay Kim
a80e1f8370 fix new() method and make from_static and from_bytes_unchecked methods const 2019-12-22 16:24:28 +04:00
Nikolay Kim
5fe759cc02 Merge branch 'master' of github.com:actix/actix-net 2019-12-20 09:15:19 +06:00
Nikolay Kim
05549f0b42 Add methods to check LocalWaker registration state 2019-12-20 09:13:11 +06:00
Yuki Okushi
b1430eaded Run tests for all features as possible (#78) 2019-12-19 16:31:32 +09:00
Nikolay Kim
0d3f9e74c5 Use .advance() intead of .split_to() 2019-12-19 09:50:31 +06:00
Nikolay Kim
cab73791ed pin trsut-dns-proto 2019-12-15 13:04:26 +06:00
Nikolay Kim
a7ac1a76ed add license files to actix-macros 2019-12-14 23:01:55 +06:00
Nikolay Kim
37bedff6fb use parking_lot 0.10 2019-12-12 06:57:40 +06:00
Nikolay Kim
33fd6adc11 better InOrder test 2019-12-12 06:56:45 +06:00
Nikolay Kim
4305cdba2c Revert InOrder service changes 2019-12-11 23:10:02 +06:00
Nikolay Kim
52ecb4bcc5 Add oneshot::Sender::is_canceled() method 2019-12-11 20:52:57 +06:00
Nikolay Kim
b28f32e82c Allow to create framed::Dispatcher with custom mpsc::Receiver 2019-12-11 20:23:14 +06:00
Nikolay Kim
081205a02f Disconnect callback accepts owned state 2019-12-11 18:57:43 +06:00
Nikolay Kim
8bb81c0768 optimize InOrder service 2019-12-11 18:55:53 +06:00
Nikolay Kim
c7a8743bf9 remove E param 2019-12-11 16:44:09 +06:00
Nikolay Kim
f26fcc703b prep release 2019-12-11 14:56:05 +06:00
Nikolay Kim
ce4587df82 prepare actix-tls release 2019-12-11 14:53:58 +06:00
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
Nikolay Kim
c094f84b85 prepare actix-service release 2019-12-11 10:29:34 +06:00
Nikolay Kim
25012d290a update actix-codec dependencies 2019-12-11 10:23:01 +06:00
Nikolay Kim
32202188cc prepare actix-codec release 2019-12-11 10:18:11 +06:00
Nikolay Kim
bf734a31dc update docs 2019-12-10 21:34:51 +06:00
Nikolay Kim
d29e7c4ba6 Merge branch 'master' of github.com:actix/actix-net 2019-12-10 21:14:18 +06:00
Nikolay Kim
7163e2c2a2 update doc strings 2019-12-10 21:14:06 +06:00
Nikolay Kim
1d810b4561 re-export AlpnError 2019-12-10 12:15:27 +06:00
daxpedda
0913badd61 Macro improvements. (#74)
* Macro improvements.

* Fix usage in `fn main`.
2019-12-10 08:47:35 +06:00
Nikolay Kim
8b3062cd6e Fix buffer remaining capacity calcualtion 2019-12-09 21:50:36 +06:00
Nikolay Kim
35218a4df1 add Clone impl for Apply service 2019-12-09 14:07:20 +06:00
Nikolay Kim
d47f1fb730 prepare actix-service release 2019-12-08 19:49:35 +06:00
Nikolay Kim
1ad0bbfb7f rename fn service helpers 2019-12-08 19:05:05 +06:00
Nikolay Kim
c38a25f102 fix hash impl 2019-12-07 11:51:47 +06:00
80 changed files with 2575 additions and 1573 deletions

View File

@@ -2,6 +2,9 @@ name: CI
on: [push, pull_request]
env:
VCPKGRS_DYNAMIC: 1
jobs:
build_and_test:
strategy:
@@ -18,10 +21,12 @@ jobs:
include:
- toolchain: x86_64-pc-windows-msvc
os: windows-latest
arch: x64
- toolchain: x86_64-pc-windows-gnu
os: windows-latest
- toolchain: i686-pc-windows-msvc
os: windows-latest
arch: x86
- toolchain: x86_64-apple-darwin
os: macOS-latest
@@ -37,6 +42,13 @@ jobs:
toolchain: ${{ matrix.version }}-${{ matrix.toolchain }}
default: true
- name: Install OpenSSL
if: matrix.toolchain == 'x86_64-pc-windows-msvc' || matrix.toolchain == 'i686-pc-windows-msvc'
run: |
vcpkg integrate install
vcpkg install openssl:${{ matrix.arch }}-windows
- name: check nightly
if: matrix.version == 'nightly'
uses: actions-rs/cargo@v1
@@ -52,6 +64,14 @@ jobs:
args: --all --bins --examples --tests
- name: tests
if: matrix.toolchain != 'x86_64-pc-windows-gnu'
uses: actions-rs/cargo@v1
with:
command: test
args: --all --all-features -- --nocapture
- name: tests on x86_64-pc-windows-gnu
if: matrix.toolchain == 'x86_64-pc-windows-gnu'
uses: actions-rs/cargo@v1
with:
command: test

View File

@@ -10,6 +10,7 @@ members = [
"actix-testing",
"actix-threadpool",
"actix-tls",
"actix-tracing",
"actix-utils",
"router",
"string",

View File

@@ -30,14 +30,16 @@ fn main() -> io::Result<()> {
let num = num.clone();
let acceptor = acceptor.clone();
// service for converting incoming TcpStream to a SslStream<TcpStream>
fn_service(move |stream: Io<tokio_tcp::TcpStream>| {
SslAcceptorExt::accept_async(&acceptor, stream.into_parts().0)
.map_err(|e| println!("Openssl error: {}", e))
})
// .and_then() combinator uses other service to convert incoming `Request` to a
// `Response` and then uses that response as an input for next
// service. in this case, on success we use `logger` service
// construct transformation pipeline
pipeline(
// service for converting incoming TcpStream to a SslStream<TcpStream>
fn_service(move |stream: actix_rt::net::TcpStream| async move {
SslAcceptorExt::accept_async(&acceptor, stream.into_parts().0).await
.map_err(|e| println!("Openssl error: {}", e))
}))
// .and_then() combinator chains result of previos service call to argument
/// for next service calll. in this case, on success we chain
/// ssl stream to the `logger` service.
.and_then(fn_service(logger))
// Next service counts number of connections
.and_then(move |_| {

View File

@@ -1,5 +1,15 @@
# Changes
* Use `.advance()` intead of `.split_to()`
## [0.2.0] - 2019-12-10
* Use specific futures dependencies
## [0.2.0-alpha.4]
* Fix buffer remaining capacity calcualtion
## [0.2.0-alpha.3]
* Use tokio 0.2
@@ -10,17 +20,14 @@
* Migrated to `std::future`
## [0.1.2] - 2019-03-27
* Added `Framed::map_io()` method.
## [0.1.1] - 2019-03-06
* Added `FramedParts::with_read_buffer()` method.
## [0.1.0] - 2018-12-09
* Move codec to separate crate

View File

@@ -1,6 +1,6 @@
[package]
name = "actix-codec"
version = "0.2.0-alpha.3"
version = "0.2.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Utilities for encoding and decoding frames"
keywords = ["network", "framework", "async", "futures"]
@@ -9,7 +9,6 @@ repository = "https://github.com/actix/actix-net.git"
documentation = "https://docs.rs/actix-codec/"
categories = ["network-programming", "asynchronous"]
license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
edition = "2018"
workspace = ".."
@@ -20,7 +19,8 @@ path = "src/lib.rs"
[dependencies]
bitflags = "1.2.1"
bytes = "0.5.2"
futures = "0.3.1"
futures-core = "0.3.1"
futures-sink = "0.3.1"
tokio = { version = "0.2.4", default-features=false }
tokio-util = { version = "0.2.0", default-features=false, features=["codec"] }
log = "0.4"

View File

@@ -2,8 +2,9 @@ use std::pin::Pin;
use std::task::{Context, Poll};
use std::{fmt, io};
use bytes::{BufMut, BytesMut};
use futures::{ready, Sink, Stream};
use bytes::{Buf, BytesMut};
use futures_core::{ready, Stream};
use futures_sink::Sink;
use crate::{AsyncRead, AsyncWrite, Decoder, Encoder};
@@ -19,8 +20,6 @@ bitflags::bitflags! {
/// A unified `Stream` and `Sink` interface to an underlying I/O object, using
/// the `Encoder` and `Decoder` traits to encode and decode frames.
///
/// You can create a `Framed` instance by using the `AsyncRead::framed` adapter.
pub struct Framed<T, U> {
io: T,
codec: U,
@@ -49,10 +48,6 @@ where
/// `Sink`; grouping this into a single object is often useful for layering
/// things like gzip or TLS, which require both read and write access to the
/// underlying object.
///
/// If you want to work more directly with the streams and sink, consider
/// calling `split` on the `Framed` returned by this method, which will
/// break them into separate objects, allowing them to interact more easily.
pub fn new(io: T, codec: U) -> Framed<T, U> {
Framed {
io,
@@ -82,10 +77,6 @@ impl<T, U> Framed<T, U> {
/// This objects takes a stream and a readbuffer and a writebuffer. These
/// field can be obtained from an existing `Framed` with the
/// `into_parts` method.
///
/// If you want to work more directly with the streams and sink, consider
/// calling `split` on the `Framed` returned by this method, which will
/// break them into separate objects, allowing them to interact more easily.
pub fn from_parts(parts: FramedParts<T, U>) -> Framed<T, U> {
Framed {
io: parts.io,
@@ -136,15 +127,6 @@ impl<T, U> Framed<T, U> {
self.write_buf.len() >= HW
}
/// Consumes the `Frame`, returning its underlying I/O stream.
///
/// Note that care should be taken to not tamper with the underlying stream
/// of data coming in as it may corrupt the stream of frames otherwise
/// being worked with.
pub fn into_inner(self) -> T {
self.io
}
/// Consume the `Frame`, returning `Frame` with different codec.
pub fn into_framed<U2>(self, codec: U2) -> Framed<T, U2> {
Framed {
@@ -208,7 +190,7 @@ impl<T, U> Framed<T, U> {
T: AsyncWrite,
U: Encoder,
{
let remaining = self.write_buf.remaining_mut();
let remaining = self.write_buf.capacity() - self.write_buf.len();
if remaining < LW {
self.write_buf.reserve(HW - remaining);
}
@@ -217,11 +199,14 @@ impl<T, U> Framed<T, U> {
Ok(())
}
/// Check if framed is able to write more data
pub fn is_ready(&self) -> bool {
/// Check if framed is able to write more data.
///
/// `Framed` object considers ready if there is free space in write buffer.
pub fn is_write_ready(&self) -> bool {
self.write_buf.len() < HW
}
/// Try to read underlying I/O stream and decode item.
pub fn next_item(&mut self, cx: &mut Context<'_>) -> Poll<Option<Result<U::Item, U::Error>>>
where
T: AsyncRead,
@@ -251,9 +236,7 @@ impl<T, U> Framed<T, U> {
return Poll::Ready(Some(Ok(frame)));
}
Err(e) => return Poll::Ready(Some(Err(e))),
_ => {
// Need more data
}
_ => (), // Need more data
}
self.flags.remove(Flags::READABLE);
@@ -262,7 +245,7 @@ impl<T, U> Framed<T, U> {
debug_assert!(!self.flags.contains(Flags::EOF));
// Otherwise, try to read more data and try again. Make sure we've got room
let remaining = self.read_buf.remaining_mut();
let remaining = self.read_buf.capacity() - self.read_buf.len();
if remaining < LW {
self.read_buf.reserve(HW - remaining)
}
@@ -281,6 +264,7 @@ impl<T, U> Framed<T, U> {
}
}
/// Flush write buffer to underlying I/O stream.
pub fn flush(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), U::Error>>
where
T: AsyncWrite,
@@ -298,15 +282,13 @@ impl<T, U> Framed<T, U> {
if n == 0 {
return Poll::Ready(Err(io::Error::new(
io::ErrorKind::WriteZero,
"failed to \
write frame to transport",
"failed to write frame to transport",
)
.into()));
}
// TODO: Add a way to `bytes` to do this w/o returning the drained
// data.
let _ = self.write_buf.split_to(n);
// remove written data
self.write_buf.advance(n);
}
// Try flushing the underlying IO
@@ -316,6 +298,7 @@ impl<T, U> Framed<T, U> {
Poll::Ready(Ok(()))
}
/// Flush write buffer and shutdown underlying I/O stream.
pub fn close(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), U::Error>>
where
T: AsyncWrite,
@@ -350,7 +333,7 @@ where
type Error = U::Error;
fn poll_ready(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
if self.is_ready() {
if self.is_write_ready() {
Poll::Ready(Ok(()))
} else {
Poll::Pending

View File

@@ -7,7 +7,6 @@
//! [`AsyncRead`]: #
//! [`AsyncWrite`]: #
#![deny(rust_2018_idioms, warnings)]
#![allow(clippy::type_complexity)]
mod bcodec;
mod framed;

View File

@@ -1,5 +1,17 @@
# Changes
## [1.0.2] - 2020-01-15
* Fix actix-service 1.0.3 compatibility
## [1.0.1] - 2019-12-15
* Fix trust-dns-resolver compilation
## [1.0.0] - 2019-12-11
* Release
## [1.0.0-alpha.3] - 2019-12-07
### Changed

View File

@@ -1,6 +1,6 @@
[package]
name = "actix-connect"
version = "1.0.0-alpha.3"
version = "1.0.2"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix connect - tcp connector service"
keywords = ["network", "framework", "async", "futures"]
@@ -9,9 +9,7 @@ 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 = ".."
[package.metadata.docs.rs]
features = ["openssl", "rustls", "uri"]
@@ -33,16 +31,17 @@ rustls = ["rust-tls", "tokio-rustls", "webpki"]
uri = ["http"]
[dependencies]
actix-service = "1.0.0-alpha.3"
actix-codec = "0.2.0-alpha.3"
actix-utils = "1.0.0-alpha.3"
actix-rt = "1.0.0-alpha.3"
actix-service = "1.0.3"
actix-codec = "0.2.0"
actix-utils = "1.0.6"
actix-rt = "1.0.0"
derive_more = "0.99.2"
either = "1.5.2"
either = "1.5.3"
futures = "0.3.1"
http = { version = "0.2.0", optional = true }
log = "0.4"
trust-dns-resolver = { version="0.18.0-alpha.2", default-features = false, features=["tokio"] }
trust-dns-proto = "=0.18.0-alpha.2"
trust-dns-resolver = "=0.18.0-alpha.2"
# openssl
open-ssl = { version="0.10", package = "openssl", optional = true }
@@ -54,5 +53,5 @@ tokio-rustls = { version = "0.12.0", optional = true }
webpki = { version = "0.21", optional = true }
[dev-dependencies]
bytes = "0.5.2"
actix-testing = { version="1.0.0-alpha.2" }
bytes = "0.5.3"
actix-testing = { version="1.0.0" }

View File

@@ -72,7 +72,7 @@ pub fn start_default_resolver() -> AsyncResolver {
}
/// Create tcp connector service
pub fn new_connector<T: Address>(
pub fn new_connector<T: Address + 'static>(
resolver: AsyncResolver,
) -> impl Service<Request = Connect<T>, Response = Connection<T, TcpStream>, Error = ConnectError>
+ Clone {
@@ -80,7 +80,7 @@ pub fn new_connector<T: Address>(
}
/// Create tcp connector service
pub fn new_connector_factory<T: Address>(
pub fn new_connector_factory<T: Address + 'static>(
resolver: AsyncResolver,
) -> impl ServiceFactory<
Config = (),
@@ -93,14 +93,14 @@ pub fn new_connector_factory<T: Address>(
}
/// Create connector service with default parameters
pub fn default_connector<T: Address>(
pub fn default_connector<T: Address + 'static>(
) -> impl Service<Request = Connect<T>, Response = Connection<T, TcpStream>, Error = ConnectError>
+ Clone {
pipeline(Resolver::default()).and_then(TcpConnector::new())
}
/// Create connector service factory with default parameters
pub fn default_connector_factory<T: Address>() -> impl ServiceFactory<
pub fn default_connector_factory<T: Address + 'static>() -> impl ServiceFactory<
Config = (),
Request = Connect<T>,
Response = Connection<T, TcpStream>,

View File

@@ -2,7 +2,7 @@ use std::io;
use actix_codec::{BytesCodec, Framed};
use actix_rt::net::TcpStream;
use actix_service::{service_fn, Service, ServiceFactory};
use actix_service::{fn_service, Service, ServiceFactory};
use actix_testing::TestServer;
use bytes::Bytes;
use futures::SinkExt;
@@ -14,7 +14,7 @@ use actix_connect::Connect;
#[actix_rt::test]
async fn test_string() {
let srv = TestServer::with(|| {
service_fn(|io: TcpStream| {
fn_service(|io: TcpStream| {
async {
let mut framed = Framed::new(io, BytesCodec);
framed.send(Bytes::from_static(b"test")).await?;
@@ -33,7 +33,7 @@ async fn test_string() {
#[actix_rt::test]
async fn test_rustls_string() {
let srv = TestServer::with(|| {
service_fn(|io: TcpStream| {
fn_service(|io: TcpStream| {
async {
let mut framed = Framed::new(io, BytesCodec);
framed.send(Bytes::from_static(b"test")).await?;
@@ -51,7 +51,7 @@ async fn test_rustls_string() {
#[actix_rt::test]
async fn test_static_str() {
let srv = TestServer::with(|| {
service_fn(|io: TcpStream| {
fn_service(|io: TcpStream| {
async {
let mut framed = Framed::new(io, BytesCodec);
framed.send(Bytes::from_static(b"test")).await?;
@@ -75,7 +75,7 @@ async fn test_static_str() {
#[actix_rt::test]
async fn test_new_service() {
let srv = TestServer::with(|| {
service_fn(|io: TcpStream| {
fn_service(|io: TcpStream| {
async {
let mut framed = Framed::new(io, BytesCodec);
framed.send(Bytes::from_static(b"test")).await?;
@@ -100,7 +100,7 @@ async fn test_uri() {
use std::convert::TryFrom;
let srv = TestServer::with(|| {
service_fn(|io: TcpStream| {
fn_service(|io: TcpStream| {
async {
let mut framed = Framed::new(io, BytesCodec);
framed.send(Bytes::from_static(b"test")).await?;
@@ -121,7 +121,7 @@ async fn test_rustls_uri() {
use std::convert::TryFrom;
let srv = TestServer::with(|| {
service_fn(|io: TcpStream| {
fn_service(|io: TcpStream| {
async {
let mut framed = Framed::new(io, BytesCodec);
framed.send(Bytes::from_static(b"test")).await?;

View File

@@ -1,5 +1,21 @@
# Changes
## [0.5.0] - 2019-12-29
* Simplify state management
* Allow to set custom output stream
* Removed disconnect callback
## [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

View File

@@ -1,6 +1,6 @@
[package]
name = "actix-ioframe"
version = "0.3.0-alpha.3"
version = "0.5.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix framed service"
keywords = ["network", "framework", "async", "futures"]
@@ -9,25 +9,23 @@ 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 = ".."
[lib]
name = "actix_ioframe"
path = "src/lib.rs"
[dependencies]
actix-service = "1.0.0-alpha.3"
actix-codec = "0.2.0-alpha.2"
actix-utils = "1.0.0-alpha.2"
actix-rt = "1.0.0-alpha.2"
bytes = "0.5"
either = "1.5.2"
actix-service = "1.0.1"
actix-codec = "0.2.0"
actix-utils = "1.0.4"
actix-rt = "1.0.0"
bytes = "0.5.3"
either = "1.5.3"
futures = "0.3.1"
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"

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,20 +3,21 @@ use std::pin::Pin;
use std::task::{Context, Poll};
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
use actix_utils::mpsc;
use actix_utils::mpsc::Receiver;
use futures::Stream;
use crate::dispatcher::FramedMessage;
use crate::sink::Sink;
pub struct Connect<Io, St = (), Codec = ()> {
pub struct Connect<Io, Codec>
where
Codec: Encoder + Decoder,
{
io: Io,
_t: PhantomData<(St, Codec)>,
_t: PhantomData<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 {
Self {
@@ -25,36 +26,26 @@ where
}
}
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, Receiver<<Codec as Encoder>::Item>> {
ConnectResult {
state: (),
out: None,
framed: Framed::new(self.io, codec),
rx,
sink,
}
}
}
#[pin_project::pin_project]
pub struct ConnectResult<Io, St, Codec: Encoder + Decoder> {
pub struct ConnectResult<Io, St, Codec: Encoder + Decoder, Out> {
pub(crate) state: St,
pub(crate) out: Option<Out>,
pub(crate) framed: Framed<Io, Codec>,
pub(crate) rx: mpsc::Receiver<FramedMessage<<Codec as Encoder>::Item>>,
pub(crate) sink: Sink<<Codec as Encoder>::Item>,
}
impl<Io, St, Codec: Encoder + Decoder> ConnectResult<Io, St, Codec> {
#[inline]
pub fn sink(&self) -> &Sink<<Codec as Encoder>::Item> {
&self.sink
}
impl<Io, St, Codec: Encoder + Decoder, Out: Unpin> ConnectResult<Io, St, Codec, Out> {
#[inline]
pub fn get_ref(&self) -> &Io {
self.framed.get_ref()
@@ -65,18 +56,28 @@ impl<Io, St, Codec: Encoder + Decoder> ConnectResult<Io, St, Codec> {
self.framed.get_mut()
}
pub fn out<U>(self, out: U) -> ConnectResult<Io, St, Codec, U>
where
U: Stream<Item = <Codec as Encoder>::Item> + Unpin,
{
ConnectResult {
state: self.state,
framed: self.framed,
out: Some(out),
}
}
#[inline]
pub fn state<S>(self, state: S) -> ConnectResult<Io, S, Codec> {
pub fn state<S>(self, state: S) -> ConnectResult<Io, S, Codec, Out> {
ConnectResult {
state,
framed: self.framed,
rx: self.rx,
sink: self.sink,
out: self.out,
}
}
}
impl<Io, St, Codec> Stream for ConnectResult<Io, St, Codec>
impl<Io, St, Codec, Out> Stream for ConnectResult<Io, St, Codec, Out>
where
Io: AsyncRead + AsyncWrite,
Codec: Encoder + Decoder,
@@ -88,7 +89,8 @@ where
}
}
impl<Io, St, Codec> futures::Sink<<Codec as Encoder>::Item> for ConnectResult<Io, St, Codec>
impl<Io, St, Codec, Out> futures::Sink<<Codec as Encoder>::Item>
for ConnectResult<Io, St, Codec, Out>
where
Io: AsyncRead + AsyncWrite,
Codec: Encoder + Decoder,
@@ -96,7 +98,7 @@ where
type Error = <Codec as Encoder>::Error;
fn poll_ready(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
if self.framed.is_ready() {
if self.framed.is_write_ready() {
Poll::Ready(Ok(()))
} else {
Poll::Pending

View File

@@ -1,87 +1,56 @@
//! 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 actix_service::Service;
use actix_utils::mpsc;
use futures::Stream;
use log::debug;
use crate::cell::Cell;
use crate::error::ServiceError;
use crate::item::Item;
use crate::sink::Sink;
type Request<S, U> = Item<S, U>;
type Request<U> = <U as Decoder>::Item;
type Response<U> = <U as Encoder>::Item;
pub(crate) enum FramedMessage<T> {
Message(T),
Close,
WaitClose(oneshot::Sender<()>),
}
/// FramedTransport - is a future that reads frames from Framed object
/// and pass then to the service.
#[pin_project::pin_project]
pub(crate) struct FramedDispatcher<St, S, T, U>
pub(crate) struct Dispatcher<S, T, U, Out>
where
St: Clone,
S: Service<Request = Request<St, U>, Response = Option<Response<U>>>,
S: Service<Request = Request<U>, Response = Option<Response<U>>>,
S::Error: 'static,
S::Future: 'static,
T: AsyncRead + AsyncWrite,
U: Encoder + Decoder,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: std::fmt::Debug,
Out: Stream<Item = <U as Encoder>::Item> + Unpin,
{
service: S,
sink: Sink<<U as Encoder>::Item>,
state: St,
dispatch_state: FramedState<S, U>,
sink: Option<Out>,
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<<U as Encoder>::Item, S::Error>>,
}
impl<St, S, T, U> FramedDispatcher<St, S, T, U>
impl<S, T, U, Out> Dispatcher<S, T, U, Out>
where
St: Clone,
S: Service<Request = Request<St, U>, Response = Option<Response<U>>>,
S: Service<Request = Request<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,
Out: Stream<Item = <U as Encoder>::Item> + Unpin,
{
pub(crate) fn new<F: IntoService<S>>(
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)>>,
) -> Self {
FramedDispatcher {
framed,
state,
pub(crate) fn new(framed: Framed<T, U>, service: S, sink: Option<Out>) -> Self {
Dispatcher {
sink,
disconnect,
rx: Some(rx),
service: service.into_service(),
dispatch_state: FramedState::Processing,
inner: Cell::new(FramedDispatcherInner {
buf: VecDeque::new(),
task: LocalWaker::new(),
}),
service,
framed,
rx: mpsc::channel().1,
state: FramedState::Processing,
}
}
}
@@ -90,307 +59,184 @@ enum FramedState<S: Service, U: Encoder + Decoder> {
Processing,
Error(ServiceError<S::Error, U>),
FramedError(ServiceError<S::Error, U>),
FlushAndStop(Vec<oneshot::Sender<()>>),
FlushAndStop,
Stopping,
}
impl<S: Service, U: Encoder + Decoder> FramedState<S, U> {
fn stop(&mut self, tx: Option<oneshot::Sender<()>>) {
match self {
FramedState::FlushAndStop(ref mut vec) => {
if let Some(tx) = tx {
vec.push(tx)
}
}
FramedState::Processing => {
*self = FramedState::FlushAndStop(if let Some(tx) = tx {
vec![tx]
} else {
Vec::new()
})
}
FramedState::Error(_) | FramedState::FramedError(_) | FramedState::Stopping => {
if let Some(tx) = tx {
let _ = tx.send(());
}
}
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<S, T, U, Out> Dispatcher<S, T, U, Out>
where
St: Clone,
S: Service<Request = Request<St, U>, Response = Option<Response<U>>>,
S: Service<Request = Request<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,
Out: Stream<Item = <U as Encoder>::Item> + Unpin,
{
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.state = FramedState::FramedError(ServiceError::Decoder(err));
return true;
}
Poll::Pending => return false,
Poll::Ready(None) => {
log::trace!("Client disconnected");
self.state = FramedState::Stopping;
return true;
}
};
let tx = self.rx.sender();
let fut = self.service.call(item);
actix_rt::spawn(async move {
let item = fut.await;
let item = match item {
Ok(Some(item)) => Ok(item),
Ok(None) => return,
Err(err) => Err(err),
};
let _ = tx.send(item);
});
}
Poll::Pending => return false,
Poll::Ready(Err(err)) => {
self.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(msg))) => {
if let Err(err) = self.framed.write(msg) {
self.state = FramedState::FramedError(ServiceError::Encoder(err));
return true;
}
continue;
}
Poll::Ready(Some(Err(err))) => {
self.state = FramedState::Error(ServiceError::Service(err));
return true;
}
Poll::Ready(None) | Poll::Pending => (),
}
if self.sink.is_some() {
match Pin::new(self.sink.as_mut().unwrap()).poll_next(cx) {
Poll::Ready(Some(msg)) => {
if let Err(err) = self.framed.write(msg) {
self.state =
FramedState::FramedError(ServiceError::Encoder(err));
return true;
}
continue;
}
Poll::Ready(None) => {
let _ = self.sink.take();
self.state = FramedState::FlushAndStop;
return true;
}
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 = 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.state {
FramedState::Processing => loop {
let read = self.poll_read(cx);
let write = self.poll_write(cx);
if read || write {
continue;
} else {
return 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(());
Poll::Ready(Err(self.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;
FramedState::FlushAndStop => {
// drain service responses
match Pin::new(&mut self.rx).poll_next(cx) {
Poll::Ready(Some(Ok(msg))) => {
if let Err(_) = self.framed.write(msg) {
return Poll::Ready(Ok(()));
}
}
Poll::Pending => return false,
Poll::Ready(None) => {
log::trace!("Client disconnected");
*dispatch_state = FramedState::Stopping;
return true;
Poll::Ready(Some(Err(_))) => return Poll::Ready(Ok(())),
Poll::Ready(None) | Poll::Pending => (),
}
// flush io
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(())
},
));
}
Poll::Pending => return false,
Poll::Ready(Err(err)) => {
*dispatch_state = FramedState::Error(ServiceError::Service(err));
return true;
Poll::Ready(Ok(()))
}
FramedState::FramedError(_) => Poll::Ready(Err(self.state.take_framed_error())),
FramedState::Stopping => 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
}

View File

@@ -1,82 +0,0 @@
use std::fmt;
use std::ops::{Deref, DerefMut};
use actix_codec::{Decoder, Encoder};
use crate::sink::Sink;
pub struct Item<St, Codec: Encoder + Decoder> {
state: St,
sink: Sink<<Codec as Encoder>::Item>,
item: <Codec as Decoder>::Item,
}
impl<St, Codec> Item<St, Codec>
where
Codec: Encoder + Decoder,
{
pub(crate) fn new(
state: St,
sink: Sink<<Codec as Encoder>::Item>,
item: <Codec as Decoder>::Item,
) -> Self {
Item { state, sink, item }
}
#[inline]
pub fn state(&self) -> &St {
&self.state
}
#[inline]
pub fn state_mut(&mut self) -> &mut St {
&mut self.state
}
#[inline]
pub fn sink(&self) -> &Sink<<Codec as Encoder>::Item> {
&self.sink
}
#[inline]
pub fn into_inner(self) -> <Codec as Decoder>::Item {
self.item
}
#[inline]
pub fn into_parts(self) -> (St, Sink<<Codec as Encoder>::Item>, <Codec as Decoder>::Item) {
(self.state, self.sink, self.item)
}
}
impl<St, Codec> Deref for Item<St, Codec>
where
Codec: Encoder + Decoder,
{
type Target = <Codec as Decoder>::Item;
#[inline]
fn deref(&self) -> &<Codec as Decoder>::Item {
&self.item
}
}
impl<St, Codec> DerefMut for Item<St, Codec>
where
Codec: Encoder + Decoder,
{
#[inline]
fn deref_mut(&mut self) -> &mut <Codec as Decoder>::Item {
&mut self.item
}
}
impl<St, Codec> fmt::Debug for Item<St, Codec>
where
Codec: Encoder + Decoder,
<Codec as Decoder>::Item: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("FramedItem").field(&self.item).finish()
}
}

View File

@@ -1,16 +1,11 @@
#![deny(rust_2018_idioms, warnings)]
// #![deny(rust_2018_idioms, warnings)]
#![allow(clippy::type_complexity, clippy::too_many_arguments)]
mod cell;
mod connect;
mod dispatcher;
mod error;
mod item;
mod service;
mod sink;
pub use self::connect::{Connect, ConnectResult};
pub use self::error::ServiceError;
pub use self::item::Item;
pub use self::service::{Builder, NewServiceBuilder, ServiceBuilder};
pub use self::sink::Sink;
pub use self::service::{Builder, FactoryBuilder};

View File

@@ -4,258 +4,265 @@ use std::pin::Pin;
use std::rc::Rc;
use std::task::{Context, Poll};
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder};
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
use actix_service::{IntoService, IntoServiceFactory, Service, ServiceFactory};
use either::Either;
use futures::future::{FutureExt, LocalBoxFuture};
use futures::{ready, Stream};
use pin_project::project;
use crate::connect::{Connect, ConnectResult};
use crate::dispatcher::FramedDispatcher;
use crate::dispatcher::Dispatcher;
use crate::error::ServiceError;
use crate::item::Item;
type RequestItem<S, U> = Item<S, U>;
type RequestItem<U> = <U as Decoder>::Item;
type ResponseItem<U> = Option<<U as Encoder>::Item>;
/// Service builder - structure that follows the builder pattern
/// for building instances for framed services.
pub struct Builder<St, Codec>(PhantomData<(St, Codec)>);
impl<St: Clone, Codec> Default for Builder<St, Codec> {
fn default() -> Builder<St, Codec> {
Builder::new()
}
pub struct Builder<St, C, Io, Codec, Out> {
connect: C,
_t: PhantomData<(St, Io, Codec, Out)>,
}
impl<St: Clone, Codec> Builder<St, Codec> {
pub fn new() -> Builder<St, Codec> {
Builder(PhantomData)
}
impl<St, C, Io, Codec, Out> Builder<St, C, Io, Codec, Out>
where
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec, Out>>,
Io: AsyncRead + AsyncWrite,
Codec: Decoder + Encoder,
<Codec as Encoder>::Item: 'static,
<Codec as Encoder>::Error: std::fmt::Debug,
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
{
/// Construct framed handler service with specified connect service
pub fn service<Io, C, F>(self, connect: F) -> ServiceBuilder<St, C, Io, Codec>
pub fn new<F>(connect: F) -> Builder<St, C, Io, Codec, Out>
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, Out>>,
Codec: Decoder + Encoder,
Out: Stream<Item = <Codec as Encoder>::Item>,
{
ServiceBuilder {
Builder {
connect: connect.into_service(),
disconnect: None,
_t: PhantomData,
}
}
/// Provide stream items handler service and construct service factory.
pub fn build<F, T>(self, service: F) -> FramedServiceImpl<St, C, T, Io, Codec, Out>
where
F: IntoServiceFactory<T>,
T: ServiceFactory<
Config = St,
Request = RequestItem<Codec>,
Response = ResponseItem<Codec>,
Error = C::Error,
InitError = C::Error,
>,
{
FramedServiceImpl {
connect: self.connect,
handler: Rc::new(service.into_factory()),
_t: PhantomData,
}
}
}
/// Service builder - structure that follows the builder pattern
/// for building instances for framed services.
pub struct FactoryBuilder<St, C, Io, Codec, Out> {
connect: C,
_t: PhantomData<(St, Io, Codec, Out)>,
}
impl<St, C, Io, Codec, Out> FactoryBuilder<St, C, Io, Codec, Out>
where
Io: AsyncRead + AsyncWrite,
C: ServiceFactory<
Config = (),
Request = Connect<Io, Codec>,
Response = ConnectResult<Io, St, Codec, Out>,
>,
Codec: Decoder + Encoder,
<Codec as Encoder>::Error: std::fmt::Debug,
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
{
/// 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 new<F>(connect: F) -> FactoryBuilder<St, C, Io, Codec, Out>
where
F: IntoServiceFactory<C>,
Io: AsyncRead + AsyncWrite,
C: ServiceFactory<
Config = (),
Request = Connect<Io>,
Response = ConnectResult<Io, St, Codec>,
Request = Connect<Io, Codec>,
Response = ConnectResult<Io, St, Codec, Out>,
>,
C::Error: 'static,
C::Future: 'static,
Codec: Decoder + Encoder,
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
{
NewServiceBuilder {
FactoryBuilder {
connect: connect.into_factory(),
disconnect: None,
_t: PhantomData,
}
}
}
pub struct ServiceBuilder<St, C, Io, Codec> {
connect: C,
disconnect: Option<Rc<dyn Fn(&mut 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,
Io: AsyncRead + AsyncWrite,
Codec: Decoder + Encoder,
<Codec as Encoder>::Item: 'static,
<Codec as Encoder>::Error: std::fmt::Debug,
{
/// Callback to execute on disconnect
///
/// Second parameter indicates error occured during disconnect.
pub fn disconnect<F, Out>(mut self, disconnect: F) -> Self
where
F: Fn(&mut St, bool) + 'static,
{
self.disconnect = Some(Rc::new(disconnect));
self
}
/// 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 build<F, T, Cfg>(self, service: F) -> FramedService<St, C, T, Io, Codec, Out, Cfg>
where
F: IntoServiceFactory<T>,
T: ServiceFactory<
Config = St,
Request = RequestItem<St, Codec>,
Response = ResponseItem<Codec>,
Error = C::Error,
InitError = C::Error,
> + 'static,
{
FramedServiceImpl {
connect: self.connect,
handler: Rc::new(service.into_factory()),
disconnect: self.disconnect.clone(),
_t: PhantomData,
}
}
}
pub struct NewServiceBuilder<St, C, Io, Codec> {
connect: C,
disconnect: Option<Rc<dyn Fn(&mut St, bool)>>,
_t: PhantomData<(St, Io, Codec)>,
}
impl<St, C, Io, Codec> NewServiceBuilder<St, C, Io, Codec>
where
St: Clone,
Io: AsyncRead + AsyncWrite,
C: ServiceFactory<
Config = (),
Request = Connect<Io>,
Response = ConnectResult<Io, St, Codec>,
>,
C::Error: 'static,
C::Future: 'static,
Codec: Decoder + Encoder,
<Codec as Encoder>::Item: 'static,
<Codec as Encoder>::Error: std::fmt::Debug,
{
/// Callback to execute on disconnect
///
/// Second parameter indicates error occured during disconnect.
pub fn disconnect<F>(mut self, disconnect: F) -> Self
where
F: Fn(&mut St, bool) + 'static,
{
self.disconnect = Some(Rc::new(disconnect));
self
}
pub fn finish<F, T, Cfg>(self, service: F) -> FramedService<St, C, T, Io, Codec, Cfg>
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<Codec>,
Response = ResponseItem<Codec>,
Error = C::Error,
InitError = C::Error,
>,
{
FramedService {
connect: self.connect,
handler: Rc::new(service.into_factory()),
disconnect: self.disconnect,
_t: PhantomData,
}
}
}
pub struct FramedService<St, C, T, Io, Codec, Cfg> {
pub struct FramedService<St, C, T, Io, Codec, Out, Cfg> {
connect: C,
handler: Rc<T>,
disconnect: Option<Rc<dyn Fn(&mut St, bool)>>,
_t: PhantomData<(St, Io, Codec, Cfg)>,
_t: PhantomData<(St, Io, Codec, Out, Cfg)>,
}
impl<St, C, T, Io, Codec, Cfg> ServiceFactory for FramedService<St, C, T, Io, Codec, Cfg>
impl<St, C, T, Io, Codec, Out, Cfg> ServiceFactory
for FramedService<St, C, T, Io, Codec, Out, Cfg>
where
St: Clone + 'static,
Io: AsyncRead + AsyncWrite,
C: ServiceFactory<
Config = (),
Request = Connect<Io>,
Response = ConnectResult<Io, St, Codec>,
Request = Connect<Io, Codec>,
Response = ConnectResult<Io, St, Codec, Out>,
>,
C::Error: 'static,
C::Future: 'static,
T: ServiceFactory<
Config = St,
Request = RequestItem<St, Codec>,
Response = ResponseItem<Codec>,
Error = C::Error,
InitError = C::Error,
> + 'static,
Config = St,
Request = RequestItem<Codec>,
Response = ResponseItem<Codec>,
Error = C::Error,
InitError = C::Error,
>,
<T::Service as Service>::Error: 'static,
<T::Service as Service>::Future: 'static,
Codec: Decoder + Encoder,
<Codec as Encoder>::Item: 'static,
<Codec as Encoder>::Error: std::fmt::Debug,
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
{
type Config = Cfg;
type Request = Io;
type Response = ();
type Error = ServiceError<C::Error, Codec>;
type InitError = C::InitError;
type Service = FramedServiceImpl<St, C::Service, T, Io, Codec>;
type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>;
type Service = FramedServiceImpl<St, C::Service, T, Io, Codec, Out>;
type Future = FramedServiceResponse<St, C, T, Io, Codec, Out>;
fn new_service(&self, _: Cfg) -> Self::Future {
let handler = self.handler.clone();
let disconnect = self.disconnect.clone();
// create connect service and then create service impl
self.connect
.new_service(())
.map(move |result| {
result.map(move |connect| FramedServiceImpl {
connect,
handler,
disconnect,
_t: PhantomData,
})
})
.boxed_local()
FramedServiceResponse {
fut: self.connect.new_service(()),
handler: self.handler.clone(),
}
}
}
pub struct FramedServiceImpl<St, C, T, Io, Codec> {
connect: C,
handler: Rc<T>,
disconnect: Option<Rc<dyn Fn(&mut St, bool)>>,
_t: PhantomData<(St, Io, Codec)>,
}
impl<St, C, T, Io, Codec> Service for FramedServiceImpl<St, C, T, Io, Codec>
#[pin_project::pin_project]
pub struct FramedServiceResponse<St, C, T, Io, Codec, Out>
where
St: Clone,
Io: AsyncRead + AsyncWrite,
C: Service<Request = Connect<Io>, Response = ConnectResult<Io, St, Codec>>,
C::Error: 'static,
C: ServiceFactory<
Config = (),
Request = Connect<Io, Codec>,
Response = ConnectResult<Io, St, Codec, Out>,
>,
T: ServiceFactory<
Config = St,
Request = RequestItem<St, Codec>,
Request = RequestItem<Codec>,
Response = ResponseItem<Codec>,
Error = C::Error,
InitError = C::Error,
>,
<T::Service as Service>::Error: 'static,
<T::Service as Service>::Future: 'static,
Codec: Decoder + Encoder,
<Codec as Encoder>::Item: 'static,
<Codec as Encoder>::Error: std::fmt::Debug,
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
{
#[pin]
fut: C::Future,
handler: Rc<T>,
}
impl<St, C, T, Io, Codec, Out> Future for FramedServiceResponse<St, C, T, Io, Codec, Out>
where
Io: AsyncRead + AsyncWrite,
C: ServiceFactory<
Config = (),
Request = Connect<Io, Codec>,
Response = ConnectResult<Io, St, Codec, Out>,
>,
T: ServiceFactory<
Config = St,
Request = RequestItem<Codec>,
Response = ResponseItem<Codec>,
Error = C::Error,
InitError = C::Error,
>,
<T::Service as Service>::Error: 'static,
<T::Service as Service>::Future: 'static,
Codec: Decoder + Encoder,
<Codec as Encoder>::Item: 'static,
<Codec as Encoder>::Error: std::fmt::Debug,
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
{
type Output = Result<FramedServiceImpl<St, C::Service, T, Io, Codec, Out>, C::InitError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
let connect = ready!(this.fut.poll(cx))?;
Poll::Ready(Ok(FramedServiceImpl {
connect,
handler: this.handler.clone(),
_t: PhantomData,
}))
}
}
pub struct FramedServiceImpl<St, C, T, Io, Codec, Out> {
connect: C,
handler: Rc<T>,
_t: PhantomData<(St, Io, Codec, Out)>,
}
impl<St, C, T, Io, Codec, Out> Service for FramedServiceImpl<St, C, T, Io, Codec, Out>
where
Io: AsyncRead + AsyncWrite,
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec, Out>>,
T: ServiceFactory<
Config = St,
Request = RequestItem<Codec>,
Response = ResponseItem<Codec>,
Error = C::Error,
InitError = C::Error,
>,
<T::Service as Service>::Error: 'static,
<T::Service as Service>::Future: 'static,
Codec: Decoder + Encoder,
<Codec as Encoder>::Item: 'static,
<Codec as Encoder>::Error: std::fmt::Debug,
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
{
type Request = Io;
type Response = ();
type Error = ServiceError<C::Error, Codec>;
type Future = FramedServiceImplResponse<St, Io, Codec, C, T>;
type Future = FramedServiceImplResponse<St, Io, Codec, Out, C, T>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.connect.poll_ready(cx).map_err(|e| e.into())
@@ -266,52 +273,51 @@ where
inner: FramedServiceImplResponseInner::Connect(
self.connect.call(Connect::new(req)),
self.handler.clone(),
self.disconnect.clone(),
),
}
}
}
#[pin_project::pin_project]
pub struct FramedServiceImplResponse<St, Io, Codec, C, T>
pub struct FramedServiceImplResponse<St, Io, Codec, Out, C, T>
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, Out>>,
T: ServiceFactory<
Config = St,
Request = RequestItem<St, Codec>,
Request = RequestItem<Codec>,
Response = ResponseItem<Codec>,
Error = C::Error,
InitError = C::Error,
>,
<T::Service as Service>::Error: 'static,
<T::Service as Service>::Future: 'static,
Io: AsyncRead + AsyncWrite,
Codec: Encoder + Decoder,
<Codec as Encoder>::Item: 'static,
<Codec as Encoder>::Error: std::fmt::Debug,
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
{
#[pin]
inner: FramedServiceImplResponseInner<St, Io, Codec, C, T>,
inner: FramedServiceImplResponseInner<St, Io, Codec, Out, C, T>,
}
impl<St, Io, Codec, C, T> Future for FramedServiceImplResponse<St, Io, Codec, C, T>
impl<St, Io, Codec, Out, C, T> Future for FramedServiceImplResponse<St, Io, Codec, Out, C, T>
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, Out>>,
T: ServiceFactory<
Config = St,
Request = RequestItem<St, Codec>,
Request = RequestItem<Codec>,
Response = ResponseItem<Codec>,
Error = C::Error,
InitError = C::Error,
>,
<T::Service as Service>::Error: 'static,
<T::Service as Service>::Future: 'static,
Io: AsyncRead + AsyncWrite,
Codec: Encoder + Decoder,
<Codec as Encoder>::Item: 'static,
<Codec as Encoder>::Error: std::fmt::Debug,
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
{
type Output = Result<(), ServiceError<C::Error, Codec>>;
@@ -331,92 +337,77 @@ where
}
#[pin_project::pin_project]
enum FramedServiceImplResponseInner<St, Io, Codec, C, T>
enum FramedServiceImplResponseInner<St, Io, Codec, Out, C, T>
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, Out>>,
T: ServiceFactory<
Config = St,
Request = RequestItem<St, Codec>,
Request = RequestItem<Codec>,
Response = ResponseItem<Codec>,
Error = C::Error,
InitError = C::Error,
>,
<T::Service as Service>::Error: 'static,
<T::Service as Service>::Future: 'static,
Io: AsyncRead + AsyncWrite,
Codec: Encoder + Decoder,
<Codec as Encoder>::Item: 'static,
<Codec as Encoder>::Error: std::fmt::Debug,
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
{
Connect(#[pin] C::Future, Rc<T>, Option<Rc<dyn Fn(&mut St, bool)>>),
Handler(
#[pin] T::Future,
Option<ConnectResult<Io, St, Codec>>,
Option<Rc<dyn Fn(&mut St, bool)>>,
),
Dispatcher(#[pin] FramedDispatcher<St, T::Service, Io, Codec>),
Connect(#[pin] C::Future, Rc<T>),
Handler(#[pin] T::Future, Option<Framed<Io, Codec>>, Option<Out>),
Dispatcher(Dispatcher<T::Service, Io, Codec, Out>),
}
impl<St, Io, Codec, C, T> FramedServiceImplResponseInner<St, Io, Codec, C, T>
impl<St, Io, Codec, Out, C, T> FramedServiceImplResponseInner<St, Io, Codec, Out, C, T>
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, Out>>,
T: ServiceFactory<
Config = St,
Request = RequestItem<St, Codec>,
Request = RequestItem<Codec>,
Response = ResponseItem<Codec>,
Error = C::Error,
InitError = C::Error,
>,
<T::Service as Service>::Error: 'static,
<T::Service as Service>::Future: 'static,
Io: AsyncRead + AsyncWrite,
Codec: Encoder + Decoder,
<Codec as Encoder>::Item: 'static,
<Codec as Encoder>::Error: std::fmt::Debug,
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
{
#[project]
fn poll(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Either<
FramedServiceImplResponseInner<St, Io, Codec, C, T>,
FramedServiceImplResponseInner<St, Io, Codec, Out, C, T>,
Poll<Result<(), ServiceError<C::Error, Codec>>>,
> {
#[project]
match self.project() {
FramedServiceImplResponseInner::Connect(fut, handler, disconnect) => {
FramedServiceImplResponseInner::Connect(fut, handler) => match fut.poll(cx) {
Poll::Ready(Ok(res)) => Either::Left(FramedServiceImplResponseInner::Handler(
handler.new_service(res.state),
Some(res.framed),
res.out,
)),
Poll::Pending => Either::Right(Poll::Pending),
Poll::Ready(Err(e)) => Either::Right(Poll::Ready(Err(e.into()))),
},
FramedServiceImplResponseInner::Handler(fut, framed, out) => {
match fut.poll(cx) {
Poll::Ready(Ok(res)) => {
Either::Left(FramedServiceImplResponseInner::Handler(
handler.new_service(res.state.clone()),
Some(res),
disconnect.take(),
Poll::Ready(Ok(handler)) => {
Either::Left(FramedServiceImplResponseInner::Dispatcher(
Dispatcher::new(framed.take().unwrap(), handler, out.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(),
),
))
}
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))
}

View File

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

View File

@@ -1,43 +1,49 @@
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;
use std::cell::Cell;
use std::rc::Rc;
use actix_codec::BytesCodec;
use actix_rt::time::delay_for;
use actix_service::{service_fn, Service};
use actix_service::{fn_factory_with_config, fn_service, IntoService, Service};
use actix_testing::TestServer;
use actix_utils::mpsc;
use bytes::{Bytes, BytesMut};
use futures::future::ok;
use actix_ioframe::{Builder, Connect};
use actix_ioframe::{Builder, Connect, FactoryBuilder};
#[derive(Clone)]
struct State;
struct State(Option<mpsc::Sender<Bytes>>);
#[actix_rt::test]
async fn test_disconnect() -> std::io::Result<()> {
let disconnect = Arc::new(AtomicBool::new(false));
let disconnect1 = disconnect.clone();
async fn test_basic() {
let client_item = Rc::new(Cell::new(false));
let srv = TestServer::with(move || {
let disconnect1 = disconnect1.clone();
Builder::new()
.factory(service_fn(|conn: Connect<_>| {
ok(conn.codec(BytesCodec).state(State))
}))
.disconnect(move |_, _| {
disconnect1.store(true, Ordering::Relaxed);
})
.finish(service_fn(|_t| ok(None)))
FactoryBuilder::new(fn_service(|conn: Connect<_, _>| {
ok(conn.codec(BytesCodec).state(State(None)))
}))
// echo
.build(fn_service(|t: BytesMut| ok(Some(t.freeze()))))
});
let mut client = Builder::new()
.service(|conn: Connect<_>| {
let conn = conn.codec(BytesCodec).state(State);
conn.sink().close();
ok(conn)
let item = client_item.clone();
let mut client = Builder::new(fn_service(move |conn: Connect<_, _>| {
async move {
let (tx, rx) = mpsc::channel();
let _ = tx.send(Bytes::from_static(b"Hello"));
Ok(conn.codec(BytesCodec).out(rx).state(State(Some(tx))))
}
}))
.build(fn_factory_with_config(move |mut cfg: State| {
let item = item.clone();
ok((move |t: BytesMut| {
assert_eq!(t.freeze(), Bytes::from_static(b"Hello"));
item.set(true);
// drop Sender, which will close connection
cfg.0.take();
ok::<_, ()>(None)
})
.finish(service_fn(|_t| ok(None)));
.into_service())
}));
let conn = actix_connect::default_connector()
.call(actix_connect::Connect::with(String::new(), srv.addr()))
@@ -45,8 +51,5 @@ async fn test_disconnect() -> std::io::Result<()> {
.unwrap();
client.call(conn.into_parts().0).await.unwrap();
let _ = delay_for(Duration::from_millis(100)).await;
assert!(disconnect.load(Ordering::Relaxed));
Ok(())
assert!(client_item.get());
}

View File

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

1
actix-macros/LICENSE-APACHE Symbolic link
View File

@@ -0,0 +1 @@
../LICENSE-APACHE

1
actix-macros/LICENSE-MIT Symbolic link
View File

@@ -0,0 +1 @@
../LICENSE-MIT

View File

@@ -17,25 +17,26 @@ use quote::quote;
#[proc_macro_attribute]
#[cfg(not(test))] // Work around for rust-lang/rust#62127
pub fn main(_: TokenStream, item: TokenStream) -> TokenStream {
let input = syn::parse_macro_input!(item as syn::ItemFn);
let ret = &input.sig.output;
let name = &input.sig.ident;
let inputs = &input.sig.inputs;
let body = &input.block;
let mut input = syn::parse_macro_input!(item as syn::ItemFn);
let attrs = &input.attrs;
let vis = &input.vis;
let sig = &mut input.sig;
let body = &input.block;
let name = &sig.ident;
if input.sig.asyncness.is_none() {
return syn::Error::new_spanned(input.sig.fn_token, "only async fn is supported")
if sig.asyncness.is_none() {
return syn::Error::new_spanned(sig.fn_token, "only async fn is supported")
.to_compile_error()
.into();
}
sig.asyncness = None;
(quote! {
#(#attrs)*
fn #name(#inputs) #ret {
actix_rt::System::new("main")
.block_on(async { #body })
#vis #sig {
actix_rt::System::new(stringify!(#name))
.block_on(async move { #body })
}
})
.into()
@@ -70,7 +71,7 @@ pub fn test(_: TokenStream, item: TokenStream) -> TokenStream {
if input.sig.asyncness.is_none() {
return syn::Error::new_spanned(
input.sig.fn_token,
format!("only async fn is supported, {:?}", input.sig.ident),
format!("only async fn is supported, {}", input.sig.ident),
)
.to_compile_error()
.into();

View File

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

View File

@@ -1,6 +1,6 @@
[package]
name = "actix-rt"
version = "1.0.0-alpha.3"
version = "1.0.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix runtime"
keywords = ["network", "framework", "async", "futures"]
@@ -9,17 +9,15 @@ repository = "https://github.com/actix/actix-net.git"
documentation = "https://docs.rs/actix-rt/"
categories = ["network-programming", "asynchronous"]
license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
edition = "2018"
workspace = ".."
[lib]
name = "actix_rt"
path = "src/lib.rs"
[dependencies]
actix-macros = "0.1.0-alpha.1"
actix-macros = "0.1.0"
actix-threadpool = "0.3"
futures = "0.3.1"
copyless = "0.1.4"
tokio = { version = "0.2.4", default-features=false, features = ["rt-core", "rt-util", "io-driver", "tcp", "uds", "udp", "time", "signal", "stream"] }
tokio = { version = "0.2.6", default-features=false, features = ["rt-core", "rt-util", "io-driver", "tcp", "uds", "udp", "time", "signal", "stream"] }

View File

@@ -42,8 +42,8 @@ impl fmt::Debug for ArbiterCommand {
#[derive(Debug)]
/// Arbiters provide an asynchronous execution environment for actors, functions
/// and futures. When an Arbiter is created, they spawn a new OS thread, and
/// host an event loop. Some Arbiter functions execute on the current thread.
/// and futures. When an Arbiter is created, it spawns a new OS thread, and
/// hosts an event loop. Some Arbiter functions execute on the current thread.
pub struct Arbiter {
sender: UnboundedSender<ArbiterCommand>,
thread_handle: Option<thread::JoinHandle<()>>,

View File

@@ -1,5 +1,24 @@
# Changes
## [1.0.1] - 2019-12-29
### Changed
* Rename `.start()` method to `.run()`
## [1.0.0] - 2019-12-11
### Changed
* Use actix-net releases
## [1.0.0-alpha.4] - 2019-12-08
### Changed
* Use actix-service 1.0.0-alpha.4
## [1.0.0-alpha.3] - 2019-12-07
### Changed

View File

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

View File

@@ -31,7 +31,7 @@ pub struct ServerBuilder {
backlog: i32,
workers: Vec<(usize, WorkerClient)>,
services: Vec<Box<dyn InternalServiceFactory>>,
sockets: Vec<(Token, StdListener)>,
sockets: Vec<(Token, String, StdListener)>,
accept: AcceptLoop,
exit: bool,
shutdown_timeout: Duration,
@@ -146,8 +146,8 @@ impl ServerBuilder {
let mut srv = ConfiguredService::new(apply);
for (name, lst) in cfg.services {
let token = self.token.next();
srv.stream(token, name, lst.local_addr()?);
self.sockets.push((token, StdListener::Tcp(lst)));
srv.stream(token, name.clone(), lst.local_addr()?);
self.sockets.push((token, name, StdListener::Tcp(lst)));
}
self.services.push(Box::new(srv));
}
@@ -172,7 +172,8 @@ impl ServerBuilder {
factory.clone(),
lst.local_addr()?,
));
self.sockets.push((token, StdListener::Tcp(lst)));
self.sockets
.push((token, name.as_ref().to_string(), StdListener::Tcp(lst)));
}
Ok(self)
}
@@ -222,7 +223,8 @@ impl ServerBuilder {
factory.clone(),
addr,
));
self.sockets.push((token, StdListener::Uds(lst)));
self.sockets
.push((token, name.as_ref().to_string(), StdListener::Uds(lst)));
Ok(self)
}
@@ -243,36 +245,18 @@ impl ServerBuilder {
factory,
lst.local_addr()?,
));
self.sockets.push((token, StdListener::Tcp(lst)));
self.sockets
.push((token, name.as_ref().to_string(), StdListener::Tcp(lst)));
Ok(self)
}
/// Spawn new thread and start listening for incoming connections.
///
/// This method spawns new thread and starts new actix system. Other than
/// that it is similar to `start()` method. This method blocks.
///
/// This methods panics if no socket addresses get bound.
///
/// ```rust,ignore
/// use actix_web::*;
///
/// fn main() -> std::io::Result<()> {
/// Server::new().
/// .service(
/// HttpServer::new(|| App::new().service(web::service("/").to(|| HttpResponse::Ok())))
/// .bind("127.0.0.1:0")
/// .run()
/// }
/// ```
pub fn run(self) -> io::Result<()> {
let sys = System::new("http-server");
self.start();
sys.run()
#[doc(hidden)]
pub fn start(self) -> Server {
self.run()
}
/// Starts processing incoming connections and return server controller.
pub fn start(mut self) -> Server {
pub fn run(mut self) -> Server {
if self.sockets.is_empty() {
panic!("Server should have at least one bound socket");
} else {
@@ -288,10 +272,15 @@ impl ServerBuilder {
// start accept thread
for sock in &self.sockets {
info!("Starting server on {}", sock.1);
info!("Starting \"{}\" service on {}", sock.1, sock.2);
}
self.accept
.start(mem::replace(&mut self.sockets, Vec::new()), workers);
self.accept.start(
mem::replace(&mut self.sockets, Vec::new())
.into_iter()
.map(|t| (t.0, t.2))
.collect(),
workers,
);
// handle signals
if !self.no_signals {
@@ -391,7 +380,7 @@ impl ServerBuilder {
.await;
System::current().stop();
}
.boxed(),
.boxed(),
);
}
ready(())

View File

@@ -142,7 +142,7 @@ impl InternalServiceFactory for ConfiguredService {
let name = names.remove(&token).unwrap().0;
res.push((
token,
Box::new(StreamService::new(actix::service_fn2(
Box::new(StreamService::new(actix::fn_service(
move |_: TcpStream| {
error!("Service {:?} is not configured", name);
ok::<_, ()>(())
@@ -153,7 +153,7 @@ impl InternalServiceFactory for ConfiguredService {
}
return Ok(res);
}
.boxed_local()
.boxed_local()
}
}
@@ -280,6 +280,6 @@ where
}
};
}
.boxed_local()
.boxed_local()
}
}

View File

@@ -217,7 +217,7 @@ impl Worker {
wrk.await
});
}
.boxed(),
.boxed(),
);
WorkerClient::new(idx, tx1, tx2, avail)

View File

@@ -6,7 +6,7 @@ use std::{net, thread, time};
use actix_codec::{BytesCodec, Framed};
use actix_rt::net::TcpStream;
use actix_server::Server;
use actix_service::service_fn;
use actix_service::fn_service;
use bytes::Bytes;
use futures::future::{lazy, ok};
use futures::SinkExt;
@@ -31,7 +31,7 @@ fn test_bind() {
let srv = Server::build()
.workers(1)
.disable_signals()
.bind("test", addr, move || service_fn(|_| ok::<_, ()>(())))
.bind("test", addr, move || fn_service(|_| ok::<_, ()>(())))
.unwrap()
.start();
let _ = tx.send((srv, actix_rt::System::current()));
@@ -56,7 +56,7 @@ fn test_listen() {
Server::build()
.disable_signals()
.workers(1)
.listen("test", lst, move || service_fn(|_| ok::<_, ()>(())))
.listen("test", lst, move || fn_service(|_| ok::<_, ()>(())))
.unwrap()
.start();
let _ = tx.send(actix_rt::System::current());
@@ -82,7 +82,7 @@ fn test_start() {
.backlog(100)
.disable_signals()
.bind("test", addr, move || {
service_fn(|io: TcpStream| {
fn_service(|io: TcpStream| {
async move {
let mut f = Framed::new(io, BytesCodec);
f.send(Bytes::from_static(b"test")).await.unwrap();
@@ -158,8 +158,8 @@ fn test_configure() {
.listen("addr3", lst)
.apply(move |rt| {
let num = num.clone();
rt.service("addr1", service_fn(|_| ok::<_, ()>(())));
rt.service("addr3", service_fn(|_| ok::<_, ()>(())));
rt.service("addr1", fn_service(|_| ok::<_, ()>(())));
rt.service("addr3", fn_service(|_| ok::<_, ()>(())));
rt.on_start(lazy(move |_| {
let _ = num.fetch_add(1, Relaxed);
}))

View File

@@ -1,5 +1,43 @@
# Changes
## [1.0.3] - 2020-01-15
### Fixed
* Fixed unsoundness in `AndThenService` impl
## [1.0.2] - 2020-01-08
### Added
* Add `into_service` helper function
## [1.0.1] - 2019-12-22
### Changed
* `map_config()` and `unit_config()` accepts `IntoServiceFactory` type
## [1.0.0] - 2019-12-11
### Added
* Add Clone impl for Apply service
## [1.0.0-alpha.4] - 2019-12-08
### Changed
* Renamed `service_fn` to `fn_service`
* Renamed `factory_fn` to `fn_factory`
* Renamed `factory_fn_cfg` to `fn_factory_with_config`
## [1.0.0-alpha.3] - 2019-12-06
### Changed

View File

@@ -1,17 +1,15 @@
[package]
name = "actix-service"
version = "1.0.0-alpha.3"
version = "1.0.3"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix Service"
description = "Actix service"
keywords = ["network", "framework", "async", "futures"]
homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-net.git"
documentation = "https://docs.rs/actix-service/"
categories = ["network-programming", "asynchronous"]
license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
edition = "2018"
workspace = ".."
[badges]
travis-ci = { repository = "actix/actix-service", branch = "master" }
@@ -27,4 +25,4 @@ futures-util = "0.3.1"
pin-project = "0.4.6"
[dev-dependencies]
actix-rt = "1.0.0-alpha.2"
actix-rt = "1.0.0"

View File

@@ -258,7 +258,7 @@ mod tests {
use futures_util::future::{lazy, ok, ready, Ready};
use crate::{factory_fn, pipeline, pipeline_factory, Service, ServiceFactory};
use crate::{fn_factory, pipeline, pipeline_factory, Service, ServiceFactory};
struct Srv1(Rc<Cell<usize>>);
@@ -320,7 +320,7 @@ mod tests {
let cnt = Rc::new(Cell::new(0));
let cnt2 = cnt.clone();
let new_srv =
pipeline_factory(factory_fn(move || ready(Ok::<_, ()>(Srv1(cnt2.clone())))))
pipeline_factory(fn_factory(move || ready(Ok::<_, ()>(Srv1(cnt2.clone())))))
.and_then(move || ready(Ok(Srv2(cnt.clone()))));
let mut srv = new_srv.new_service(()).await.unwrap();

View File

@@ -283,7 +283,7 @@ mod tests {
use futures_util::future::{lazy, ok, Ready, TryFutureExt};
use crate::{pipeline, pipeline_factory, service_fn2, Service, ServiceFactory};
use crate::{fn_service, pipeline, pipeline_factory, Service, ServiceFactory};
#[derive(Clone)]
struct Srv;
@@ -318,7 +318,7 @@ mod tests {
#[actix_rt::test]
async fn test_service_factory() {
let new_srv = pipeline_factory(|| ok::<_, ()>(service_fn2(|r: &'static str| ok(r))))
let new_srv = pipeline_factory(|| ok::<_, ()>(fn_service(|r: &'static str| ok(r))))
.and_then_apply_fn(
|| ok(Srv),
|req: &'static str, s| s.call(()).map_ok(move |res| (req, res)),

View File

@@ -5,7 +5,7 @@ use std::task::{Context, Poll};
use super::{IntoService, IntoServiceFactory, Service, ServiceFactory};
/// Apply tranform function to a service
/// Apply tranform function to a service.
pub fn apply_fn<T, F, R, In, Out, Err, U>(service: U, f: F) -> Apply<T, F, R, In, Out, Err>
where
T: Service<Error = Err>,
@@ -16,7 +16,7 @@ where
Apply::new(service.into_service(), f)
}
/// Create factory for `apply` service.
/// Service factory that prodices `apply_fn` service.
pub fn apply_fn_factory<T, F, R, In, Out, Err, U>(
service: U,
f: F,
@@ -56,6 +56,21 @@ where
}
}
impl<T, F, R, In, Out, Err> Clone for Apply<T, F, R, In, Out, Err>
where
T: Service<Error = Err> + Clone,
F: FnMut(In, &mut T) -> R + Clone,
R: Future<Output = Result<Out, Err>>,
{
fn clone(&self) -> Self {
Apply {
service: self.service.clone(),
f: self.f.clone(),
r: PhantomData,
}
}
}
impl<T, F, R, In, Out, Err> Service for Apply<T, F, R, In, Out, Err>
where
T: Service<Error = Err>,

View File

@@ -6,7 +6,7 @@ use std::task::{Context, Poll};
use crate::cell::Cell;
use crate::{Service, ServiceFactory};
/// Convert `Fn(&Config, &mut Service) -> Future<Service>` fn to a NewService
/// Convert `Fn(Config, &mut Service1) -> Future<Service2>` fn to a service factory
pub fn apply_cfg<F, C, T, R, S, E>(srv: T, f: F) -> ApplyConfigService<F, C, T, R, S, E>
where
F: FnMut(C, &mut T) -> R,
@@ -20,10 +20,11 @@ where
}
}
/// Convert `Fn(&Config, &mut Service) -> Future<Service>` fn to a NewService
/// Service get constructor from NewService.
/// Convert `Fn(Config, &mut Service1) -> Future<Service2>` fn to a service factory
///
/// Service1 get constructed from `T` factory.
pub fn apply_cfg_factory<F, C, T, R, S>(
srv: T,
factory: T,
f: F,
) -> ApplyConfigServiceFactory<F, C, T, R, S>
where
@@ -34,12 +35,12 @@ where
S: Service,
{
ApplyConfigServiceFactory {
srv: Cell::new((srv, f)),
srv: Cell::new((factory, f)),
_t: PhantomData,
}
}
/// Convert `Fn(&Config) -> Future<Service>` fn to NewService\
/// Convert `Fn(Config, &mut Server) -> Future<Service>` fn to NewService\
pub struct ApplyConfigService<F, C, T, R, S, E>
where
F: FnMut(C, &mut T) -> R,

View File

@@ -13,7 +13,7 @@ pub type BoxService<Req, Res, Err> =
pub struct BoxServiceFactory<C, Req, Res, Err, InitErr>(Inner<C, Req, Res, Err, InitErr>);
/// Create boxed new service
/// Create boxed service factory
pub fn factory<T>(
factory: T,
) -> BoxServiceFactory<T::Config, T::Request, T::Response, T::Error, T::InitError>

View File

@@ -7,7 +7,7 @@ use futures_util::future::{ok, Ready};
use crate::{IntoService, IntoServiceFactory, Service, ServiceFactory};
/// Create `ServiceFactory` for function that can act as a `Service`
pub fn service_fn<F, Fut, Req, Res, Err, Cfg>(
pub fn fn_service<F, Fut, Req, Res, Err, Cfg>(
f: F,
) -> FnServiceFactory<F, Fut, Req, Res, Err, Cfg>
where
@@ -17,16 +17,43 @@ where
FnServiceFactory::new(f)
}
pub fn service_fn2<F, Fut, Req, Res, Err>(f: F) -> FnService<F, Fut, Req, Res, Err>
where
F: FnMut(Req) -> Fut,
Fut: Future<Output = Result<Res, Err>>,
{
FnService::new(f)
}
/// Create `ServiceFactory` for function that can produce services
pub fn factory_fn<F, Cfg, Srv, Fut, Err>(f: F) -> FnServiceNoConfig<F, Cfg, Srv, Fut, Err>
///
/// # Example
///
/// ```rust
/// use std::io;
/// use actix_service::{fn_factory, fn_service, Service, ServiceFactory};
/// use futures_util::future::ok;
///
/// /// Service that divides two usize values.
/// async fn div((x, y): (usize, usize)) -> Result<usize, io::Error> {
/// if y == 0 {
/// Err(io::Error::new(io::ErrorKind::Other, "divide by zdro"))
/// } else {
/// Ok(x / y)
/// }
/// }
///
/// #[actix_rt::main]
/// async fn main() -> io::Result<()> {
/// // Create service factory that produces `div` services
/// let factory = fn_factory(|| {
/// ok::<_, io::Error>(fn_service(div))
/// });
///
/// // construct new service
/// let mut srv = factory.new_service(()).await?;
///
/// // now we can use `div` service
/// let result = srv.call((10, 20)).await?;
///
/// println!("10 / 20 = {}", result);
///
/// Ok(())
/// }
/// ```
pub fn fn_factory<F, Cfg, Srv, Fut, Err>(f: F) -> FnServiceNoConfig<F, Cfg, Srv, Fut, Err>
where
Srv: Service,
F: Fn() -> Fut,
@@ -35,8 +62,39 @@ where
FnServiceNoConfig::new(f)
}
/// Create `ServiceFactory` for function that can produce services with configuration
pub fn factory_fn_cfg<F, Fut, Cfg, Srv, Err>(f: F) -> FnServiceConfig<F, Fut, Cfg, Srv, Err>
/// Create `ServiceFactory` for function that accepts config argument and can produce services
///
/// Any function that has following form `Fn(Config) -> Future<Output = Service>` could
/// act as a `ServiceFactory`.
///
/// # Example
///
/// ```rust
/// use std::io;
/// use actix_service::{fn_factory_with_config, fn_service, Service, ServiceFactory};
/// use futures_util::future::ok;
///
/// #[actix_rt::main]
/// async fn main() -> io::Result<()> {
/// // Create service factory. factory uses config argument for
/// // services it generates.
/// let factory = fn_factory_with_config(|y: usize| {
/// ok::<_, io::Error>(fn_service(move |x: usize| ok::<_, io::Error>(x * y)))
/// });
///
/// // construct new service with config argument
/// let mut srv = factory.new_service(10).await?;
///
/// let result = srv.call(10).await?;
/// assert_eq!(result, 100);
///
/// println!("10 * 10 = {}", result);
/// Ok(())
/// }
/// ```
pub fn fn_factory_with_config<F, Fut, Cfg, Srv, Err>(
f: F,
) -> FnServiceConfig<F, Fut, Cfg, Srv, Err>
where
F: Fn(Cfg) -> Fut,
Fut: Future<Output = Result<Srv, Err>>,
@@ -132,6 +190,25 @@ where
}
}
impl<F, Fut, Req, Res, Err> Service for FnServiceFactory<F, Fut, Req, Res, Err, ()>
where
F: FnMut(Req) -> Fut + Clone,
Fut: Future<Output = Result<Res, Err>>,
{
type Request = Req;
type Response = Res;
type Error = Err;
type Future = Fut;
fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, req: Self::Request) -> Self::Future {
(self.f)(req)
}
}
impl<F, Fut, Req, Res, Err, Cfg> ServiceFactory for FnServiceFactory<F, Fut, Req, Res, Err, Cfg>
where
F: FnMut(Req) -> Fut + Clone,
@@ -280,3 +357,47 @@ where
FnServiceNoConfig::new(self)
}
}
#[cfg(test)]
mod tests {
use std::task::Poll;
use futures_util::future::{lazy, ok};
use super::*;
use crate::{Service, ServiceFactory};
#[actix_rt::test]
async fn test_fn_service() {
let new_srv = fn_service(|()| ok::<_, ()>("srv"));
let mut srv = new_srv.new_service(()).await.unwrap();
let res = srv.call(()).await;
assert_eq!(lazy(|cx| srv.poll_ready(cx)).await, Poll::Ready(Ok(())));
assert!(res.is_ok());
assert_eq!(res.unwrap(), "srv");
}
#[actix_rt::test]
async fn test_fn_service_service() {
let mut srv = fn_service(|()| ok::<_, ()>("srv"));
let res = srv.call(()).await;
assert_eq!(lazy(|cx| srv.poll_ready(cx)).await, Poll::Ready(Ok(())));
assert!(res.is_ok());
assert_eq!(res.unwrap(), "srv");
}
#[actix_rt::test]
async fn test_fn_service_with_config() {
let new_srv = fn_factory_with_config(|cfg: usize| {
ok::<_, ()>(fn_service(move |()| ok::<_, ()>(("srv", cfg))))
});
let mut srv = new_srv.new_service(1).await.unwrap();
let res = srv.call(()).await;
assert_eq!(lazy(|cx| srv.poll_ready(cx)).await, Poll::Ready(Ok(())));
assert!(res.is_ok());
assert_eq!(res.unwrap(), ("srv", 1));
}
}

View File

@@ -25,12 +25,48 @@ mod transform_err;
pub use self::apply::{apply_fn, apply_fn_factory};
pub use self::apply_cfg::{apply_cfg, apply_cfg_factory};
pub use self::fn_service::{factory_fn, factory_fn_cfg, service_fn, service_fn2};
pub use self::fn_service::{fn_factory, fn_factory_with_config, fn_service};
pub use self::map_config::{map_config, unit_config};
pub use self::pipeline::{pipeline, pipeline_factory, Pipeline, PipelineFactory};
pub use self::transform::{apply, Transform};
/// An asynchronous function from `Request` to a `Response`.
///
/// `Service` represents a service that represanting interation, taking requests and giving back
/// replies. You can think about service as a function with one argument and result as a return
/// type. In general form it looks like `async fn(Req) -> Result<Res, Err>`. `Service`
/// trait just generalizing form of this function. Each parameter described as an assotiated type.
///
/// Services provides a symmetric and uniform API, same abstractions represents
/// clients and servers. Services describe only `transforamtion` operation
/// which encorouge to simplify api surface and phrases `value transformation`.
/// That leads to simplier design of each service. That also allows better testability
/// and better composition.
///
/// Services could be represented in several different forms. In general,
/// Service is a type that implements `Service` trait.
///
/// ```rust,ignore
/// struct MyService;
///
/// impl Service for MyService {
/// type Request = u8;
/// type Response = u64;
/// type Error = MyError;
/// type Future = Pin<Box<Future<Output=Result<Self::Response, Self::Error>>>;
///
/// fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { ... }
///
/// fn call(&mut self, req: Self::Request) -> Self::Future { ... }
/// }
/// ```
///
/// Service can have mutable state that influence computation.
/// This service could be rewritten as a simple function:
///
/// ```rust,ignore
/// async fn my_service(req: u8) -> Result<u64, MyError>;
/// ```
pub trait Service {
/// Requests handled by the service.
type Request;
@@ -46,13 +82,19 @@ pub trait Service {
/// Returns `Ready` when the service is able to process requests.
///
/// If the service is at capacity, then `NotReady` is returned and the task
/// If the service is at capacity, then `Pending` is returned and the task
/// is notified when the service becomes ready again. This function is
/// expected to be called while on a task.
///
/// This is a **best effort** implementation. False positives are permitted.
/// It is permitted for the service to return `Ready` from a `poll_ready`
/// call and the next invocation of `call` results in an error.
///
/// There are several notes to consider:
///
/// 1. `.poll_ready()` might be called on different task from actual service call.
///
/// 2. In case of chained services, `.poll_ready()` get called for all services at once.
fn poll_ready(&mut self, ctx: &mut task::Context<'_>) -> Poll<Result<(), Self::Error>>;
/// Process the request and return the response asynchronously.
@@ -287,7 +329,7 @@ pub trait IntoServiceFactory<T>
where
T: ServiceFactory,
{
/// Convert `Self` an `ServiceFactory`
/// Convert `Self` to a `ServiceFactory`
fn into_factory(self) -> T;
}
@@ -309,6 +351,15 @@ where
}
}
/// Convert object of type `T` to a service `S`
pub fn into_service<T, S>(tp: T) -> S
where
S: Service,
T: IntoService<S>,
{
tp.into_service()
}
pub mod dev {
pub use crate::and_then::{AndThenService, AndThenServiceFactory};
pub use crate::and_then_apply_fn::{AndThenApplyFn, AndThenApplyFnFactory};

View File

@@ -1,25 +1,30 @@
use std::marker::PhantomData;
use super::ServiceFactory;
use super::{IntoServiceFactory, ServiceFactory};
/// Adapt external config to a config for provided new service
pub fn map_config<T, F, C>(factory: T, f: F) -> MapConfig<T, F, C>
/// Adapt external config argument to a config for provided service factory
///
/// Note that this function consumes the receiving service factory and returns
/// a wrapped version of it.
pub fn map_config<T, U, F, C>(factory: U, f: F) -> MapConfig<T, F, C>
where
T: ServiceFactory,
U: IntoServiceFactory<T>,
F: Fn(C) -> T::Config,
{
MapConfig::new(factory, f)
MapConfig::new(factory.into_factory(), f)
}
/// Replace config with unit
pub fn unit_config<T, C>(new_service: T) -> UnitConfig<T, C>
pub fn unit_config<T, U, C>(factory: U) -> UnitConfig<T, C>
where
T: ServiceFactory<Config = ()>,
U: IntoServiceFactory<T>,
{
UnitConfig::new(new_service)
UnitConfig::new(factory.into_factory())
}
/// `.map_config()` service combinator
/// `map_config()` adapter service factory
pub struct MapConfig<A, F, C> {
a: A,
f: F,

View File

@@ -9,6 +9,7 @@ use crate::map_init_err::MapInitErr;
use crate::then::{ThenService, ThenServiceFactory};
use crate::{IntoService, IntoServiceFactory, Service, ServiceFactory};
/// Contruct new pipeline with one service in pipeline chain.
pub fn pipeline<F, T>(service: F) -> Pipeline<T>
where
F: IntoService<T>,
@@ -19,6 +20,7 @@ where
}
}
/// Contruct new pipeline factory with one service factory.
pub fn pipeline_factory<T, F>(factory: F) -> PipelineFactory<T>
where
T: ServiceFactory,
@@ -29,7 +31,7 @@ where
}
}
/// Pipeline service
/// Pipeline service - pipeline allows to compose multiple service into one service.
pub struct Pipeline<T> {
service: T,
}
@@ -48,7 +50,7 @@ impl<T: Service> Pipeline<T> {
where
Self: Sized,
F: IntoService<U>,
U: Service<Request = T::Response, Error = T::Error>,
U: Service<Request = T::Response, Error = T::Error> + 'static,
{
Pipeline {
service: AndThenService::new(self.service, service.into_service()),
@@ -67,7 +69,7 @@ impl<T: Service> Pipeline<T> {
where
Self: Sized,
I: IntoService<U>,
U: Service,
U: Service + 'static,
F: FnMut(T::Response, &mut U) -> Fut,
Fut: Future<Output = Result<Res, Err>>,
Err: From<T::Error> + From<U::Error>,
@@ -86,7 +88,7 @@ impl<T: Service> Pipeline<T> {
where
Self: Sized,
F: IntoService<U>,
U: Service<Request = Result<T::Response, T::Error>, Error = T::Error>,
U: Service<Request = Result<T::Response, T::Error>, Error = T::Error> + 'static,
{
Pipeline {
service: ThenService::new(self.service, service.into_service()),
@@ -159,7 +161,7 @@ impl<T: Service> Service for Pipeline<T> {
}
}
/// Pipeline constructor
/// Pipeline factory
pub struct PipelineFactory<T> {
factory: T,
}
@@ -177,6 +179,7 @@ impl<T: ServiceFactory> PipelineFactory<T> {
Error = T::Error,
InitError = T::InitError,
>,
U::Service: 'static,
{
PipelineFactory {
factory: AndThenServiceFactory::new(self.factory, factory.into_factory()),
@@ -197,6 +200,7 @@ impl<T: ServiceFactory> PipelineFactory<T> {
T::Config: Clone,
I: IntoServiceFactory<U>,
U: ServiceFactory<Config = T::Config, InitError = T::InitError>,
U::Service: 'static,
F: FnMut(T::Response, &mut U::Service) -> Fut + Clone,
Fut: Future<Output = Result<Res, Err>>,
Err: From<T::Error> + From<U::Error>,
@@ -223,6 +227,7 @@ impl<T: ServiceFactory> PipelineFactory<T> {
Error = T::Error,
InitError = T::InitError,
>,
U::Service: 'static,
{
PipelineFactory {
factory: ThenServiceFactory::new(self.factory, factory.into_factory()),

View File

@@ -7,23 +7,88 @@ use std::task::{Context, Poll};
use crate::transform_err::TransformMapInitErr;
use crate::{IntoServiceFactory, Service, ServiceFactory};
/// Apply transform to a service. Function returns
/// services factory that in initialization creates
/// service and applies transform to this service.
pub fn apply<T, S, U>(t: T, service: U) -> ApplyTransform<T, S>
/// Apply transform to a service.
pub fn apply<T, S, U>(t: T, factory: U) -> ApplyTransform<T, S>
where
S: ServiceFactory,
T: Transform<S::Service, InitError = S::InitError>,
U: IntoServiceFactory<S>,
{
ApplyTransform::new(t, service.into_factory())
ApplyTransform::new(t, factory.into_factory())
}
/// The `Transform` trait defines the interface of a service factory that wraps inner service
/// during construction.
///
/// Transform(middleware) wraps inner service and runs during
/// inbound and/or outbound processing in the request/response lifecycle.
/// It may modify request and/or response.
///
/// For example, timeout transform:
///
/// ```rust,ignore
/// pub struct Timeout<S> {
/// service: S,
/// timeout: Duration,
/// }
///
/// impl<S> Service for Timeout<S>
/// where
/// S: Service,
/// {
/// type Request = S::Request;
/// type Response = S::Response;
/// type Error = TimeoutError<S::Error>;
/// type Future = TimeoutServiceResponse<S>;
///
/// fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
/// ready!(self.service.poll_ready(cx)).map_err(TimeoutError::Service)
/// }
///
/// fn call(&mut self, req: S::Request) -> Self::Future {
/// TimeoutServiceResponse {
/// fut: self.service.call(req),
/// sleep: Delay::new(clock::now() + self.timeout),
/// }
/// }
/// }
/// ```
///
/// Timeout service in above example is decoupled from underlying service implementation
/// and could be applied to any service.
///
/// The `Transform` trait defines the interface of a Service factory. `Transform`
/// is often implemented for middleware, defining how to construct a
/// middleware Service. A Service that is constructed by the factory takes
/// the Service that follows it during execution as a parameter, assuming
/// ownership of the next Service.
///
/// Factory for `Timeout` middleware from the above example could look like this:
///
/// ```rust,,ignore
/// pub struct TimeoutTransform {
/// timeout: Duration,
/// }
///
/// impl<S> Transform<S> for TimeoutTransform<E>
/// where
/// S: Service,
/// {
/// type Request = S::Request;
/// type Response = S::Response;
/// type Error = TimeoutError<S::Error>;
/// type InitError = S::Error;
/// type Transform = Timeout<S>;
/// type Future = Ready<Result<Self::Transform, Self::InitError>>;
///
/// fn new_transform(&self, service: S) -> Self::Future {
/// ok(TimeoutService {
/// service,
/// timeout: self.timeout,
/// })
/// }
/// }
/// ```
pub trait Transform<S> {
/// Requests handled by the service.
type Request;
@@ -41,13 +106,13 @@ pub trait Transform<S> {
Error = Self::Error,
>;
/// Errors produced while building a service.
/// Errors produced while building a transform service.
type InitError;
/// The future response value.
type Future: Future<Output = Result<Self::Transform, Self::InitError>>;
/// Creates and returns a new Service component, asynchronously
/// Creates and returns a new Transform component, asynchronously
fn new_transform(&self, service: S) -> Self::Future;
/// Map this transforms's factory error to a different error,

View File

@@ -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

View File

@@ -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,10 +17,10 @@ name = "actix_testing"
path = "src/lib.rs"
[dependencies]
actix-rt = "1.0.0-alpha.3"
actix-macros = "0.1.0-alpha.1"
actix-server = "1.0.0-alpha.3"
actix-service = "1.0.0-alpha.3"
actix-rt = "1.0.0"
actix-macros = "0.1.0"
actix-server = "1.0.0"
actix-service = "1.0.0"
log = "0.4"
net2 = "0.2"

View File

@@ -20,12 +20,12 @@ pub use actix_macros::test;
/// # Examples
///
/// ```rust
/// use actix_service::{service_fn};
/// use actix_service::fn_service;
/// use actix_testing::TestServer;
///
/// #[actix_rt::main]
/// async fn main() {
/// let srv = TestServer::with(|| service_fn(
/// let srv = TestServer::with(|| fn_service(
/// |sock| async move {
/// println!("New connection: {:?}", sock);
/// Ok::<_, ()>(())

View File

@@ -1,5 +1,11 @@
# Changes
## [0.3.1] - 2019-12-12
### Changed
* Use parking_lot 0.10
## [0.3.0] - 2019-12-02
### Changed

View File

@@ -1,6 +1,6 @@
[package]
name = "actix-threadpool"
version = "0.3.0"
version = "0.3.1"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix thread pool for sync code"
keywords = ["actix", "network", "framework", "async", "futures"]
@@ -19,9 +19,9 @@ path = "src/lib.rs"
[dependencies]
derive_more = "0.99.2"
futures = "0.3.1"
parking_lot = "0.9"
lazy_static = "1.2"
futures-channel = "0.3.1"
parking_lot = "0.10"
lazy_static = "1.3"
log = "0.4"
num_cpus = "1.10"
threadpool = "1.7"

View File

@@ -6,7 +6,7 @@ use std::pin::Pin;
use std::task::{Context, Poll};
use derive_more::Display;
use futures::channel::oneshot;
use futures_channel::oneshot;
use parking_lot::Mutex;
use threadpool::ThreadPool;
@@ -79,9 +79,12 @@ impl<I, E: fmt::Debug> Future for CpuFuture<I, E> {
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let rx = Pin::new(&mut self.rx);
let res = futures::ready!(rx.poll(cx))
.map_err(|_| BlockingError::Canceled)
.and_then(|res| res.map_err(BlockingError::Error));
let res = match rx.poll(cx) {
Poll::Pending => return Poll::Pending,
Poll::Ready(res) => res
.map_err(|_| BlockingError::Canceled)
.and_then(|res| res.map_err(BlockingError::Error)),
};
Poll::Ready(res)
}
}

View File

@@ -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

View File

@@ -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"]
@@ -32,10 +32,10 @@ rustls = ["rust-tls", "webpki", "webpki-roots", "tokio-rustls"]
nativetls = ["native-tls", "tokio-tls"]
[dependencies]
actix-service = "1.0.0-alpha.3"
actix-codec = "0.2.0-alpha.3"
actix-utils = "1.0.0-alpha.3"
actix-rt = "1.0.0-alpha.3"
actix-service = "1.0.0"
actix-codec = "0.2.0"
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" }

View File

@@ -3,7 +3,7 @@ use std::marker::PhantomData;
use std::pin::Pin;
use std::task::{Context, Poll};
pub use open_ssl::ssl::{SslAcceptor, SslAcceptorBuilder};
pub use open_ssl::ssl::{AlpnError, SslAcceptor, SslAcceptorBuilder};
pub use tokio_openssl::{HandshakeError, SslStream};
use actix_codec::{AsyncRead, AsyncWrite};
@@ -88,7 +88,7 @@ impl<T: AsyncRead + AsyncWrite + Unpin + 'static> Service for AcceptorService<T>
let acc = acc;
tokio_openssl::accept(&acc, req).await
}
.boxed_local(),
.boxed_local(),
}
}
}

27
actix-tracing/Cargo.toml Normal file
View File

@@ -0,0 +1,27 @@
[package]
name = "actix-tracing"
version = "0.1.0"
authors = ["Rajasekharan Vengalil <avranju@gmail.com>"]
description = "Support for tokio tracing with Actix services"
keywords = ["network", "framework", "tracing"]
homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-net.git"
documentation = "https://docs.rs/actix-tracing/"
categories = ["network-programming", "asynchronous"]
license = "MIT/Apache-2.0"
edition = "2018"
workspace = ".."
[lib]
name = "actix_tracing"
path = "src/lib.rs"
[dependencies]
actix-service = "1.0"
futures-util = "0.3"
tracing = "0.1"
tracing-futures = "0.2"
[dev_dependencies]
actix-rt = "1.0"
slab = "0.4"

261
actix-tracing/src/lib.rs Normal file
View File

@@ -0,0 +1,261 @@
//! Actix tracing - support for tokio tracing with Actix services.
#![deny(rust_2018_idioms, warnings)]
use std::marker::PhantomData;
use std::task::{Context, Poll};
use actix_service::{
apply, dev::ApplyTransform, IntoServiceFactory, Service, ServiceFactory, Transform,
};
use futures_util::future::{ok, Either, Ready};
use tracing_futures::{Instrument, Instrumented};
/// A `Service` implementation that automatically enters/exits tracing spans
/// for the wrapped inner service.
#[derive(Clone)]
pub struct TracingService<S, F> {
inner: S,
make_span: F,
}
impl<S, F> TracingService<S, F> {
pub fn new(inner: S, make_span: F) -> Self {
TracingService { inner, make_span }
}
}
impl<S, F> Service for TracingService<S, F>
where
S: Service,
F: Fn(&S::Request) -> Option<tracing::Span>,
{
type Request = S::Request;
type Response = S::Response;
type Error = S::Error;
type Future = Either<S::Future, Instrumented<S::Future>>;
fn poll_ready(&mut self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(ctx)
}
fn call(&mut self, req: Self::Request) -> Self::Future {
let span = (self.make_span)(&req);
let _enter = span.as_ref().map(|s| s.enter());
let fut = self.inner.call(req);
// make a child span to track the future's execution
if let Some(span) = span
.clone()
.map(|span| tracing::span!(parent: &span, tracing::Level::INFO, "future"))
{
Either::Right(fut.instrument(span))
} else {
Either::Left(fut)
}
}
}
/// A `Transform` implementation that wraps services with a [`TracingService`].
///
/// [`TracingService`]: struct.TracingService.html
pub struct TracingTransform<S, U, F> {
make_span: F,
_p: PhantomData<fn(S, U)>,
}
impl<S, U, F> TracingTransform<S, U, F> {
pub fn new(make_span: F) -> Self {
TracingTransform {
make_span,
_p: PhantomData,
}
}
}
impl<S, U, F> Transform<S> for TracingTransform<S, U, F>
where
S: Service,
U: ServiceFactory<
Request = S::Request,
Response = S::Response,
Error = S::Error,
Service = S,
>,
F: Fn(&S::Request) -> Option<tracing::Span> + Clone,
{
type Request = S::Request;
type Response = S::Response;
type Error = S::Error;
type Transform = TracingService<S, F>;
type InitError = U::InitError;
type Future = Ready<Result<Self::Transform, Self::InitError>>;
fn new_transform(&self, service: S) -> Self::Future {
ok(TracingService::new(service, self.make_span.clone()))
}
}
/// Wraps the provided service factory with a transform that automatically
/// enters/exits the given span.
///
/// The span to be entered/exited can be provided via a closure. The closure
/// is passed in a reference to the request being handled by the service.
///
/// For example:
/// ```rust,ignore
/// let traced_service = trace(
/// web_service,
/// |req: &Request| Some(span!(Level::INFO, "request", req.id))
/// );
/// ```
pub fn trace<S, U, F>(
service_factory: U,
make_span: F,
) -> ApplyTransform<TracingTransform<S::Service, S, F>, S>
where
S: ServiceFactory,
F: Fn(&S::Request) -> Option<tracing::Span> + Clone,
U: IntoServiceFactory<S>,
{
apply(
TracingTransform::new(make_span),
service_factory.into_factory(),
)
}
#[cfg(test)]
mod test {
use super::*;
use std::cell::RefCell;
use std::collections::{BTreeMap, BTreeSet};
use std::sync::{Arc, RwLock};
use actix_service::{fn_factory, fn_service};
use slab::Slab;
use tracing::{span, Event, Level, Metadata, Subscriber};
thread_local! {
static SPAN: RefCell<Vec<span::Id>> = RefCell::new(Vec::new());
}
#[derive(Default)]
struct Stats {
entered_spans: BTreeSet<u64>,
exited_spans: BTreeSet<u64>,
events_count: BTreeMap<u64, usize>,
}
#[derive(Default)]
struct Inner {
spans: Slab<&'static Metadata<'static>>,
stats: Stats,
}
#[derive(Clone, Default)]
struct TestSubscriber {
inner: Arc<RwLock<Inner>>,
}
impl Subscriber for TestSubscriber {
fn enabled(&self, _metadata: &Metadata<'_>) -> bool {
true
}
fn new_span(&self, span: &span::Attributes<'_>) -> span::Id {
let id = self.inner.write().unwrap().spans.insert(span.metadata());
span::Id::from_u64(id as u64 + 1)
}
fn record(&self, _span: &span::Id, _values: &span::Record<'_>) {}
fn record_follows_from(&self, _span: &span::Id, _follows: &span::Id) {}
fn event(&self, event: &Event<'_>) {
let id = event
.parent()
.cloned()
.or_else(|| SPAN.with(|current_span| current_span.borrow().last().cloned()))
.unwrap();
*self
.inner
.write()
.unwrap()
.stats
.events_count
.entry(id.into_u64())
.or_insert(0) += 1;
}
fn enter(&self, span: &span::Id) {
self.inner
.write()
.unwrap()
.stats
.entered_spans
.insert(span.into_u64());
SPAN.with(|current_span| {
current_span.borrow_mut().push(span.clone());
});
}
fn exit(&self, span: &span::Id) {
self.inner
.write()
.unwrap()
.stats
.exited_spans
.insert(span.into_u64());
// we are guaranteed that on any given thread, spans are exited in reverse order
SPAN.with(|current_span| {
let leaving = current_span
.borrow_mut()
.pop()
.expect("told to exit span when not in span");
assert_eq!(
&leaving, span,
"told to exit span that was not most recently entered"
);
});
}
}
#[actix_rt::test]
async fn service_call() {
let service_factory = fn_factory(|| {
ok::<_, ()>(fn_service(|req: &'static str| {
tracing::event!(Level::TRACE, "It's happening - {}!", req);
ok::<_, ()>(())
}))
});
let subscriber = TestSubscriber::default();
let _guard = tracing::subscriber::set_default(subscriber.clone());
let span_svc = span!(Level::TRACE, "span_svc");
let trace_service_factory = trace(service_factory, |_: &&str| Some(span_svc.clone()));
let mut service = trace_service_factory.new_service(()).await.unwrap();
service.call("boo").await.unwrap();
let id = span_svc.id().unwrap().into_u64();
assert!(subscriber
.inner
.read()
.unwrap()
.stats
.entered_spans
.contains(&id));
assert!(subscriber
.inner
.read()
.unwrap()
.stats
.exited_spans
.contains(&id));
assert_eq!(subscriber.inner.read().unwrap().stats.events_count[&id], 1);
}
}

View File

@@ -1,5 +1,37 @@
# Changes
## [1.0.6] - 2020-01-08
* Add `Clone` impl for `condition::Waiter`
## [1.0.5] - 2020-01-08
* Add `Condition` type.
* Add `Pool` of one-shot's.
## [1.0.4] - 2019-12-20
* Add methods to check `LocalWaker` registration state.
## [1.0.3] - 2019-12-11
* Revert InOrder service 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

View File

@@ -1,6 +1,6 @@
[package]
name = "actix-utils"
version = "1.0.0-alpha.3"
version = "1.0.6"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix utils - various actix net related services"
keywords = ["network", "framework", "async", "futures"]
@@ -9,20 +9,20 @@ 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 = ".."
[lib]
name = "actix_utils"
path = "src/lib.rs"
[dependencies]
actix-service = "1.0.0-alpha.3"
actix-rt = "1.0.0-alpha.3"
actix-codec = "0.2.0-alpha.3"
bytes = "0.5.2"
either = "1.5.2"
actix-service = "1.0.1"
actix-rt = "1.0.0"
actix-codec = "0.2.0"
bitflags = "1.2"
bytes = "0.5.3"
either = "1.5.3"
futures = "0.3.1"
pin-project = "0.4.6"
log = "0.4"
slab = "0.4"

View File

@@ -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()
}
}

View File

@@ -0,0 +1,127 @@
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use slab::Slab;
use crate::cell::Cell;
use crate::task::LocalWaker;
/// Condition allows to notify multiple receivers at the same time
pub struct Condition(Cell<Inner>);
struct Inner {
data: Slab<Option<LocalWaker>>,
}
impl Default for Condition {
fn default() -> Self {
Self::new()
}
}
impl Condition {
pub fn new() -> Condition {
Condition(Cell::new(Inner { data: Slab::new() }))
}
/// Get condition waiter
pub fn wait(&mut self) -> Waiter {
let token = self.0.get_mut().data.insert(None);
Waiter {
token,
inner: self.0.clone(),
}
}
/// Notify all waiters
pub fn notify(&self) {
let inner = self.0.get_ref();
for item in inner.data.iter() {
if let Some(waker) = item.1 {
waker.wake();
}
}
}
}
impl Drop for Condition {
fn drop(&mut self) {
self.notify()
}
}
#[must_use = "Waiter do nothing unless polled"]
pub struct Waiter {
token: usize,
inner: Cell<Inner>,
}
impl Clone for Waiter {
fn clone(&self) -> Self {
let token = unsafe { self.inner.get_mut_unsafe() }.data.insert(None);
Waiter {
token,
inner: self.inner.clone(),
}
}
}
impl Future for Waiter {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.get_mut();
let inner = unsafe { this.inner.get_mut().data.get_unchecked_mut(this.token) };
if inner.is_none() {
let waker = LocalWaker::default();
waker.register(cx.waker());
*inner = Some(waker);
Poll::Pending
} else if inner.as_mut().unwrap().register(cx.waker()) {
Poll::Pending
} else {
Poll::Ready(())
}
}
}
impl Drop for Waiter {
fn drop(&mut self) {
self.inner.get_mut().data.remove(self.token);
}
}
#[cfg(test)]
mod tests {
use super::*;
use futures::future::lazy;
#[actix_rt::test]
async fn test_condition() {
let mut cond = Condition::new();
let mut waiter = cond.wait();
assert_eq!(
lazy(|cx| Pin::new(&mut waiter).poll(cx)).await,
Poll::Pending
);
cond.notify();
assert_eq!(waiter.await, ());
let mut waiter = cond.wait();
assert_eq!(
lazy(|cx| Pin::new(&mut waiter).poll(cx)).await,
Poll::Pending
);
let mut waiter2 = waiter.clone();
assert_eq!(
lazy(|cx| Pin::new(&mut waiter2).poll(cx)).await,
Poll::Pending
);
drop(cond);
assert_eq!(waiter.await, ());
assert_eq!(waiter2.await, ());
}
}

View File

@@ -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
}

View File

@@ -115,7 +115,7 @@ mod tests {
use std::time::Duration;
use super::*;
use actix_service::{apply, factory_fn, Service, ServiceFactory};
use actix_service::{apply, fn_factory, Service, ServiceFactory};
use futures::future::{lazy, ok, FutureExt, LocalBoxFuture};
struct SleepService(Duration);
@@ -155,7 +155,7 @@ mod tests {
async fn test_newtransform() {
let wait_time = Duration::from_millis(50);
let srv = apply(InFlight::new(1), factory_fn(|| ok(SleepService(wait_time))));
let srv = apply(InFlight::new(1), fn_factory(|| ok(SleepService(wait_time))));
let mut srv = srv.new_service(&()).await.unwrap();
assert_eq!(lazy(|cx| srv.poll_ready(cx)).await, Poll::Ready(Ok(())));

View File

@@ -3,6 +3,7 @@
#![allow(clippy::type_complexity)]
mod cell;
pub mod condition;
pub mod counter;
pub mod either;
pub mod framed;

View File

@@ -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());
}
}

View File

@@ -1,69 +1,51 @@
//! 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 slab::Slab;
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)
}
/// Creates a new futures-aware, pool of one-shot's.
pub fn pool<T>() -> Pool<T> {
Pool(Cell::new(Slab::new()))
}
/// 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 +60,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,45 +76,14 @@ 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(_) => {}
};
self.inner.get_ref().rx_task.wake();
}
}
@@ -142,33 +93,219 @@ 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();
/// Futures-aware, pool of one-shot's.
pub struct Pool<T>(Cell<Slab<PoolInner<T>>>);
bitflags::bitflags! {
pub struct Flags: u8 {
const SENDER = 0b0000_0001;
const RECEIVER = 0b0000_0010;
}
}
#[derive(Debug)]
struct PoolInner<T> {
flags: Flags,
value: Option<T>,
waker: LocalWaker,
}
impl<T> Pool<T> {
pub fn channel(&mut self) -> (PSender<T>, PReceiver<T>) {
let token = self.0.get_mut().insert(PoolInner {
flags: Flags::all(),
value: None,
waker: LocalWaker::default(),
});
(
PSender {
token,
inner: self.0.clone(),
},
PReceiver {
token,
inner: self.0.clone(),
},
)
}
}
impl<T> Clone for Pool<T> {
fn clone(&self) -> Self {
Pool(self.0.clone())
}
}
/// Represents the completion half of a oneshot through which the result of a
/// computation is signaled.
#[derive(Debug)]
pub struct PSender<T> {
token: usize,
inner: Cell<Slab<PoolInner<T>>>,
}
/// A future representing the completion of a computation happening elsewhere in
/// memory.
#[derive(Debug)]
#[must_use = "futures do nothing unless polled"]
pub struct PReceiver<T> {
token: usize,
inner: Cell<Slab<PoolInner<T>>>,
}
// The oneshots do not ever project Pin to the inner T
impl<T> Unpin for PReceiver<T> {}
impl<T> Unpin for PSender<T> {}
impl<T> PSender<T> {
/// Completes this oneshot with a successful result.
///
/// This function will consume `self` and indicate to the other end, the
/// `Receiver`, that the error provided is the result of the computation this
/// represents.
///
/// If the value is successfully enqueued for the remote end to receive,
/// 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(mut self, val: T) -> Result<(), T> {
let inner = unsafe { self.inner.get_mut().get_unchecked_mut(self.token) };
if inner.flags.contains(Flags::RECEIVER) {
inner.value = Some(val);
inner.waker.wake();
Ok(())
} else {
Err(val)
}
}
/// Tests to see whether this `Sender`'s corresponding `Receiver`
/// has gone away.
pub fn is_canceled(&self) -> bool {
!unsafe { self.inner.get_ref().get_unchecked(self.token) }
.flags
.contains(Flags::RECEIVER)
}
}
impl<T> Drop for PSender<T> {
fn drop(&mut self) {
let inner = unsafe { self.inner.get_mut().get_unchecked_mut(self.token) };
if inner.flags.contains(Flags::RECEIVER) {
inner.waker.wake();
inner.flags.remove(Flags::SENDER);
} else {
self.inner.get_mut().remove(self.token);
}
}
}
impl<T> Drop for PReceiver<T> {
fn drop(&mut self) {
let inner = unsafe { self.inner.get_mut().get_unchecked_mut(self.token) };
if inner.flags.contains(Flags::SENDER) {
inner.flags.remove(Flags::RECEIVER);
} else {
self.inner.get_mut().remove(self.token);
}
}
}
impl<T> Future for PReceiver<T> {
type Output = Result<T, Canceled>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.get_mut();
let inner = unsafe { this.inner.get_mut().get_unchecked_mut(this.token) };
// If we've got a value, then skip the logic below as we're done.
if let Some(val) = inner.value.take() {
return Poll::Ready(Ok(val));
}
// Check if sender is dropped and return error if it is.
if !inner.flags.contains(Flags::SENDER) {
Poll::Ready(Err(Canceled))
} else {
inner.waker.register(cx.waker());
Poll::Pending
}
}
}
#[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());
}
#[actix_rt::test]
async fn test_pool() {
let (tx, rx) = pool().channel();
tx.send("test").unwrap();
assert_eq!(rx.await.unwrap(), "test");
let (tx, rx) = pool().channel();
assert!(!tx.is_canceled());
drop(rx);
assert!(tx.is_canceled());
assert!(tx.send("test").is_err());
let (tx, rx) = pool::<&'static str>().channel();
drop(tx);
assert!(rx.await.is_err());
let (tx, mut rx) = pool::<&'static str>().channel();
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) = pool::<&'static str>().channel();
assert_eq!(lazy(|cx| Pin::new(&mut rx).poll(cx)).await, Poll::Pending);
drop(tx);
assert!(rx.await.is_err());
}
}

View File

@@ -105,7 +105,7 @@ where
pub struct InOrderService<S: Service> {
service: S,
task: Rc<LocalWaker>,
waker: Rc<LocalWaker>,
acks: VecDeque<Record<S::Response, S::Error>>,
}
@@ -123,7 +123,7 @@ where
Self {
service: service.into_service(),
acks: VecDeque::new(),
task: Rc::new(LocalWaker::new()),
waker: Rc::new(LocalWaker::new()),
}
}
}
@@ -142,7 +142,7 @@ where
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());
self.waker.register(cx.waker());
// check acks
while !self.acks.is_empty() {
@@ -172,11 +172,11 @@ where
let (tx2, rx2) = oneshot::channel();
self.acks.push_back(Record { rx: rx1, tx: tx2 });
let task = self.task.clone();
let waker = self.waker.clone();
let fut = self.service.call(request);
actix_rt::spawn(async move {
let res = fut.await;
task.wake();
waker.wake();
let _ = tx1.send(res);
});
@@ -211,7 +211,7 @@ mod tests {
use super::*;
use actix_service::Service;
use futures::channel::oneshot;
use futures::future::{lazy, FutureExt, LocalBoxFuture};
use futures::future::{lazy, poll_fn, FutureExt, LocalBoxFuture};
struct Srv;
@@ -245,15 +245,18 @@ mod tests {
let _ = actix_rt::System::new("test").block_on(async {
let mut srv = InOrderService::new(Srv);
let _ = lazy(|cx| srv.poll_ready(cx)).await;
let res1 = srv.call(rx1);
let res2 = srv.call(rx2);
let res3 = srv.call(rx3);
let _ = lazy(|cx| srv.poll_ready(cx)).await;
// dispatcher do this
actix_rt::time::delay_for(Duration::from_millis(100)).await;
let _ = lazy(|cx| srv.poll_ready(cx)).await;
actix_rt::spawn(async move {
let _ = poll_fn(|cx| {
let _ = srv.poll_ready(cx);
Poll::<()>::Pending
})
.await;
});
assert_eq!(res1.await.unwrap(), 1);
assert_eq!(res2.await.unwrap(), 2);

View File

@@ -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,
};
}
}
}

View File

@@ -34,11 +34,22 @@ impl LocalWaker {
}
}
#[inline]
/// Check if waker has been registered.
pub fn is_registed(&self) -> bool {
unsafe { (*self.waker.get()).is_some() }
}
#[inline]
/// Registers the waker to be notified on calls to `wake`.
pub fn register(&self, waker: &Waker) {
///
/// Returns `true` if waker was registered before.
pub fn register(&self, waker: &Waker) -> bool {
unsafe {
*self.waker.get() = Some(waker.clone());
let w = self.waker.get();
let is_registered = (*w).is_some();
*w = Some(waker.clone());
is_registered
}
}

View File

@@ -182,7 +182,7 @@ mod tests {
use std::time::Duration;
use super::*;
use actix_service::{apply, factory_fn, Service, ServiceFactory};
use actix_service::{apply, fn_factory, Service, ServiceFactory};
use futures::future::{ok, FutureExt, LocalBoxFuture};
struct SleepService(Duration);
@@ -229,7 +229,7 @@ mod tests {
let timeout = apply(
Timeout::new(resolution),
factory_fn(|| ok::<_, ()>(SleepService(wait_time))),
fn_factory(|| ok::<_, ()>(SleepService(wait_time))),
);
let mut srv = timeout.new_service(&()).await.unwrap();

View File

@@ -1,5 +1,23 @@
# Changes
## [0.2.4] - 2019-12-31
* Add `ResourceDef::resource_path_named()` path generation method
## [0.2.3] - 2019-12-25
* Add impl `IntoPattern` for `&String`
## [0.2.2] - 2019-12-25
* Use `IntoPattern` for `RouterBuilder::path()`
## [0.2.1] - 2019-12-25
* Add `IntoPattern` trait
* Add multi-pattern resources
## [0.2.0] - 2019-12-07
* Update http to 0.2

View File

@@ -1,6 +1,6 @@
[package]
name = "actix-router"
version = "0.2.0"
version = "0.2.4"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Path router"
keywords = ["actix"]
@@ -8,9 +8,7 @@ homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-net.git"
documentation = "https://docs.rs/actix-router/"
license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
edition = "2018"
workspace = ".."
[lib]
name = "actix_router"
@@ -21,8 +19,8 @@ default = ["http"]
[dependencies]
regex = "1.3.1"
serde = "1.0.80"
bytestring = "0.1.0"
serde = "1.0.104"
bytestring = "0.1.2"
log = "0.4.8"
http = { version="0.2.0", optional=true }

View File

@@ -492,7 +492,7 @@ mod tests {
#[derive(Deserialize)]
struct Id {
id: String,
_id: String,
}
#[derive(Debug, Deserialize)]

View File

@@ -35,6 +35,100 @@ impl ResourcePath for bytestring::ByteString {
}
}
/// Helper trait for type that could be converted to path pattern
pub trait IntoPattern {
/// Signle patter
fn is_single(&self) -> bool;
fn patterns(&self) -> Vec<String>;
}
impl IntoPattern for String {
fn is_single(&self) -> bool {
true
}
fn patterns(&self) -> Vec<String> {
vec![self.clone()]
}
}
impl<'a> IntoPattern for &'a String {
fn is_single(&self) -> bool {
true
}
fn patterns(&self) -> Vec<String> {
vec![self.as_str().to_string()]
}
}
impl<'a> IntoPattern for &'a str {
fn is_single(&self) -> bool {
true
}
fn patterns(&self) -> Vec<String> {
vec![self.to_string()]
}
}
impl<T: AsRef<str>> IntoPattern for Vec<T> {
fn is_single(&self) -> bool {
self.len() == 1
}
fn patterns(&self) -> Vec<String> {
self.into_iter().map(|v| v.as_ref().to_string()).collect()
}
}
macro_rules! array_patterns (($tp:ty, $num:tt) => {
impl IntoPattern for [$tp; $num] {
fn is_single(&self) -> bool {
$num == 1
}
fn patterns(&self) -> Vec<String> {
self.iter().map(|v| v.to_string()).collect()
}
}
});
array_patterns!(&str, 1);
array_patterns!(&str, 2);
array_patterns!(&str, 3);
array_patterns!(&str, 4);
array_patterns!(&str, 5);
array_patterns!(&str, 6);
array_patterns!(&str, 7);
array_patterns!(&str, 8);
array_patterns!(&str, 9);
array_patterns!(&str, 10);
array_patterns!(&str, 11);
array_patterns!(&str, 12);
array_patterns!(&str, 13);
array_patterns!(&str, 14);
array_patterns!(&str, 15);
array_patterns!(&str, 16);
array_patterns!(String, 1);
array_patterns!(String, 2);
array_patterns!(String, 3);
array_patterns!(String, 4);
array_patterns!(String, 5);
array_patterns!(String, 6);
array_patterns!(String, 7);
array_patterns!(String, 8);
array_patterns!(String, 9);
array_patterns!(String, 10);
array_patterns!(String, 11);
array_patterns!(String, 12);
array_patterns!(String, 13);
array_patterns!(String, 14);
array_patterns!(String, 15);
array_patterns!(String, 16);
#[cfg(feature = "http")]
mod url;

View File

@@ -1,5 +1,4 @@
use std::ops::Index;
use std::rc::Rc;
use serde::de;
@@ -19,7 +18,7 @@ pub(crate) enum PathItem {
pub struct Path<T> {
path: T,
pub(crate) skip: u16,
pub(crate) segments: Vec<(Rc<String>, PathItem)>,
pub(crate) segments: Vec<(&'static str, PathItem)>,
}
impl<T: Default> Default for Path<T> {
@@ -96,7 +95,7 @@ impl<T: ResourcePath> Path<T> {
self.skip += n;
}
pub(crate) fn add(&mut self, name: Rc<String>, value: PathItem) {
pub(crate) fn add(&mut self, name: &'static str, value: PathItem) {
match value {
PathItem::Static(s) => self.segments.push((name, PathItem::Static(s))),
PathItem::Segment(begin, end) => self
@@ -106,9 +105,8 @@ impl<T: ResourcePath> Path<T> {
}
#[doc(hidden)]
pub fn add_static(&mut self, name: &str, value: &'static str) {
self.segments
.push((Rc::new(name.to_string()), PathItem::Static(value)));
pub fn add_static(&mut self, name: &'static str, value: &'static str) {
self.segments.push((name, PathItem::Static(value)));
}
#[inline]
@@ -126,7 +124,7 @@ impl<T: ResourcePath> Path<T> {
/// Get matched parameter by name without type conversion
pub fn get(&self, key: &str) -> Option<&str> {
for item in self.segments.iter() {
if key == item.0.as_str() {
if key == item.0 {
return match item.1 {
PathItem::Static(ref s) => Some(&s),
PathItem::Segment(s, e) => {

View File

@@ -1,11 +1,11 @@
use std::cmp::min;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::rc::Rc;
use regex::{escape, Regex};
use regex::{escape, Regex, RegexSet};
use crate::path::{Path, PathItem};
use crate::{Resource, ResourcePath};
use crate::{IntoPattern, Resource, ResourcePath};
const MAX_DYNAMIC_SEGMENTS: usize = 16;
@@ -31,22 +31,56 @@ enum PatternElement {
enum PatternType {
Static(String),
Prefix(String),
Dynamic(Regex, Vec<Rc<String>>, usize),
Dynamic(Regex, Vec<&'static str>, usize),
DynamicSet(RegexSet, Vec<(Regex, Vec<&'static str>, usize)>),
}
impl ResourceDef {
/// Parse path pattern and create new `Pattern` instance.
///
/// Panics if path pattern is wrong.
pub fn new(path: &str) -> Self {
ResourceDef::with_prefix(path, false)
/// Panics if path pattern is malformed.
pub fn new<T: IntoPattern>(path: T) -> Self {
if path.is_single() {
let patterns = path.patterns();
ResourceDef::with_prefix(&patterns[0], false)
} else {
let set = path.patterns();
let mut data = Vec::new();
let mut re_set = Vec::new();
for path in set {
let (pattern, _, _, len) = ResourceDef::parse(&path, false);
let re = match Regex::new(&pattern) {
Ok(re) => re,
Err(err) => panic!("Wrong path pattern: \"{}\" {}", path, err),
};
// actix creates one router per thread
let names: Vec<_> = re
.capture_names()
.filter_map(|name| {
name.map(|name| Box::leak(Box::new(name.to_owned())).as_str())
})
.collect();
data.push((re, names, len));
re_set.push(pattern);
}
ResourceDef {
id: 0,
tp: PatternType::DynamicSet(RegexSet::new(re_set).unwrap(), data),
elements: Vec::new(),
name: String::new(),
pattern: "".to_owned(),
}
}
}
/// Parse path pattern and create new `Pattern` instance.
///
/// Use `prefix` type instead of `static`.
///
/// Panics if path regex pattern is wrong.
/// Panics if path regex pattern is malformed.
pub fn prefix(path: &str) -> Self {
ResourceDef::with_prefix(path, true)
}
@@ -57,7 +91,7 @@ impl ResourceDef {
///
/// Use `prefix` type instead of `static`.
///
/// Panics if path regex pattern is wrong.
/// Panics if path regex pattern is malformed.
pub fn root_prefix(path: &str) -> Self {
ResourceDef::with_prefix(&insert_slash(path), true)
}
@@ -85,7 +119,9 @@ impl ResourceDef {
// actix creates one router per thread
let names = re
.capture_names()
.filter_map(|name| name.map(|name| Rc::new(name.to_owned())))
.filter_map(|name| {
name.map(|name| Box::leak(Box::new(name.to_owned())).as_str())
})
.collect();
PatternType::Dynamic(re, names, len)
} else if for_prefix {
@@ -123,8 +159,9 @@ impl ResourceDef {
pub fn is_match(&self, path: &str) -> bool {
match self.tp {
PatternType::Static(ref s) => s == path,
PatternType::Dynamic(ref re, _, _) => re.is_match(path),
PatternType::Prefix(ref s) => path.starts_with(s),
PatternType::Dynamic(ref re, _, _) => re.is_match(path),
PatternType::DynamicSet(ref re, _) => re.is_match(path),
}
}
@@ -176,6 +213,30 @@ impl ResourceDef {
};
Some(min(plen, len))
}
PatternType::DynamicSet(ref re, ref params) => {
if let Some(idx) = re.matches(path).into_iter().next() {
let (ref pattern, _, len) = params[idx];
if let Some(captures) = pattern.captures(path) {
let mut pos = 0;
let mut passed = false;
for capture in captures.iter() {
if let Some(ref m) = capture {
if !passed {
passed = true;
continue;
}
pos = m.end();
}
}
Some(pos + len)
} else {
None
}
} else {
None
}
}
}
}
@@ -190,6 +251,25 @@ impl ResourceDef {
false
}
}
PatternType::Prefix(ref s) => {
let rpath = path.path();
let len = if s == rpath {
s.len()
} else if rpath.starts_with(s)
&& (s.ends_with('/') || rpath.split_at(s.len()).1.starts_with('/'))
{
if s.ends_with('/') {
s.len() - 1
} else {
s.len()
}
} else {
return false;
};
let rpath_len = rpath.len();
path.skip(min(rpath_len, len) as u16);
true
}
PatternType::Dynamic(ref re, ref names, len) => {
let mut idx = 0;
let mut pos = 0;
@@ -219,24 +299,40 @@ impl ResourceDef {
path.skip((pos + len) as u16);
true
}
PatternType::Prefix(ref s) => {
let rpath = path.path();
let len = if s == rpath {
s.len()
} else if rpath.starts_with(s)
&& (s.ends_with('/') || rpath.split_at(s.len()).1.starts_with('/'))
{
if s.ends_with('/') {
s.len() - 1
PatternType::DynamicSet(ref re, ref params) => {
if let Some(idx) = re.matches(path.path()).into_iter().next() {
let (ref pattern, ref names, len) = params[idx];
let mut idx = 0;
let mut pos = 0;
let mut segments: [PathItem; MAX_DYNAMIC_SEGMENTS] =
[PathItem::Static(""); MAX_DYNAMIC_SEGMENTS];
if let Some(captures) = pattern.captures(path.path()) {
for (no, name) in names.iter().enumerate() {
if let Some(m) = captures.name(&name) {
idx += 1;
pos = m.end();
segments[no] =
PathItem::Segment(m.start() as u16, m.end() as u16);
} else {
log::error!(
"Dynamic path match but not all segments found: {}",
name
);
return false;
}
}
} else {
s.len()
return false;
}
for idx in 0..idx {
path.add(names[idx].clone(), segments[idx]);
}
path.skip((pos + len) as u16);
true
} else {
return false;
};
let rpath_len = rpath.len();
path.skip(min(rpath_len, len) as u16);
true
false
}
}
}
}
@@ -263,6 +359,30 @@ impl ResourceDef {
false
}
}
PatternType::Prefix(ref s) => {
let len = {
let rpath = res.resource_path().path();
if s == rpath {
s.len()
} else if rpath.starts_with(s)
&& (s.ends_with('/') || rpath.split_at(s.len()).1.starts_with('/'))
{
if s.ends_with('/') {
s.len() - 1
} else {
s.len()
}
} else {
return false;
}
};
if !check(res, user_data) {
return false;
}
let path = res.resource_path();
path.skip(min(path.path().len(), len) as u16);
true
}
PatternType::Dynamic(ref re, ref names, len) => {
let mut idx = 0;
let mut pos = 0;
@@ -298,29 +418,47 @@ impl ResourceDef {
path.skip((pos + len) as u16);
true
}
PatternType::Prefix(ref s) => {
let len = {
let rpath = res.resource_path().path();
if s == rpath {
s.len()
} else if rpath.starts_with(s)
&& (s.ends_with('/') || rpath.split_at(s.len()).1.starts_with('/'))
{
if s.ends_with('/') {
s.len() - 1
} else {
s.len()
PatternType::DynamicSet(ref re, ref params) => {
let path = res.resource_path().path();
if let Some(idx) = re.matches(path).into_iter().next() {
let (ref pattern, ref names, len) = params[idx];
let mut idx = 0;
let mut pos = 0;
let mut segments: [PathItem; MAX_DYNAMIC_SEGMENTS] =
[PathItem::Static(""); MAX_DYNAMIC_SEGMENTS];
if let Some(captures) = pattern.captures(path) {
for (no, name) in names.iter().enumerate() {
if let Some(m) = captures.name(&name) {
idx += 1;
pos = m.end();
segments[no] =
PathItem::Segment(m.start() as u16, m.end() as u16);
} else {
log::error!(
"Dynamic path match but not all segments found: {}",
name
);
return false;
}
}
} else {
return false;
}
};
if !check(res, user_data) {
return false;
if !check(res, user_data) {
return false;
}
let path = res.resource_path();
for idx in 0..idx {
path.add(names[idx].clone(), segments[idx]);
}
path.skip((pos + len) as u16);
true
} else {
false
}
let path = res.resource_path();
path.skip(min(path.path().len(), len) as u16);
true
}
}
}
@@ -348,7 +486,45 @@ impl ResourceDef {
}
}
}
};
PatternType::DynamicSet(..) => {
return false;
}
}
true
}
/// Build resource path from elements. Returns `true` on success.
pub fn resource_path_named<K, V, S>(
&self,
path: &mut String,
elements: &HashMap<K, V, S>,
) -> bool
where
K: std::borrow::Borrow<str> + Eq + Hash,
V: AsRef<str>,
S: std::hash::BuildHasher,
{
match self.tp {
PatternType::Prefix(ref p) => path.push_str(p),
PatternType::Static(ref p) => path.push_str(p),
PatternType::Dynamic(..) => {
for el in &self.elements {
match *el {
PatternElement::Str(ref s) => path.push_str(s),
PatternElement::Var(ref name) => {
if let Some(val) = elements.get(name) {
path.push_str(val.as_ref())
} else {
return false;
}
}
}
}
}
PatternType::DynamicSet(..) => {
return false;
}
}
true
}
@@ -476,7 +652,7 @@ impl<'a> From<&'a str> for ResourceDef {
impl From<String> for ResourceDef {
fn from(path: String) -> ResourceDef {
ResourceDef::new(&path)
ResourceDef::new(path)
}
}
@@ -558,6 +734,65 @@ mod tests {
assert_eq!(path.get("id").unwrap(), "012345");
}
#[test]
fn test_dynamic_set() {
let re = ResourceDef::new(vec![
"/user/{id}",
"/v{version}/resource/{id}",
"/{id:[[:digit:]]{6}}",
]);
assert!(re.is_match("/user/profile"));
assert!(re.is_match("/user/2345"));
assert!(!re.is_match("/user/2345/"));
assert!(!re.is_match("/user/2345/sdg"));
let mut path = Path::new("/user/profile");
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "profile");
let mut path = Path::new("/user/1245125");
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "1245125");
assert!(re.is_match("/v1/resource/320120"));
assert!(!re.is_match("/v/resource/1"));
assert!(!re.is_match("/resource"));
let mut path = Path::new("/v151/resource/adahg32");
assert!(re.match_path(&mut path));
assert_eq!(path.get("version").unwrap(), "151");
assert_eq!(path.get("id").unwrap(), "adahg32");
assert!(re.is_match("/012345"));
assert!(!re.is_match("/012"));
assert!(!re.is_match("/01234567"));
assert!(!re.is_match("/XXXXXX"));
let mut path = Path::new("/012345");
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "012345");
let re = ResourceDef::new([
"/user/{id}",
"/v{version}/resource/{id}",
"/{id:[[:digit:]]{6}}",
]);
assert!(re.is_match("/user/profile"));
assert!(re.is_match("/user/2345"));
assert!(!re.is_match("/user/2345/"));
assert!(!re.is_match("/user/2345/sdg"));
let re = ResourceDef::new([
"/user/{id}".to_string(),
"/v{version}/resource/{id}".to_string(),
"/{id:[[:digit:]]{6}}".to_string(),
]);
assert!(re.is_match("/user/profile"));
assert!(re.is_match("/user/2345"));
assert!(!re.is_match("/user/2345/"));
assert!(!re.is_match("/user/2345/sdg"));
}
#[test]
fn test_parse_tail() {
let re = ResourceDef::new("/user/-{id}*");
@@ -659,4 +894,50 @@ mod tests {
assert_eq!(&path["name"], "test2");
assert_eq!(&path[0], "test2");
}
#[test]
fn test_resource_path() {
let mut s = String::new();
let resource = ResourceDef::new("/user/{item1}/test");
assert!(resource.resource_path(&mut s, &mut (&["user1"]).into_iter()));
assert_eq!(s, "/user/user1/test");
let mut s = String::new();
let resource = ResourceDef::new("/user/{item1}/{item2}/test");
assert!(resource.resource_path(&mut s, &mut (&["item", "item2"]).into_iter()));
assert_eq!(s, "/user/item/item2/test");
let mut s = String::new();
let resource = ResourceDef::new("/user/{item1}/{item2}");
assert!(resource.resource_path(&mut s, &mut (&["item", "item2"]).into_iter()));
assert_eq!(s, "/user/item/item2");
let mut s = String::new();
let resource = ResourceDef::new("/user/{item1}/{item2}/");
assert!(resource.resource_path(&mut s, &mut (&["item", "item2"]).into_iter()));
assert_eq!(s, "/user/item/item2/");
let mut s = String::new();
assert!(!resource.resource_path(&mut s, &mut (&["item"]).into_iter()));
let mut s = String::new();
assert!(resource.resource_path(&mut s, &mut (&["item", "item2"]).into_iter()));
assert_eq!(s, "/user/item/item2/");
assert!(!resource.resource_path(&mut s, &mut (&["item"]).into_iter()));
let mut s = String::new();
assert!(resource.resource_path(&mut s, &mut vec!["item", "item2"].into_iter()));
assert_eq!(s, "/user/item/item2/");
let mut map = HashMap::new();
map.insert("item1", "item");
let mut s = String::new();
assert!(!resource.resource_path_named(&mut s, &map));
let mut s = String::new();
map.insert("item2", "item2");
assert!(resource.resource_path_named(&mut s, &map));
assert_eq!(s, "/user/item/item2/");
}
}

View File

@@ -1,4 +1,4 @@
use crate::{Resource, ResourceDef, ResourcePath};
use crate::{IntoPattern, Resource, ResourceDef, ResourcePath};
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct ResourceId(pub u16);
@@ -70,7 +70,11 @@ pub struct RouterBuilder<T, U = ()> {
impl<T, U> RouterBuilder<T, U> {
/// Register resource for specified path.
pub fn path(&mut self, path: &str, resource: T) -> &mut (ResourceDef, T, Option<U>) {
pub fn path<P: IntoPattern>(
&mut self,
path: P,
resource: T,
) -> &mut (ResourceDef, T, Option<U>) {
self.resources
.push((ResourceDef::new(path), resource, None));
self.resources.last_mut().unwrap()

View File

@@ -1,5 +1,23 @@
# Changes
[0.1.0] - 2019-12-07
## [0.1.4] - 2020-01-14
* Fix `AsRef<str>` impl
## [0.1.3] - 2020-01-13
* Add `PartialEq<T: AsRef<str>>`, `AsRef<[u8]>` impls
## [0.1.2] - 2019-12-22
* Fix `new()` method
* Make `ByteString::from_static()` and `ByteString::from_bytes_unchecked()` methods const.
## [0.1.1] - 2019-12-07
* Fix hash impl
## [0.1.0] - 2019-12-07
* Initial release

View File

@@ -1,6 +1,6 @@
[package]
name = "bytestring"
version = "0.1.0"
version = "0.1.4"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "A UTF-8 encoded string with Bytes as a storage"
keywords = ["actix"]
@@ -9,11 +9,10 @@ repository = "https://github.com/actix/actix-net.git"
documentation = "https://docs.rs/bytestring/"
license = "MIT/Apache-2.0"
edition = "2018"
workspace = ".."
[lib]
name = "bytestring"
path = "src/lib.rs"
[dependencies]
bytes = "0.5.2"
bytes = "0.5.3"

View File

@@ -6,14 +6,14 @@ use bytes::Bytes;
/// A utf-8 encoded string with [`Bytes`] as a storage.
///
/// [`Bytes`]: https://docs.rs/bytes/0.5.2/bytes/struct.Bytes.html
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Default)]
/// [`Bytes`]: https://docs.rs/bytes/0.5.3/bytes/struct.Bytes.html
#[derive(Clone, Eq, Ord, PartialOrd, Default)]
pub struct ByteString(Bytes);
impl ByteString {
/// Creates a new `ByteString`.
pub fn new() -> String {
String::default()
pub fn new() -> Self {
ByteString(Bytes::new())
}
/// Get a reference to the underlying bytes object.
@@ -27,12 +27,12 @@ impl ByteString {
}
/// Creates a new `ByteString` from a static str.
pub fn from_static(src: &'static str) -> ByteString {
Self(Bytes::from_static(src.as_ref()))
pub const fn from_static(src: &'static str) -> ByteString {
Self(Bytes::from_static(src.as_bytes()))
}
/// Creates a new `ByteString` from a Bytes.
pub unsafe fn from_bytes_unchecked(src: Bytes) -> ByteString {
pub const unsafe fn from_bytes_unchecked(src: Bytes) -> ByteString {
Self(src)
}
}
@@ -43,9 +43,27 @@ impl PartialEq<str> for ByteString {
}
}
impl<T: AsRef<str>> PartialEq<T> for ByteString {
fn eq(&self, other: &T) -> bool {
&self[..] == other.as_ref()
}
}
impl AsRef<[u8]> for ByteString {
fn as_ref(&self) -> &[u8] {
self.0.as_ref()
}
}
impl AsRef<str> for ByteString {
fn as_ref(&self) -> &str {
&*self
}
}
impl hash::Hash for ByteString {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.0.hash(state);
(**self).hash(state);
}
}
@@ -144,11 +162,39 @@ impl fmt::Display for ByteString {
#[cfg(test)]
mod test {
use super::*;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
#[test]
fn test_partial_eq() {
let s: ByteString = ByteString::from_static("test");
assert_eq!(s, "test");
assert_eq!(s, *"test");
assert_eq!(s, "test".to_string());
}
#[test]
fn test_new() {
let _: ByteString = ByteString::new();
}
#[test]
fn test_hash() {
let mut hasher1 = DefaultHasher::default();
"str".hash(&mut hasher1);
let mut hasher2 = DefaultHasher::default();
let s = ByteString::from_static("str");
s.hash(&mut hasher2);
assert_eq!(hasher1.finish(), hasher2.finish());
}
#[test]
fn test_from_string() {
let s: ByteString = "hello".to_string().into();
assert_eq!(&s, "hello");
let t: &str = s.as_ref();
assert_eq!(t, "hello");
}
#[test]
@@ -158,6 +204,7 @@ mod test {
#[test]
fn test_from_static_str() {
const _S: ByteString = ByteString::from_static("hello");
let _ = ByteString::from_static("str");
}