mirror of
https://github.com/fafhrd91/actix-net
synced 2025-08-15 06:45:56 +02:00
Compare commits
26 Commits
utils-v1.0
...
service-v1
Author | SHA1 | Date | |
---|---|---|---|
|
7c5fa25b23 | ||
|
3551d6674d | ||
|
9f00daea80 | ||
|
7dddeab2a8 | ||
|
dcbcc40da2 | ||
|
b0d44198ba | ||
|
974bd6b01e | ||
|
5779da0f49 | ||
|
1918c8d4f8 | ||
|
e21c58930b | ||
|
59c5e9be6a | ||
|
a2a9d9764d | ||
|
bf0a9d2f6e | ||
|
119027f822 | ||
|
0fe8038d23 | ||
|
b599bc4a0c | ||
|
a80e1f8370 | ||
|
5fe759cc02 | ||
|
05549f0b42 | ||
|
b1430eaded | ||
|
0d3f9e74c5 | ||
|
cab73791ed | ||
|
a7ac1a76ed | ||
|
37bedff6fb | ||
|
33fd6adc11 | ||
|
4305cdba2c |
20
.github/workflows/main.yml
vendored
20
.github/workflows/main.yml
vendored
@@ -2,6 +2,9 @@ name: CI
|
|||||||
|
|
||||||
on: [push, pull_request]
|
on: [push, pull_request]
|
||||||
|
|
||||||
|
env:
|
||||||
|
VCPKGRS_DYNAMIC: 1
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build_and_test:
|
build_and_test:
|
||||||
strategy:
|
strategy:
|
||||||
@@ -18,10 +21,12 @@ jobs:
|
|||||||
include:
|
include:
|
||||||
- toolchain: x86_64-pc-windows-msvc
|
- toolchain: x86_64-pc-windows-msvc
|
||||||
os: windows-latest
|
os: windows-latest
|
||||||
|
arch: x64
|
||||||
- toolchain: x86_64-pc-windows-gnu
|
- toolchain: x86_64-pc-windows-gnu
|
||||||
os: windows-latest
|
os: windows-latest
|
||||||
- toolchain: i686-pc-windows-msvc
|
- toolchain: i686-pc-windows-msvc
|
||||||
os: windows-latest
|
os: windows-latest
|
||||||
|
arch: x86
|
||||||
- toolchain: x86_64-apple-darwin
|
- toolchain: x86_64-apple-darwin
|
||||||
os: macOS-latest
|
os: macOS-latest
|
||||||
|
|
||||||
@@ -37,6 +42,13 @@ jobs:
|
|||||||
toolchain: ${{ matrix.version }}-${{ matrix.toolchain }}
|
toolchain: ${{ matrix.version }}-${{ matrix.toolchain }}
|
||||||
default: true
|
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
|
- name: check nightly
|
||||||
if: matrix.version == 'nightly'
|
if: matrix.version == 'nightly'
|
||||||
uses: actions-rs/cargo@v1
|
uses: actions-rs/cargo@v1
|
||||||
@@ -52,6 +64,14 @@ jobs:
|
|||||||
args: --all --bins --examples --tests
|
args: --all --bins --examples --tests
|
||||||
|
|
||||||
- name: 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
|
uses: actions-rs/cargo@v1
|
||||||
with:
|
with:
|
||||||
command: test
|
command: test
|
||||||
|
@@ -1,5 +1,7 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
* Use `.advance()` intead of `.split_to()`
|
||||||
|
|
||||||
## [0.2.0] - 2019-12-10
|
## [0.2.0] - 2019-12-10
|
||||||
|
|
||||||
* Use specific futures dependencies
|
* Use specific futures dependencies
|
||||||
|
@@ -2,7 +2,7 @@ use std::pin::Pin;
|
|||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
use std::{fmt, io};
|
use std::{fmt, io};
|
||||||
|
|
||||||
use bytes::BytesMut;
|
use bytes::{Buf, BytesMut};
|
||||||
use futures_core::{ready, Stream};
|
use futures_core::{ready, Stream};
|
||||||
use futures_sink::Sink;
|
use futures_sink::Sink;
|
||||||
|
|
||||||
@@ -288,7 +288,7 @@ impl<T, U> Framed<T, U> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// remove written data
|
// remove written data
|
||||||
let _ = self.write_buf.split_to(n);
|
self.write_buf.advance(n);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Try flushing the underlying IO
|
// Try flushing the underlying IO
|
||||||
|
@@ -1,5 +1,9 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [1.0.1] - 2019-12-15
|
||||||
|
|
||||||
|
* Fix trust-dns-resolver compilation
|
||||||
|
|
||||||
## [1.0.0] - 2019-12-11
|
## [1.0.0] - 2019-12-11
|
||||||
|
|
||||||
* Release
|
* Release
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-connect"
|
name = "actix-connect"
|
||||||
version = "1.0.0"
|
version = "1.0.1"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix connect - tcp connector service"
|
description = "Actix connect - tcp connector service"
|
||||||
keywords = ["network", "framework", "async", "futures"]
|
keywords = ["network", "framework", "async", "futures"]
|
||||||
@@ -34,14 +34,15 @@ uri = ["http"]
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
actix-service = "1.0.0"
|
actix-service = "1.0.0"
|
||||||
actix-codec = "0.2.0"
|
actix-codec = "0.2.0"
|
||||||
actix-utils = "1.0.0"
|
actix-utils = "1.0.3"
|
||||||
actix-rt = "1.0.0"
|
actix-rt = "1.0.0"
|
||||||
derive_more = "0.99.2"
|
derive_more = "0.99.2"
|
||||||
either = "1.5.2"
|
either = "1.5.2"
|
||||||
futures = "0.3.1"
|
futures = "0.3.1"
|
||||||
http = { version = "0.2.0", optional = true }
|
http = { version = "0.2.0", optional = true }
|
||||||
log = "0.4"
|
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
|
# openssl
|
||||||
open-ssl = { version="0.10", package = "openssl", optional = true }
|
open-ssl = { version="0.10", package = "openssl", optional = true }
|
||||||
@@ -53,5 +54,5 @@ tokio-rustls = { version = "0.12.0", optional = true }
|
|||||||
webpki = { version = "0.21", optional = true }
|
webpki = { version = "0.21", optional = true }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
bytes = "0.5.2"
|
bytes = "0.5.3"
|
||||||
actix-testing = { version="1.0.0" }
|
actix-testing = { version="1.0.0" }
|
||||||
|
@@ -1,5 +1,13 @@
|
|||||||
# Changes
|
# 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
|
## [0.4.1] - 2019-12-11
|
||||||
|
|
||||||
* Disconnect callback accepts owned state
|
* Disconnect callback accepts owned state
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-ioframe"
|
name = "actix-ioframe"
|
||||||
version = "0.4.1"
|
version = "0.5.0"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix framed service"
|
description = "Actix framed service"
|
||||||
keywords = ["network", "framework", "async", "futures"]
|
keywords = ["network", "framework", "async", "futures"]
|
||||||
@@ -10,19 +10,18 @@ documentation = "https://docs.rs/actix-ioframe/"
|
|||||||
categories = ["network-programming", "asynchronous"]
|
categories = ["network-programming", "asynchronous"]
|
||||||
license = "MIT/Apache-2.0"
|
license = "MIT/Apache-2.0"
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
workspace = ".."
|
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
name = "actix_ioframe"
|
name = "actix_ioframe"
|
||||||
path = "src/lib.rs"
|
path = "src/lib.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-service = "1.0.0"
|
actix-service = "1.0.1"
|
||||||
actix-codec = "0.2.0"
|
actix-codec = "0.2.0"
|
||||||
actix-utils = "1.0.1"
|
actix-utils = "1.0.4"
|
||||||
actix-rt = "1.0.0"
|
actix-rt = "1.0.0"
|
||||||
bytes = "0.5"
|
bytes = "0.5.3"
|
||||||
either = "1.5.2"
|
either = "1.5.3"
|
||||||
futures = "0.3.1"
|
futures = "0.3.1"
|
||||||
pin-project = "0.4.6"
|
pin-project = "0.4.6"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
|
@@ -3,17 +3,15 @@ use std::pin::Pin;
|
|||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
|
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
|
||||||
|
use actix_utils::mpsc::Receiver;
|
||||||
use futures::Stream;
|
use futures::Stream;
|
||||||
|
|
||||||
use crate::sink::Sink;
|
pub struct Connect<Io, Codec>
|
||||||
|
|
||||||
pub struct Connect<Io, Codec, St = ()>
|
|
||||||
where
|
where
|
||||||
Codec: Encoder + Decoder,
|
Codec: Encoder + Decoder,
|
||||||
{
|
{
|
||||||
io: Io,
|
io: Io,
|
||||||
sink: Sink<<Codec as Encoder>::Item>,
|
_t: PhantomData<Codec>,
|
||||||
_t: PhantomData<(St, Codec)>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<Io, Codec> Connect<Io, Codec>
|
impl<Io, Codec> Connect<Io, Codec>
|
||||||
@@ -21,36 +19,33 @@ where
|
|||||||
Io: AsyncRead + AsyncWrite,
|
Io: AsyncRead + AsyncWrite,
|
||||||
Codec: Encoder + Decoder,
|
Codec: Encoder + Decoder,
|
||||||
{
|
{
|
||||||
pub(crate) fn new(io: Io, sink: Sink<<Codec as Encoder>::Item>) -> Self {
|
pub(crate) fn new(io: Io) -> Self {
|
||||||
Self {
|
Self {
|
||||||
io,
|
io,
|
||||||
sink,
|
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn codec(self, codec: Codec) -> ConnectResult<Io, (), Codec> {
|
pub fn codec(
|
||||||
|
self,
|
||||||
|
codec: Codec,
|
||||||
|
) -> ConnectResult<Io, (), Codec, Receiver<<Codec as Encoder>::Item>> {
|
||||||
ConnectResult {
|
ConnectResult {
|
||||||
state: (),
|
state: (),
|
||||||
sink: self.sink,
|
out: None,
|
||||||
framed: Framed::new(self.io, codec),
|
framed: Framed::new(self.io, codec),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[pin_project::pin_project]
|
#[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) state: St,
|
||||||
|
pub(crate) out: Option<Out>,
|
||||||
pub(crate) framed: Framed<Io, Codec>,
|
pub(crate) framed: Framed<Io, Codec>,
|
||||||
pub(crate) sink: Sink<<Codec as Encoder>::Item>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<Io, St, Codec: Encoder + Decoder> ConnectResult<Io, St, Codec> {
|
impl<Io, St, Codec: Encoder + Decoder, Out: Unpin> ConnectResult<Io, St, Codec, Out> {
|
||||||
#[inline]
|
|
||||||
pub fn sink(&self) -> &Sink<<Codec as Encoder>::Item> {
|
|
||||||
&self.sink
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn get_ref(&self) -> &Io {
|
pub fn get_ref(&self) -> &Io {
|
||||||
self.framed.get_ref()
|
self.framed.get_ref()
|
||||||
@@ -61,17 +56,28 @@ impl<Io, St, Codec: Encoder + Decoder> ConnectResult<Io, St, Codec> {
|
|||||||
self.framed.get_mut()
|
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]
|
#[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 {
|
ConnectResult {
|
||||||
state,
|
state,
|
||||||
framed: self.framed,
|
framed: self.framed,
|
||||||
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
|
where
|
||||||
Io: AsyncRead + AsyncWrite,
|
Io: AsyncRead + AsyncWrite,
|
||||||
Codec: Encoder + Decoder,
|
Codec: Encoder + Decoder,
|
||||||
@@ -83,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
|
where
|
||||||
Io: AsyncRead + AsyncWrite,
|
Io: AsyncRead + AsyncWrite,
|
||||||
Codec: Encoder + Decoder,
|
Codec: Encoder + Decoder,
|
||||||
|
@@ -1,81 +1,56 @@
|
|||||||
//! Framed dispatcher service and related utilities
|
//! Framed dispatcher service and related utilities
|
||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
use std::rc::Rc;
|
|
||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
|
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
|
||||||
use actix_service::{IntoService, Service};
|
use actix_service::Service;
|
||||||
use actix_utils::{mpsc, oneshot};
|
use actix_utils::mpsc;
|
||||||
use futures::{FutureExt, Stream};
|
use futures::Stream;
|
||||||
use log::debug;
|
use log::debug;
|
||||||
|
|
||||||
use crate::error::ServiceError;
|
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;
|
type Response<U> = <U as Encoder>::Item;
|
||||||
|
|
||||||
pub(crate) enum Message<T> {
|
|
||||||
Item(T),
|
|
||||||
WaitClose(oneshot::Sender<()>),
|
|
||||||
Close,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// FramedTransport - is a future that reads frames from Framed object
|
/// FramedTransport - is a future that reads frames from Framed object
|
||||||
/// and pass then to the service.
|
/// and pass then to the service.
|
||||||
#[pin_project::pin_project]
|
pub(crate) struct Dispatcher<S, T, U, Out>
|
||||||
pub(crate) struct Dispatcher<St, S, T, U>
|
|
||||||
where
|
where
|
||||||
St: Clone,
|
S: Service<Request = Request<U>, Response = Option<Response<U>>>,
|
||||||
S: Service<Request = Request<St, U>, Response = Option<Response<U>>>,
|
|
||||||
S::Error: 'static,
|
S::Error: 'static,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
T: AsyncRead + AsyncWrite,
|
T: AsyncRead + AsyncWrite,
|
||||||
U: Encoder + Decoder,
|
U: Encoder + Decoder,
|
||||||
<U as Encoder>::Item: 'static,
|
<U as Encoder>::Item: 'static,
|
||||||
<U as Encoder>::Error: std::fmt::Debug,
|
<U as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <U as Encoder>::Item> + Unpin,
|
||||||
{
|
{
|
||||||
service: S,
|
service: S,
|
||||||
sink: Sink<<U as Encoder>::Item>,
|
sink: Option<Out>,
|
||||||
state: St,
|
state: FramedState<S, U>,
|
||||||
dispatch_state: FramedState<S, U>,
|
|
||||||
framed: Framed<T, U>,
|
framed: Framed<T, U>,
|
||||||
rx: mpsc::Receiver<Result<Message<<U as Encoder>::Item>, S::Error>>,
|
rx: mpsc::Receiver<Result<<U as Encoder>::Item, S::Error>>,
|
||||||
tx: mpsc::Sender<Result<Message<<U as Encoder>::Item>, S::Error>>,
|
|
||||||
disconnect: Option<Rc<dyn Fn(St, bool)>>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<St, S, T, U> Dispatcher<St, S, T, U>
|
impl<S, T, U, Out> Dispatcher<S, T, U, Out>
|
||||||
where
|
where
|
||||||
St: Clone,
|
S: Service<Request = Request<U>, Response = Option<Response<U>>>,
|
||||||
S: Service<Request = Request<St, U>, Response = Option<Response<U>>>,
|
|
||||||
S::Error: 'static,
|
S::Error: 'static,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
T: AsyncRead + AsyncWrite,
|
T: AsyncRead + AsyncWrite,
|
||||||
U: Decoder + Encoder,
|
U: Decoder + Encoder,
|
||||||
<U as Encoder>::Item: 'static,
|
<U as Encoder>::Item: 'static,
|
||||||
<U as Encoder>::Error: std::fmt::Debug,
|
<U as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <U as Encoder>::Item> + Unpin,
|
||||||
{
|
{
|
||||||
pub(crate) fn new<F: IntoService<S>>(
|
pub(crate) fn new(framed: Framed<T, U>, service: S, sink: Option<Out>) -> Self {
|
||||||
framed: Framed<T, U>,
|
|
||||||
state: St,
|
|
||||||
service: F,
|
|
||||||
sink: Sink<<U as Encoder>::Item>,
|
|
||||||
rx: mpsc::Receiver<Result<Message<<U as Encoder>::Item>, S::Error>>,
|
|
||||||
disconnect: Option<Rc<dyn Fn(St, bool)>>,
|
|
||||||
) -> Self {
|
|
||||||
let tx = rx.sender();
|
|
||||||
|
|
||||||
Dispatcher {
|
Dispatcher {
|
||||||
framed,
|
|
||||||
state,
|
|
||||||
sink,
|
sink,
|
||||||
disconnect,
|
service,
|
||||||
rx,
|
framed,
|
||||||
tx,
|
rx: mpsc::channel().1,
|
||||||
service: service.into_service(),
|
state: FramedState::Processing,
|
||||||
dispatch_state: FramedState::Processing,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -84,33 +59,11 @@ enum FramedState<S: Service, U: Encoder + Decoder> {
|
|||||||
Processing,
|
Processing,
|
||||||
Error(ServiceError<S::Error, U>),
|
Error(ServiceError<S::Error, U>),
|
||||||
FramedError(ServiceError<S::Error, U>),
|
FramedError(ServiceError<S::Error, U>),
|
||||||
FlushAndStop(Vec<oneshot::Sender<()>>),
|
FlushAndStop,
|
||||||
Stopping,
|
Stopping,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S: Service, U: Encoder + Decoder> FramedState<S, U> {
|
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> {
|
fn take_error(&mut self) -> ServiceError<S::Error, U> {
|
||||||
match std::mem::replace(self, FramedState::Processing) {
|
match std::mem::replace(self, FramedState::Processing) {
|
||||||
FramedState::Error(err) => err,
|
FramedState::Error(err) => err,
|
||||||
@@ -126,16 +79,16 @@ impl<S: Service, U: Encoder + Decoder> FramedState<S, U> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<St, S, T, U> Dispatcher<St, S, T, U>
|
impl<S, T, U, Out> Dispatcher<S, T, U, Out>
|
||||||
where
|
where
|
||||||
St: Clone,
|
S: Service<Request = Request<U>, Response = Option<Response<U>>>,
|
||||||
S: Service<Request = Request<St, U>, Response = Option<Response<U>>>,
|
|
||||||
S::Error: 'static,
|
S::Error: 'static,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
T: AsyncRead + AsyncWrite,
|
T: AsyncRead + AsyncWrite,
|
||||||
U: Decoder + Encoder,
|
U: Decoder + Encoder,
|
||||||
<U as Encoder>::Item: 'static,
|
<U as Encoder>::Item: 'static,
|
||||||
<U as Encoder>::Error: std::fmt::Debug,
|
<U as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <U as Encoder>::Item> + Unpin,
|
||||||
{
|
{
|
||||||
fn poll_read(&mut self, cx: &mut Context<'_>) -> bool {
|
fn poll_read(&mut self, cx: &mut Context<'_>) -> bool {
|
||||||
loop {
|
loop {
|
||||||
@@ -144,35 +97,32 @@ where
|
|||||||
let item = match self.framed.next_item(cx) {
|
let item = match self.framed.next_item(cx) {
|
||||||
Poll::Ready(Some(Ok(el))) => el,
|
Poll::Ready(Some(Ok(el))) => el,
|
||||||
Poll::Ready(Some(Err(err))) => {
|
Poll::Ready(Some(Err(err))) => {
|
||||||
self.dispatch_state =
|
self.state = FramedState::FramedError(ServiceError::Decoder(err));
|
||||||
FramedState::FramedError(ServiceError::Decoder(err));
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
Poll::Pending => return false,
|
Poll::Pending => return false,
|
||||||
Poll::Ready(None) => {
|
Poll::Ready(None) => {
|
||||||
log::trace!("Client disconnected");
|
log::trace!("Client disconnected");
|
||||||
self.dispatch_state = FramedState::Stopping;
|
self.state = FramedState::Stopping;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let tx = self.tx.clone();
|
let tx = self.rx.sender();
|
||||||
actix_rt::spawn(
|
let fut = self.service.call(item);
|
||||||
self.service
|
actix_rt::spawn(async move {
|
||||||
.call(Item::new(self.state.clone(), self.sink.clone(), item))
|
let item = fut.await;
|
||||||
.map(move |item| {
|
let item = match item {
|
||||||
let item = match item {
|
Ok(Some(item)) => Ok(item),
|
||||||
Ok(Some(item)) => Ok(Message::Item(item)),
|
Ok(None) => return,
|
||||||
Ok(None) => return,
|
Err(err) => Err(err),
|
||||||
Err(err) => Err(err),
|
};
|
||||||
};
|
let _ = tx.send(item);
|
||||||
let _ = tx.send(item);
|
});
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
Poll::Pending => return false,
|
Poll::Pending => return false,
|
||||||
Poll::Ready(Err(err)) => {
|
Poll::Ready(Err(err)) => {
|
||||||
self.dispatch_state = FramedState::Error(ServiceError::Service(err));
|
self.state = FramedState::Error(ServiceError::Service(err));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -184,27 +134,39 @@ where
|
|||||||
loop {
|
loop {
|
||||||
while !self.framed.is_write_buf_full() {
|
while !self.framed.is_write_buf_full() {
|
||||||
match Pin::new(&mut self.rx).poll_next(cx) {
|
match Pin::new(&mut self.rx).poll_next(cx) {
|
||||||
Poll::Ready(Some(Ok(Message::Item(msg)))) => {
|
Poll::Ready(Some(Ok(msg))) => {
|
||||||
if let Err(err) = self.framed.write(msg) {
|
if let Err(err) = self.framed.write(msg) {
|
||||||
self.dispatch_state =
|
self.state = FramedState::FramedError(ServiceError::Encoder(err));
|
||||||
FramedState::FramedError(ServiceError::Encoder(err));
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
continue;
|
||||||
Poll::Ready(Some(Ok(Message::Close))) => {
|
|
||||||
self.dispatch_state.stop(None);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
Poll::Ready(Some(Ok(Message::WaitClose(tx)))) => {
|
|
||||||
self.dispatch_state.stop(Some(tx));
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
Poll::Ready(Some(Err(err))) => {
|
Poll::Ready(Some(Err(err))) => {
|
||||||
self.dispatch_state = FramedState::Error(ServiceError::Service(err));
|
self.state = FramedState::Error(ServiceError::Service(err));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
Poll::Ready(None) | Poll::Pending => break,
|
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() {
|
if !self.framed.is_write_buf_empty() {
|
||||||
@@ -213,8 +175,7 @@ where
|
|||||||
Poll::Ready(Ok(_)) => (),
|
Poll::Ready(Ok(_)) => (),
|
||||||
Poll::Ready(Err(err)) => {
|
Poll::Ready(Err(err)) => {
|
||||||
debug!("Error sending data: {:?}", err);
|
debug!("Error sending data: {:?}", err);
|
||||||
self.dispatch_state =
|
self.state = FramedState::FramedError(ServiceError::Encoder(err));
|
||||||
FramedState::FramedError(ServiceError::Encoder(err));
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -229,14 +190,16 @@ where
|
|||||||
&mut self,
|
&mut self,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Poll<Result<(), ServiceError<S::Error, U>>> {
|
) -> Poll<Result<(), ServiceError<S::Error, U>>> {
|
||||||
match self.dispatch_state {
|
match self.state {
|
||||||
FramedState::Processing => {
|
FramedState::Processing => loop {
|
||||||
if self.poll_read(cx) || self.poll_write(cx) {
|
let read = self.poll_read(cx);
|
||||||
self.poll(cx)
|
let write = self.poll_write(cx);
|
||||||
|
if read || write {
|
||||||
|
continue;
|
||||||
} else {
|
} else {
|
||||||
Poll::Pending
|
return Poll::Pending;
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
FramedState::Error(_) => {
|
FramedState::Error(_) => {
|
||||||
// flush write buffer
|
// flush write buffer
|
||||||
if !self.framed.is_write_buf_empty() {
|
if !self.framed.is_write_buf_empty() {
|
||||||
@@ -244,12 +207,21 @@ where
|
|||||||
return Poll::Pending;
|
return Poll::Pending;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if let Some(ref disconnect) = self.disconnect {
|
Poll::Ready(Err(self.state.take_error()))
|
||||||
(&*disconnect)(self.state.clone(), true);
|
|
||||||
}
|
|
||||||
Poll::Ready(Err(self.dispatch_state.take_error()))
|
|
||||||
}
|
}
|
||||||
FramedState::FlushAndStop(ref mut vec) => {
|
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::Ready(Some(Err(_))) => return Poll::Ready(Ok(())),
|
||||||
|
Poll::Ready(None) | Poll::Pending => (),
|
||||||
|
}
|
||||||
|
|
||||||
|
// flush io
|
||||||
if !self.framed.is_write_buf_empty() {
|
if !self.framed.is_write_buf_empty() {
|
||||||
match self.framed.flush(cx) {
|
match self.framed.flush(cx) {
|
||||||
Poll::Ready(Err(err)) => {
|
Poll::Ready(Err(err)) => {
|
||||||
@@ -261,26 +233,10 @@ where
|
|||||||
Poll::Ready(_) => (),
|
Poll::Ready(_) => (),
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
for tx in vec.drain(..) {
|
|
||||||
let _ = tx.send(());
|
|
||||||
}
|
|
||||||
if let Some(ref disconnect) = self.disconnect {
|
|
||||||
(&*disconnect)(self.state.clone(), false);
|
|
||||||
}
|
|
||||||
Poll::Ready(Ok(()))
|
|
||||||
}
|
|
||||||
FramedState::FramedError(_) => {
|
|
||||||
if let Some(ref disconnect) = self.disconnect {
|
|
||||||
(&*disconnect)(self.state.clone(), true);
|
|
||||||
}
|
|
||||||
Poll::Ready(Err(self.dispatch_state.take_framed_error()))
|
|
||||||
}
|
|
||||||
FramedState::Stopping => {
|
|
||||||
if let Some(ref disconnect) = self.disconnect {
|
|
||||||
(&*disconnect)(self.state.clone(), false);
|
|
||||||
}
|
|
||||||
Poll::Ready(Ok(()))
|
Poll::Ready(Ok(()))
|
||||||
}
|
}
|
||||||
|
FramedState::FramedError(_) => Poll::Ready(Err(self.state.take_framed_error())),
|
||||||
|
FramedState::Stopping => Poll::Ready(Ok(())),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -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("Item").field(&self.item).finish()
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,15 +1,11 @@
|
|||||||
#![deny(rust_2018_idioms, warnings)]
|
// #![deny(rust_2018_idioms, warnings)]
|
||||||
#![allow(clippy::type_complexity, clippy::too_many_arguments)]
|
#![allow(clippy::type_complexity, clippy::too_many_arguments)]
|
||||||
|
|
||||||
mod connect;
|
mod connect;
|
||||||
mod dispatcher;
|
mod dispatcher;
|
||||||
mod error;
|
mod error;
|
||||||
mod item;
|
|
||||||
mod service;
|
mod service;
|
||||||
mod sink;
|
|
||||||
|
|
||||||
pub use self::connect::{Connect, ConnectResult};
|
pub use self::connect::{Connect, ConnectResult};
|
||||||
pub use self::error::ServiceError;
|
pub use self::error::ServiceError;
|
||||||
pub use self::item::Item;
|
pub use self::service::{Builder, FactoryBuilder};
|
||||||
pub use self::service::{Builder, NewServiceBuilder, ServiceBuilder};
|
|
||||||
pub use self::sink::Sink;
|
|
||||||
|
@@ -4,108 +4,57 @@ use std::pin::Pin;
|
|||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder};
|
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
|
||||||
use actix_service::{IntoService, IntoServiceFactory, Service, ServiceFactory};
|
use actix_service::{IntoService, IntoServiceFactory, Service, ServiceFactory};
|
||||||
use actix_utils::mpsc;
|
|
||||||
use either::Either;
|
use either::Either;
|
||||||
use futures::future::{FutureExt, LocalBoxFuture};
|
use futures::{ready, Stream};
|
||||||
use pin_project::project;
|
use pin_project::project;
|
||||||
|
|
||||||
use crate::connect::{Connect, ConnectResult};
|
use crate::connect::{Connect, ConnectResult};
|
||||||
use crate::dispatcher::{Dispatcher, Message};
|
use crate::dispatcher::Dispatcher;
|
||||||
use crate::error::ServiceError;
|
use crate::error::ServiceError;
|
||||||
use crate::item::Item;
|
|
||||||
use crate::sink::Sink;
|
|
||||||
|
|
||||||
type RequestItem<S, U> = Item<S, U>;
|
type RequestItem<U> = <U as Decoder>::Item;
|
||||||
type ResponseItem<U> = Option<<U as Encoder>::Item>;
|
type ResponseItem<U> = Option<<U as Encoder>::Item>;
|
||||||
type ServiceResult<U, E> = Result<Message<<U as Encoder>::Item>, E>;
|
|
||||||
|
|
||||||
/// Service builder - structure that follows the builder pattern
|
/// Service builder - structure that follows the builder pattern
|
||||||
/// for building instances for framed services.
|
/// for building instances for framed services.
|
||||||
pub struct Builder<St, Codec>(PhantomData<(St, Codec)>);
|
pub struct Builder<St, C, Io, Codec, Out> {
|
||||||
|
|
||||||
impl<St: Clone, Codec> Default for Builder<St, Codec> {
|
|
||||||
fn default() -> Builder<St, Codec> {
|
|
||||||
Builder::new()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<St: Clone, Codec> Builder<St, Codec> {
|
|
||||||
pub fn new() -> Builder<St, Codec> {
|
|
||||||
Builder(PhantomData)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Construct framed handler service with specified connect service
|
|
||||||
pub fn service<Io, C, F>(self, connect: F) -> ServiceBuilder<St, C, Io, Codec>
|
|
||||||
where
|
|
||||||
F: IntoService<C>,
|
|
||||||
Io: AsyncRead + AsyncWrite,
|
|
||||||
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec>>,
|
|
||||||
Codec: Decoder + Encoder,
|
|
||||||
{
|
|
||||||
ServiceBuilder {
|
|
||||||
connect: connect.into_service(),
|
|
||||||
disconnect: None,
|
|
||||||
_t: PhantomData,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Construct framed handler new service with specified connect service
|
|
||||||
pub fn factory<Io, C, F>(self, connect: F) -> NewServiceBuilder<St, C, Io, Codec>
|
|
||||||
where
|
|
||||||
F: IntoServiceFactory<C>,
|
|
||||||
Io: AsyncRead + AsyncWrite,
|
|
||||||
C: ServiceFactory<
|
|
||||||
Config = (),
|
|
||||||
Request = Connect<Io, Codec>,
|
|
||||||
Response = ConnectResult<Io, St, Codec>,
|
|
||||||
>,
|
|
||||||
C::Error: 'static,
|
|
||||||
C::Future: 'static,
|
|
||||||
Codec: Decoder + Encoder,
|
|
||||||
{
|
|
||||||
NewServiceBuilder {
|
|
||||||
connect: connect.into_factory(),
|
|
||||||
disconnect: None,
|
|
||||||
_t: PhantomData,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct ServiceBuilder<St, C, Io, Codec> {
|
|
||||||
connect: C,
|
connect: C,
|
||||||
disconnect: Option<Rc<dyn Fn(St, bool)>>,
|
_t: PhantomData<(St, Io, Codec, Out)>,
|
||||||
_t: PhantomData<(St, Io, Codec)>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<St, C, Io, Codec> ServiceBuilder<St, C, Io, Codec>
|
impl<St, C, Io, Codec, Out> Builder<St, C, Io, Codec, Out>
|
||||||
where
|
where
|
||||||
St: Clone,
|
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec, Out>>,
|
||||||
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec>>,
|
|
||||||
Io: AsyncRead + AsyncWrite,
|
Io: AsyncRead + AsyncWrite,
|
||||||
Codec: Decoder + Encoder,
|
Codec: Decoder + Encoder,
|
||||||
<Codec as Encoder>::Item: 'static,
|
<Codec as Encoder>::Item: 'static,
|
||||||
<Codec as Encoder>::Error: std::fmt::Debug,
|
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
|
||||||
{
|
{
|
||||||
/// Callback to execute on disconnect
|
/// Construct framed handler service with specified connect service
|
||||||
///
|
pub fn new<F>(connect: F) -> Builder<St, C, Io, Codec, Out>
|
||||||
/// Second parameter indicates error occured during disconnect.
|
|
||||||
pub fn disconnect<F, Out>(mut self, disconnect: F) -> Self
|
|
||||||
where
|
where
|
||||||
F: Fn(St, bool) + 'static,
|
F: IntoService<C>,
|
||||||
|
Io: AsyncRead + AsyncWrite,
|
||||||
|
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec, Out>>,
|
||||||
|
Codec: Decoder + Encoder,
|
||||||
|
Out: Stream<Item = <Codec as Encoder>::Item>,
|
||||||
{
|
{
|
||||||
self.disconnect = Some(Rc::new(disconnect));
|
Builder {
|
||||||
self
|
connect: connect.into_service(),
|
||||||
|
_t: PhantomData,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Provide stream items handler service and construct service factory.
|
/// Provide stream items handler service and construct service factory.
|
||||||
pub fn finish<F, T>(self, service: F) -> FramedServiceImpl<St, C, T, Io, Codec>
|
pub fn build<F, T>(self, service: F) -> FramedServiceImpl<St, C, T, Io, Codec, Out>
|
||||||
where
|
where
|
||||||
F: IntoServiceFactory<T>,
|
F: IntoServiceFactory<T>,
|
||||||
T: ServiceFactory<
|
T: ServiceFactory<
|
||||||
Config = St,
|
Config = St,
|
||||||
Request = RequestItem<St, Codec>,
|
Request = RequestItem<Codec>,
|
||||||
Response = ResponseItem<Codec>,
|
Response = ResponseItem<Codec>,
|
||||||
Error = C::Error,
|
Error = C::Error,
|
||||||
InitError = C::Error,
|
InitError = C::Error,
|
||||||
@@ -114,211 +63,261 @@ where
|
|||||||
FramedServiceImpl {
|
FramedServiceImpl {
|
||||||
connect: self.connect,
|
connect: self.connect,
|
||||||
handler: Rc::new(service.into_factory()),
|
handler: Rc::new(service.into_factory()),
|
||||||
disconnect: self.disconnect.clone(),
|
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct NewServiceBuilder<St, C, Io, Codec> {
|
/// Service builder - structure that follows the builder pattern
|
||||||
|
/// for building instances for framed services.
|
||||||
|
pub struct FactoryBuilder<St, C, Io, Codec, Out> {
|
||||||
connect: C,
|
connect: C,
|
||||||
disconnect: Option<Rc<dyn Fn(St, bool)>>,
|
_t: PhantomData<(St, Io, Codec, Out)>,
|
||||||
_t: PhantomData<(St, Io, Codec)>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<St, C, Io, Codec> NewServiceBuilder<St, C, Io, Codec>
|
impl<St, C, Io, Codec, Out> FactoryBuilder<St, C, Io, Codec, Out>
|
||||||
where
|
where
|
||||||
St: Clone,
|
|
||||||
Io: AsyncRead + AsyncWrite,
|
Io: AsyncRead + AsyncWrite,
|
||||||
C: ServiceFactory<
|
C: ServiceFactory<
|
||||||
Config = (),
|
Config = (),
|
||||||
Request = Connect<Io, Codec>,
|
Request = Connect<Io, Codec>,
|
||||||
Response = ConnectResult<Io, St, Codec>,
|
Response = ConnectResult<Io, St, Codec, Out>,
|
||||||
>,
|
>,
|
||||||
C::Error: 'static,
|
|
||||||
C::Future: 'static,
|
|
||||||
Codec: Decoder + Encoder,
|
Codec: Decoder + Encoder,
|
||||||
<Codec as Encoder>::Item: 'static,
|
|
||||||
<Codec as Encoder>::Error: std::fmt::Debug,
|
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
|
||||||
{
|
{
|
||||||
/// Callback to execute on disconnect
|
/// Construct framed handler new service with specified connect service
|
||||||
///
|
pub fn new<F>(connect: F) -> FactoryBuilder<St, C, Io, Codec, Out>
|
||||||
/// Second parameter indicates error occured during disconnect.
|
|
||||||
pub fn disconnect<F>(mut self, disconnect: F) -> Self
|
|
||||||
where
|
where
|
||||||
F: Fn(St, bool) + 'static,
|
F: IntoServiceFactory<C>,
|
||||||
|
Io: AsyncRead + AsyncWrite,
|
||||||
|
C: ServiceFactory<
|
||||||
|
Config = (),
|
||||||
|
Request = Connect<Io, Codec>,
|
||||||
|
Response = ConnectResult<Io, St, Codec, Out>,
|
||||||
|
>,
|
||||||
|
Codec: Decoder + Encoder,
|
||||||
|
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
|
||||||
{
|
{
|
||||||
self.disconnect = Some(Rc::new(disconnect));
|
FactoryBuilder {
|
||||||
self
|
connect: connect.into_factory(),
|
||||||
|
_t: PhantomData,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn finish<F, T, Cfg>(self, service: F) -> FramedService<St, C, T, Io, Codec, Cfg>
|
pub fn build<F, T, Cfg>(self, service: F) -> FramedService<St, C, T, Io, Codec, Out, Cfg>
|
||||||
where
|
where
|
||||||
F: IntoServiceFactory<T>,
|
F: IntoServiceFactory<T>,
|
||||||
T: ServiceFactory<
|
T: ServiceFactory<
|
||||||
Config = St,
|
Config = St,
|
||||||
Request = RequestItem<St, Codec>,
|
Request = RequestItem<Codec>,
|
||||||
Response = ResponseItem<Codec>,
|
Response = ResponseItem<Codec>,
|
||||||
Error = C::Error,
|
Error = C::Error,
|
||||||
InitError = C::Error,
|
InitError = C::Error,
|
||||||
> + 'static,
|
>,
|
||||||
{
|
{
|
||||||
FramedService {
|
FramedService {
|
||||||
connect: self.connect,
|
connect: self.connect,
|
||||||
handler: Rc::new(service.into_factory()),
|
handler: Rc::new(service.into_factory()),
|
||||||
disconnect: self.disconnect,
|
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct FramedService<St, C, T, Io, Codec, Cfg> {
|
pub struct FramedService<St, C, T, Io, Codec, Out, Cfg> {
|
||||||
connect: C,
|
connect: C,
|
||||||
handler: Rc<T>,
|
handler: Rc<T>,
|
||||||
disconnect: Option<Rc<dyn Fn(St, bool)>>,
|
_t: PhantomData<(St, Io, Codec, Out, Cfg)>,
|
||||||
_t: PhantomData<(St, Io, Codec, 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
|
where
|
||||||
St: Clone + 'static,
|
|
||||||
Io: AsyncRead + AsyncWrite,
|
Io: AsyncRead + AsyncWrite,
|
||||||
C: ServiceFactory<
|
C: ServiceFactory<
|
||||||
Config = (),
|
Config = (),
|
||||||
Request = Connect<Io, Codec>,
|
Request = Connect<Io, Codec>,
|
||||||
Response = ConnectResult<Io, St, Codec>,
|
Response = ConnectResult<Io, St, Codec, Out>,
|
||||||
>,
|
>,
|
||||||
C::Error: 'static,
|
|
||||||
C::Future: 'static,
|
|
||||||
T: ServiceFactory<
|
T: ServiceFactory<
|
||||||
Config = St,
|
Config = St,
|
||||||
Request = RequestItem<St, Codec>,
|
Request = RequestItem<Codec>,
|
||||||
Response = ResponseItem<Codec>,
|
Response = ResponseItem<Codec>,
|
||||||
Error = C::Error,
|
Error = C::Error,
|
||||||
InitError = C::Error,
|
InitError = C::Error,
|
||||||
> + 'static,
|
>,
|
||||||
|
<T::Service as Service>::Error: 'static,
|
||||||
<T::Service as Service>::Future: 'static,
|
<T::Service as Service>::Future: 'static,
|
||||||
Codec: Decoder + Encoder,
|
Codec: Decoder + Encoder,
|
||||||
<Codec as Encoder>::Item: 'static,
|
<Codec as Encoder>::Item: 'static,
|
||||||
<Codec as Encoder>::Error: std::fmt::Debug,
|
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
|
||||||
{
|
{
|
||||||
type Config = Cfg;
|
type Config = Cfg;
|
||||||
type Request = Io;
|
type Request = Io;
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = ServiceError<C::Error, Codec>;
|
type Error = ServiceError<C::Error, Codec>;
|
||||||
type InitError = C::InitError;
|
type InitError = C::InitError;
|
||||||
type Service = FramedServiceImpl<St, C::Service, T, Io, Codec>;
|
type Service = FramedServiceImpl<St, C::Service, T, Io, Codec, Out>;
|
||||||
type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>;
|
type Future = FramedServiceResponse<St, C, T, Io, Codec, Out>;
|
||||||
|
|
||||||
fn new_service(&self, _: Cfg) -> Self::Future {
|
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
|
// create connect service and then create service impl
|
||||||
self.connect
|
FramedServiceResponse {
|
||||||
.new_service(())
|
fut: self.connect.new_service(()),
|
||||||
.map(move |result| {
|
handler: self.handler.clone(),
|
||||||
result.map(move |connect| FramedServiceImpl {
|
}
|
||||||
connect,
|
|
||||||
handler,
|
|
||||||
disconnect,
|
|
||||||
_t: PhantomData,
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.boxed_local()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct FramedServiceImpl<St, C, T, Io, Codec> {
|
#[pin_project::pin_project]
|
||||||
connect: C,
|
pub struct FramedServiceResponse<St, C, T, Io, Codec, Out>
|
||||||
handler: Rc<T>,
|
|
||||||
disconnect: Option<Rc<dyn Fn(St, bool)>>,
|
|
||||||
_t: PhantomData<(St, Io, Codec)>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<St, C, T, Io, Codec> Service for FramedServiceImpl<St, C, T, Io, Codec>
|
|
||||||
where
|
where
|
||||||
St: Clone,
|
|
||||||
Io: AsyncRead + AsyncWrite,
|
Io: AsyncRead + AsyncWrite,
|
||||||
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec>>,
|
C: ServiceFactory<
|
||||||
C::Error: 'static,
|
Config = (),
|
||||||
|
Request = Connect<Io, Codec>,
|
||||||
|
Response = ConnectResult<Io, St, Codec, Out>,
|
||||||
|
>,
|
||||||
T: ServiceFactory<
|
T: ServiceFactory<
|
||||||
Config = St,
|
Config = St,
|
||||||
Request = RequestItem<St, Codec>,
|
Request = RequestItem<Codec>,
|
||||||
Response = ResponseItem<Codec>,
|
Response = ResponseItem<Codec>,
|
||||||
Error = C::Error,
|
Error = C::Error,
|
||||||
InitError = C::Error,
|
InitError = C::Error,
|
||||||
>,
|
>,
|
||||||
|
<T::Service as Service>::Error: 'static,
|
||||||
<T::Service as Service>::Future: 'static,
|
<T::Service as Service>::Future: 'static,
|
||||||
Codec: Decoder + Encoder,
|
Codec: Decoder + Encoder,
|
||||||
<Codec as Encoder>::Item: 'static,
|
<Codec as Encoder>::Item: 'static,
|
||||||
<Codec as Encoder>::Error: std::fmt::Debug,
|
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||||
|
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 Request = Io;
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = ServiceError<C::Error, Codec>;
|
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>> {
|
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||||
self.connect.poll_ready(cx).map_err(|e| e.into())
|
self.connect.poll_ready(cx).map_err(|e| e.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: Io) -> Self::Future {
|
fn call(&mut self, req: Io) -> Self::Future {
|
||||||
let (tx, rx) = mpsc::channel();
|
|
||||||
let sink = Sink::new(Rc::new(move |msg| {
|
|
||||||
let _ = tx.send(Ok(msg));
|
|
||||||
}));
|
|
||||||
FramedServiceImplResponse {
|
FramedServiceImplResponse {
|
||||||
inner: FramedServiceImplResponseInner::Connect(
|
inner: FramedServiceImplResponseInner::Connect(
|
||||||
self.connect.call(Connect::new(req, sink.clone())),
|
self.connect.call(Connect::new(req)),
|
||||||
self.handler.clone(),
|
self.handler.clone(),
|
||||||
self.disconnect.clone(),
|
|
||||||
Some(rx),
|
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[pin_project::pin_project]
|
#[pin_project::pin_project]
|
||||||
pub struct FramedServiceImplResponse<St, Io, Codec, C, T>
|
pub struct FramedServiceImplResponse<St, Io, Codec, Out, C, T>
|
||||||
where
|
where
|
||||||
St: Clone,
|
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec, Out>>,
|
||||||
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec>>,
|
|
||||||
C::Error: 'static,
|
|
||||||
T: ServiceFactory<
|
T: ServiceFactory<
|
||||||
Config = St,
|
Config = St,
|
||||||
Request = RequestItem<St, Codec>,
|
Request = RequestItem<Codec>,
|
||||||
Response = ResponseItem<Codec>,
|
Response = ResponseItem<Codec>,
|
||||||
Error = C::Error,
|
Error = C::Error,
|
||||||
InitError = C::Error,
|
InitError = C::Error,
|
||||||
>,
|
>,
|
||||||
|
<T::Service as Service>::Error: 'static,
|
||||||
<T::Service as Service>::Future: 'static,
|
<T::Service as Service>::Future: 'static,
|
||||||
Io: AsyncRead + AsyncWrite,
|
Io: AsyncRead + AsyncWrite,
|
||||||
Codec: Encoder + Decoder,
|
Codec: Encoder + Decoder,
|
||||||
<Codec as Encoder>::Item: 'static,
|
<Codec as Encoder>::Item: 'static,
|
||||||
<Codec as Encoder>::Error: std::fmt::Debug,
|
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
|
||||||
{
|
{
|
||||||
#[pin]
|
#[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
|
where
|
||||||
St: Clone,
|
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec, Out>>,
|
||||||
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec>>,
|
|
||||||
C::Error: 'static,
|
|
||||||
T: ServiceFactory<
|
T: ServiceFactory<
|
||||||
Config = St,
|
Config = St,
|
||||||
Request = RequestItem<St, Codec>,
|
Request = RequestItem<Codec>,
|
||||||
Response = ResponseItem<Codec>,
|
Response = ResponseItem<Codec>,
|
||||||
Error = C::Error,
|
Error = C::Error,
|
||||||
InitError = C::Error,
|
InitError = C::Error,
|
||||||
>,
|
>,
|
||||||
|
<T::Service as Service>::Error: 'static,
|
||||||
<T::Service as Service>::Future: 'static,
|
<T::Service as Service>::Future: 'static,
|
||||||
Io: AsyncRead + AsyncWrite,
|
Io: AsyncRead + AsyncWrite,
|
||||||
Codec: Encoder + Decoder,
|
Codec: Encoder + Decoder,
|
||||||
<Codec as Encoder>::Item: 'static,
|
<Codec as Encoder>::Item: 'static,
|
||||||
<Codec as Encoder>::Error: std::fmt::Debug,
|
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
|
||||||
{
|
{
|
||||||
type Output = Result<(), ServiceError<C::Error, Codec>>;
|
type Output = Result<(), ServiceError<C::Error, Codec>>;
|
||||||
|
|
||||||
@@ -338,94 +337,71 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[pin_project::pin_project]
|
#[pin_project::pin_project]
|
||||||
enum FramedServiceImplResponseInner<St, Io, Codec, C, T>
|
enum FramedServiceImplResponseInner<St, Io, Codec, Out, C, T>
|
||||||
where
|
where
|
||||||
St: Clone,
|
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec, Out>>,
|
||||||
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec>>,
|
|
||||||
C::Error: 'static,
|
|
||||||
T: ServiceFactory<
|
T: ServiceFactory<
|
||||||
Config = St,
|
Config = St,
|
||||||
Request = RequestItem<St, Codec>,
|
Request = RequestItem<Codec>,
|
||||||
Response = ResponseItem<Codec>,
|
Response = ResponseItem<Codec>,
|
||||||
Error = C::Error,
|
Error = C::Error,
|
||||||
InitError = C::Error,
|
InitError = C::Error,
|
||||||
>,
|
>,
|
||||||
|
<T::Service as Service>::Error: 'static,
|
||||||
<T::Service as Service>::Future: 'static,
|
<T::Service as Service>::Future: 'static,
|
||||||
Io: AsyncRead + AsyncWrite,
|
Io: AsyncRead + AsyncWrite,
|
||||||
Codec: Encoder + Decoder,
|
Codec: Encoder + Decoder,
|
||||||
<Codec as Encoder>::Item: 'static,
|
<Codec as Encoder>::Item: 'static,
|
||||||
<Codec as Encoder>::Error: std::fmt::Debug,
|
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
|
||||||
{
|
{
|
||||||
Connect(
|
Connect(#[pin] C::Future, Rc<T>),
|
||||||
#[pin] C::Future,
|
Handler(#[pin] T::Future, Option<Framed<Io, Codec>>, Option<Out>),
|
||||||
Rc<T>,
|
Dispatcher(Dispatcher<T::Service, Io, Codec, Out>),
|
||||||
Option<Rc<dyn Fn(St, bool)>>,
|
|
||||||
Option<mpsc::Receiver<ServiceResult<Codec, C::Error>>>,
|
|
||||||
),
|
|
||||||
Handler(
|
|
||||||
#[pin] T::Future,
|
|
||||||
Option<ConnectResult<Io, St, Codec>>,
|
|
||||||
Option<Rc<dyn Fn(St, bool)>>,
|
|
||||||
Option<mpsc::Receiver<ServiceResult<Codec, C::Error>>>,
|
|
||||||
),
|
|
||||||
Dispatcher(Dispatcher<St, T::Service, Io, Codec>),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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
|
where
|
||||||
St: Clone,
|
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec, Out>>,
|
||||||
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec>>,
|
|
||||||
C::Error: 'static,
|
|
||||||
T: ServiceFactory<
|
T: ServiceFactory<
|
||||||
Config = St,
|
Config = St,
|
||||||
Request = RequestItem<St, Codec>,
|
Request = RequestItem<Codec>,
|
||||||
Response = ResponseItem<Codec>,
|
Response = ResponseItem<Codec>,
|
||||||
Error = C::Error,
|
Error = C::Error,
|
||||||
InitError = C::Error,
|
InitError = C::Error,
|
||||||
>,
|
>,
|
||||||
|
<T::Service as Service>::Error: 'static,
|
||||||
<T::Service as Service>::Future: 'static,
|
<T::Service as Service>::Future: 'static,
|
||||||
Io: AsyncRead + AsyncWrite,
|
Io: AsyncRead + AsyncWrite,
|
||||||
Codec: Encoder + Decoder,
|
Codec: Encoder + Decoder,
|
||||||
<Codec as Encoder>::Item: 'static,
|
<Codec as Encoder>::Item: 'static,
|
||||||
<Codec as Encoder>::Error: std::fmt::Debug,
|
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
|
||||||
{
|
{
|
||||||
#[project]
|
#[project]
|
||||||
fn poll(
|
fn poll(
|
||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Either<
|
) -> Either<
|
||||||
FramedServiceImplResponseInner<St, Io, Codec, C, T>,
|
FramedServiceImplResponseInner<St, Io, Codec, Out, C, T>,
|
||||||
Poll<Result<(), ServiceError<C::Error, Codec>>>,
|
Poll<Result<(), ServiceError<C::Error, Codec>>>,
|
||||||
> {
|
> {
|
||||||
#[project]
|
#[project]
|
||||||
match self.project() {
|
match self.project() {
|
||||||
FramedServiceImplResponseInner::Connect(fut, handler, disconnect, rx) => {
|
FramedServiceImplResponseInner::Connect(fut, handler) => match fut.poll(cx) {
|
||||||
match fut.poll(cx) {
|
Poll::Ready(Ok(res)) => Either::Left(FramedServiceImplResponseInner::Handler(
|
||||||
Poll::Ready(Ok(res)) => {
|
handler.new_service(res.state),
|
||||||
Either::Left(FramedServiceImplResponseInner::Handler(
|
Some(res.framed),
|
||||||
handler.new_service(res.state.clone()),
|
res.out,
|
||||||
Some(res),
|
)),
|
||||||
disconnect.take(),
|
Poll::Pending => Either::Right(Poll::Pending),
|
||||||
rx.take(),
|
Poll::Ready(Err(e)) => Either::Right(Poll::Ready(Err(e.into()))),
|
||||||
))
|
},
|
||||||
}
|
FramedServiceImplResponseInner::Handler(fut, framed, out) => {
|
||||||
Poll::Pending => Either::Right(Poll::Pending),
|
|
||||||
Poll::Ready(Err(e)) => Either::Right(Poll::Ready(Err(e.into()))),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
FramedServiceImplResponseInner::Handler(fut, res, disconnect, rx) => {
|
|
||||||
match fut.poll(cx) {
|
match fut.poll(cx) {
|
||||||
Poll::Ready(Ok(handler)) => {
|
Poll::Ready(Ok(handler)) => {
|
||||||
let res = res.take().unwrap();
|
|
||||||
Either::Left(FramedServiceImplResponseInner::Dispatcher(
|
Either::Left(FramedServiceImplResponseInner::Dispatcher(
|
||||||
Dispatcher::new(
|
Dispatcher::new(framed.take().unwrap(), handler, out.take()),
|
||||||
res.framed,
|
|
||||||
res.state,
|
|
||||||
handler,
|
|
||||||
res.sink,
|
|
||||||
rx.take().unwrap(),
|
|
||||||
disconnect.take(),
|
|
||||||
),
|
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
Poll::Pending => Either::Right(Poll::Pending),
|
Poll::Pending => Either::Right(Poll::Pending),
|
||||||
|
@@ -1,45 +0,0 @@
|
|||||||
use std::fmt;
|
|
||||||
use std::rc::Rc;
|
|
||||||
|
|
||||||
use actix_utils::oneshot;
|
|
||||||
use futures::future::{Future, FutureExt};
|
|
||||||
|
|
||||||
use crate::dispatcher::Message;
|
|
||||||
|
|
||||||
pub struct Sink<T>(Rc<dyn Fn(Message<T>)>);
|
|
||||||
|
|
||||||
impl<T> Clone for Sink<T> {
|
|
||||||
fn clone(&self) -> Self {
|
|
||||||
Sink(self.0.clone())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> Sink<T> {
|
|
||||||
pub(crate) fn new(tx: Rc<dyn Fn(Message<T>)>) -> Self {
|
|
||||||
Sink(tx)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Close connection
|
|
||||||
pub fn close(&self) {
|
|
||||||
(self.0)(Message::Close);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Close connection
|
|
||||||
pub fn wait_close(&self) -> impl Future<Output = ()> {
|
|
||||||
let (tx, rx) = oneshot::channel();
|
|
||||||
(self.0)(Message::WaitClose(tx));
|
|
||||||
|
|
||||||
rx.map(|_| ())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Send item
|
|
||||||
pub fn send(&self, item: T) {
|
|
||||||
(self.0)(Message::Item(item));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> fmt::Debug for Sink<T> {
|
|
||||||
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
fmt.debug_struct("Sink").finish()
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,43 +1,49 @@
|
|||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::cell::Cell;
|
||||||
use std::sync::Arc;
|
use std::rc::Rc;
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
use actix_codec::BytesCodec;
|
use actix_codec::BytesCodec;
|
||||||
use actix_rt::time::delay_for;
|
use actix_service::{fn_factory_with_config, fn_service, IntoService, Service};
|
||||||
use actix_service::{fn_service, Service};
|
|
||||||
use actix_testing::TestServer;
|
use actix_testing::TestServer;
|
||||||
|
use actix_utils::mpsc;
|
||||||
|
use bytes::{Bytes, BytesMut};
|
||||||
use futures::future::ok;
|
use futures::future::ok;
|
||||||
|
|
||||||
use actix_ioframe::{Builder, Connect};
|
use actix_ioframe::{Builder, Connect, FactoryBuilder};
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
struct State;
|
struct State(Option<mpsc::Sender<Bytes>>);
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_disconnect() -> std::io::Result<()> {
|
async fn test_basic() {
|
||||||
let disconnect = Arc::new(AtomicBool::new(false));
|
let client_item = Rc::new(Cell::new(false));
|
||||||
let disconnect1 = disconnect.clone();
|
|
||||||
|
|
||||||
let srv = TestServer::with(move || {
|
let srv = TestServer::with(move || {
|
||||||
let disconnect1 = disconnect1.clone();
|
FactoryBuilder::new(fn_service(|conn: Connect<_, _>| {
|
||||||
|
ok(conn.codec(BytesCodec).state(State(None)))
|
||||||
Builder::new()
|
}))
|
||||||
.factory(fn_service(|conn: Connect<_, _>| {
|
// echo
|
||||||
ok(conn.codec(BytesCodec).state(State))
|
.build(fn_service(|t: BytesMut| ok(Some(t.freeze()))))
|
||||||
}))
|
|
||||||
.disconnect(move |_, _| {
|
|
||||||
disconnect1.store(true, Ordering::Relaxed);
|
|
||||||
})
|
|
||||||
.finish(fn_service(|_t| ok(None)))
|
|
||||||
});
|
});
|
||||||
|
|
||||||
let mut client = Builder::new()
|
let item = client_item.clone();
|
||||||
.service(|conn: Connect<_, _>| {
|
let mut client = Builder::new(fn_service(move |conn: Connect<_, _>| {
|
||||||
let conn = conn.codec(BytesCodec).state(State);
|
async move {
|
||||||
conn.sink().close();
|
let (tx, rx) = mpsc::channel();
|
||||||
ok(conn)
|
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(fn_service(|_t| ok(None)));
|
.into_service())
|
||||||
|
}));
|
||||||
|
|
||||||
let conn = actix_connect::default_connector()
|
let conn = actix_connect::default_connector()
|
||||||
.call(actix_connect::Connect::with(String::new(), srv.addr()))
|
.call(actix_connect::Connect::with(String::new(), srv.addr()))
|
||||||
@@ -45,8 +51,5 @@ async fn test_disconnect() -> std::io::Result<()> {
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
client.call(conn.into_parts().0).await.unwrap();
|
client.call(conn.into_parts().0).await.unwrap();
|
||||||
let _ = delay_for(Duration::from_millis(100)).await;
|
assert!(client_item.get());
|
||||||
assert!(disconnect.load(Ordering::Relaxed));
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-macros"
|
name = "actix-macros"
|
||||||
version = "0.1.0"
|
version = "0.1.1"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix runtime macros"
|
description = "Actix runtime macros"
|
||||||
repository = "https://github.com/actix/actix-net"
|
repository = "https://github.com/actix/actix-net"
|
||||||
|
1
actix-macros/LICENSE-APACHE
Symbolic link
1
actix-macros/LICENSE-APACHE
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../LICENSE-APACHE
|
1
actix-macros/LICENSE-MIT
Symbolic link
1
actix-macros/LICENSE-MIT
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../LICENSE-MIT
|
@@ -71,7 +71,7 @@ pub fn test(_: TokenStream, item: TokenStream) -> TokenStream {
|
|||||||
if input.sig.asyncness.is_none() {
|
if input.sig.asyncness.is_none() {
|
||||||
return syn::Error::new_spanned(
|
return syn::Error::new_spanned(
|
||||||
input.sig.fn_token,
|
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()
|
.to_compile_error()
|
||||||
.into();
|
.into();
|
||||||
|
@@ -10,7 +10,6 @@ documentation = "https://docs.rs/actix-rt/"
|
|||||||
categories = ["network-programming", "asynchronous"]
|
categories = ["network-programming", "asynchronous"]
|
||||||
license = "MIT/Apache-2.0"
|
license = "MIT/Apache-2.0"
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
workspace = ".."
|
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
name = "actix_rt"
|
name = "actix_rt"
|
||||||
@@ -21,4 +20,4 @@ actix-macros = "0.1.0"
|
|||||||
actix-threadpool = "0.3"
|
actix-threadpool = "0.3"
|
||||||
futures = "0.3.1"
|
futures = "0.3.1"
|
||||||
copyless = "0.1.4"
|
copyless = "0.1.4"
|
||||||
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"] }
|
||||||
|
@@ -1,5 +1,11 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [1.0.1] - 2019-12-29
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Rename `.start()` method to `.run()`
|
||||||
|
|
||||||
## [1.0.0] - 2019-12-11
|
## [1.0.0] - 2019-12-11
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-server"
|
name = "actix-server"
|
||||||
version = "1.0.0"
|
version = "1.0.1"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix server - General purpose tcp server"
|
description = "Actix server - General purpose tcp server"
|
||||||
keywords = ["network", "framework", "async", "futures"]
|
keywords = ["network", "framework", "async", "futures"]
|
||||||
@@ -21,10 +21,10 @@ path = "src/lib.rs"
|
|||||||
default = []
|
default = []
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-service = "1.0.0"
|
actix-service = "1.0.1"
|
||||||
actix-rt = "1.0.0"
|
actix-rt = "1.0.0"
|
||||||
actix-codec = "0.2.0"
|
actix-codec = "0.2.0"
|
||||||
actix-utils = "1.0.0"
|
actix-utils = "1.0.4"
|
||||||
|
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
num_cpus = "1.11"
|
num_cpus = "1.11"
|
||||||
@@ -38,5 +38,5 @@ mio-uds = { version = "0.6.7" }
|
|||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
bytes = "0.5"
|
bytes = "0.5"
|
||||||
env_logger = "0.6"
|
env_logger = "0.7"
|
||||||
actix-testing = "1.0.0"
|
actix-testing = "1.0.0"
|
@@ -31,7 +31,7 @@ pub struct ServerBuilder {
|
|||||||
backlog: i32,
|
backlog: i32,
|
||||||
workers: Vec<(usize, WorkerClient)>,
|
workers: Vec<(usize, WorkerClient)>,
|
||||||
services: Vec<Box<dyn InternalServiceFactory>>,
|
services: Vec<Box<dyn InternalServiceFactory>>,
|
||||||
sockets: Vec<(Token, StdListener)>,
|
sockets: Vec<(Token, String, StdListener)>,
|
||||||
accept: AcceptLoop,
|
accept: AcceptLoop,
|
||||||
exit: bool,
|
exit: bool,
|
||||||
shutdown_timeout: Duration,
|
shutdown_timeout: Duration,
|
||||||
@@ -146,8 +146,8 @@ impl ServerBuilder {
|
|||||||
let mut srv = ConfiguredService::new(apply);
|
let mut srv = ConfiguredService::new(apply);
|
||||||
for (name, lst) in cfg.services {
|
for (name, lst) in cfg.services {
|
||||||
let token = self.token.next();
|
let token = self.token.next();
|
||||||
srv.stream(token, name, lst.local_addr()?);
|
srv.stream(token, name.clone(), lst.local_addr()?);
|
||||||
self.sockets.push((token, StdListener::Tcp(lst)));
|
self.sockets.push((token, name, StdListener::Tcp(lst)));
|
||||||
}
|
}
|
||||||
self.services.push(Box::new(srv));
|
self.services.push(Box::new(srv));
|
||||||
}
|
}
|
||||||
@@ -172,7 +172,8 @@ impl ServerBuilder {
|
|||||||
factory.clone(),
|
factory.clone(),
|
||||||
lst.local_addr()?,
|
lst.local_addr()?,
|
||||||
));
|
));
|
||||||
self.sockets.push((token, StdListener::Tcp(lst)));
|
self.sockets
|
||||||
|
.push((token, name.as_ref().to_string(), StdListener::Tcp(lst)));
|
||||||
}
|
}
|
||||||
Ok(self)
|
Ok(self)
|
||||||
}
|
}
|
||||||
@@ -222,7 +223,8 @@ impl ServerBuilder {
|
|||||||
factory.clone(),
|
factory.clone(),
|
||||||
addr,
|
addr,
|
||||||
));
|
));
|
||||||
self.sockets.push((token, StdListener::Uds(lst)));
|
self.sockets
|
||||||
|
.push((token, name.as_ref().to_string(), StdListener::Uds(lst)));
|
||||||
Ok(self)
|
Ok(self)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -243,36 +245,18 @@ impl ServerBuilder {
|
|||||||
factory,
|
factory,
|
||||||
lst.local_addr()?,
|
lst.local_addr()?,
|
||||||
));
|
));
|
||||||
self.sockets.push((token, StdListener::Tcp(lst)));
|
self.sockets
|
||||||
|
.push((token, name.as_ref().to_string(), StdListener::Tcp(lst)));
|
||||||
Ok(self)
|
Ok(self)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Spawn new thread and start listening for incoming connections.
|
#[doc(hidden)]
|
||||||
///
|
pub fn start(self) -> Server {
|
||||||
/// This method spawns new thread and starts new actix system. Other than
|
self.run()
|
||||||
/// 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()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Starts processing incoming connections and return server controller.
|
/// 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() {
|
if self.sockets.is_empty() {
|
||||||
panic!("Server should have at least one bound socket");
|
panic!("Server should have at least one bound socket");
|
||||||
} else {
|
} else {
|
||||||
@@ -288,10 +272,15 @@ impl ServerBuilder {
|
|||||||
|
|
||||||
// start accept thread
|
// start accept thread
|
||||||
for sock in &self.sockets {
|
for sock in &self.sockets {
|
||||||
info!("Starting server on {}", sock.1);
|
info!("Starting \"{}\" service on {}", sock.1, sock.2);
|
||||||
}
|
}
|
||||||
self.accept
|
self.accept.start(
|
||||||
.start(mem::replace(&mut self.sockets, Vec::new()), workers);
|
mem::replace(&mut self.sockets, Vec::new())
|
||||||
|
.into_iter()
|
||||||
|
.map(|t| (t.0, t.2))
|
||||||
|
.collect(),
|
||||||
|
workers,
|
||||||
|
);
|
||||||
|
|
||||||
// handle signals
|
// handle signals
|
||||||
if !self.no_signals {
|
if !self.no_signals {
|
||||||
@@ -391,7 +380,7 @@ impl ServerBuilder {
|
|||||||
.await;
|
.await;
|
||||||
System::current().stop();
|
System::current().stop();
|
||||||
}
|
}
|
||||||
.boxed(),
|
.boxed(),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
ready(())
|
ready(())
|
||||||
|
@@ -153,7 +153,7 @@ impl InternalServiceFactory for ConfiguredService {
|
|||||||
}
|
}
|
||||||
return Ok(res);
|
return Ok(res);
|
||||||
}
|
}
|
||||||
.boxed_local()
|
.boxed_local()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -280,6 +280,6 @@ where
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
.boxed_local()
|
.boxed_local()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -217,7 +217,7 @@ impl Worker {
|
|||||||
wrk.await
|
wrk.await
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
.boxed(),
|
.boxed(),
|
||||||
);
|
);
|
||||||
|
|
||||||
WorkerClient::new(idx, tx1, tx2, avail)
|
WorkerClient::new(idx, tx1, tx2, avail)
|
||||||
|
@@ -1,5 +1,19 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [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
|
## [1.0.0] - 2019-12-11
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-service"
|
name = "actix-service"
|
||||||
version = "1.0.0"
|
version = "1.0.2"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix service"
|
description = "Actix service"
|
||||||
keywords = ["network", "framework", "async", "futures"]
|
keywords = ["network", "framework", "async", "futures"]
|
||||||
@@ -10,7 +10,6 @@ documentation = "https://docs.rs/actix-service/"
|
|||||||
categories = ["network-programming", "asynchronous"]
|
categories = ["network-programming", "asynchronous"]
|
||||||
license = "MIT/Apache-2.0"
|
license = "MIT/Apache-2.0"
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
workspace = ".."
|
|
||||||
|
|
||||||
[badges]
|
[badges]
|
||||||
travis-ci = { repository = "actix/actix-service", branch = "master" }
|
travis-ci = { repository = "actix/actix-service", branch = "master" }
|
||||||
|
@@ -351,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 mod dev {
|
||||||
pub use crate::and_then::{AndThenService, AndThenServiceFactory};
|
pub use crate::and_then::{AndThenService, AndThenServiceFactory};
|
||||||
pub use crate::and_then_apply_fn::{AndThenApplyFn, AndThenApplyFnFactory};
|
pub use crate::and_then_apply_fn::{AndThenApplyFn, AndThenApplyFnFactory};
|
||||||
|
@@ -1,28 +1,30 @@
|
|||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
|
|
||||||
use super::ServiceFactory;
|
use super::{IntoServiceFactory, ServiceFactory};
|
||||||
|
|
||||||
/// Adapt external config argument to a config for provided service factory
|
/// Adapt external config argument to a config for provided service factory
|
||||||
///
|
///
|
||||||
/// Note that this function consumes the receiving service factory and returns
|
/// Note that this function consumes the receiving service factory and returns
|
||||||
/// a wrapped version of it.
|
/// a wrapped version of it.
|
||||||
pub fn map_config<T, F, C>(factory: T, f: F) -> MapConfig<T, F, C>
|
pub fn map_config<T, U, F, C>(factory: U, f: F) -> MapConfig<T, F, C>
|
||||||
where
|
where
|
||||||
T: ServiceFactory,
|
T: ServiceFactory,
|
||||||
|
U: IntoServiceFactory<T>,
|
||||||
F: Fn(C) -> T::Config,
|
F: Fn(C) -> T::Config,
|
||||||
{
|
{
|
||||||
MapConfig::new(factory, f)
|
MapConfig::new(factory.into_factory(), f)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Replace config with unit
|
/// 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
|
where
|
||||||
T: ServiceFactory<Config = ()>,
|
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> {
|
pub struct MapConfig<A, F, C> {
|
||||||
a: A,
|
a: A,
|
||||||
f: F,
|
f: F,
|
||||||
|
@@ -1,5 +1,11 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [0.3.1] - 2019-12-12
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Use parking_lot 0.10
|
||||||
|
|
||||||
## [0.3.0] - 2019-12-02
|
## [0.3.0] - 2019-12-02
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-threadpool"
|
name = "actix-threadpool"
|
||||||
version = "0.3.0"
|
version = "0.3.1"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix thread pool for sync code"
|
description = "Actix thread pool for sync code"
|
||||||
keywords = ["actix", "network", "framework", "async", "futures"]
|
keywords = ["actix", "network", "framework", "async", "futures"]
|
||||||
@@ -19,9 +19,9 @@ path = "src/lib.rs"
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
derive_more = "0.99.2"
|
derive_more = "0.99.2"
|
||||||
futures = "0.3.1"
|
futures-channel = "0.3.1"
|
||||||
parking_lot = "0.9"
|
parking_lot = "0.10"
|
||||||
lazy_static = "1.2"
|
lazy_static = "1.3"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
num_cpus = "1.10"
|
num_cpus = "1.10"
|
||||||
threadpool = "1.7"
|
threadpool = "1.7"
|
||||||
|
@@ -6,7 +6,7 @@ use std::pin::Pin;
|
|||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
use derive_more::Display;
|
use derive_more::Display;
|
||||||
use futures::channel::oneshot;
|
use futures_channel::oneshot;
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
use threadpool::ThreadPool;
|
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> {
|
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||||
let rx = Pin::new(&mut self.rx);
|
let rx = Pin::new(&mut self.rx);
|
||||||
let res = futures::ready!(rx.poll(cx))
|
let res = match rx.poll(cx) {
|
||||||
.map_err(|_| BlockingError::Canceled)
|
Poll::Pending => return Poll::Pending,
|
||||||
.and_then(|res| res.map_err(BlockingError::Error));
|
Poll::Ready(res) => res
|
||||||
|
.map_err(|_| BlockingError::Canceled)
|
||||||
|
.and_then(|res| res.map_err(BlockingError::Error)),
|
||||||
|
};
|
||||||
Poll::Ready(res)
|
Poll::Ready(res)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -88,7 +88,7 @@ impl<T: AsyncRead + AsyncWrite + Unpin + 'static> Service for AcceptorService<T>
|
|||||||
let acc = acc;
|
let acc = acc;
|
||||||
tokio_openssl::accept(&acc, req).await
|
tokio_openssl::accept(&acc, req).await
|
||||||
}
|
}
|
||||||
.boxed_local(),
|
.boxed_local(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,5 +1,23 @@
|
|||||||
# Changes
|
# 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
|
## [1.0.2] - 2019-12-11
|
||||||
|
|
||||||
* Allow to create `framed::Dispatcher` with custom `mpsc::Receiver`
|
* Allow to create `framed::Dispatcher` with custom `mpsc::Receiver`
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-utils"
|
name = "actix-utils"
|
||||||
version = "1.0.2"
|
version = "1.0.6"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix utils - various actix net related services"
|
description = "Actix utils - various actix net related services"
|
||||||
keywords = ["network", "framework", "async", "futures"]
|
keywords = ["network", "framework", "async", "futures"]
|
||||||
@@ -10,18 +10,19 @@ documentation = "https://docs.rs/actix-utils/"
|
|||||||
categories = ["network-programming", "asynchronous"]
|
categories = ["network-programming", "asynchronous"]
|
||||||
license = "MIT/Apache-2.0"
|
license = "MIT/Apache-2.0"
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
workspace = ".."
|
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
name = "actix_utils"
|
name = "actix_utils"
|
||||||
path = "src/lib.rs"
|
path = "src/lib.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-service = "1.0.0"
|
actix-service = "1.0.1"
|
||||||
actix-rt = "1.0.0"
|
actix-rt = "1.0.0"
|
||||||
actix-codec = "0.2.0"
|
actix-codec = "0.2.0"
|
||||||
bytes = "0.5.2"
|
bitflags = "1.2"
|
||||||
either = "1.5.2"
|
bytes = "0.5.3"
|
||||||
|
either = "1.5.3"
|
||||||
futures = "0.3.1"
|
futures = "0.3.1"
|
||||||
pin-project = "0.4.6"
|
pin-project = "0.4.6"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
|
slab = "0.4"
|
||||||
|
127
actix-utils/src/condition.rs
Normal file
127
actix-utils/src/condition.rs
Normal 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, ());
|
||||||
|
}
|
||||||
|
}
|
@@ -3,6 +3,7 @@
|
|||||||
#![allow(clippy::type_complexity)]
|
#![allow(clippy::type_complexity)]
|
||||||
|
|
||||||
mod cell;
|
mod cell;
|
||||||
|
pub mod condition;
|
||||||
pub mod counter;
|
pub mod counter;
|
||||||
pub mod either;
|
pub mod either;
|
||||||
pub mod framed;
|
pub mod framed;
|
||||||
|
@@ -4,6 +4,7 @@ use std::pin::Pin;
|
|||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
pub use futures::channel::oneshot::Canceled;
|
pub use futures::channel::oneshot::Canceled;
|
||||||
|
use slab::Slab;
|
||||||
|
|
||||||
use crate::cell::Cell;
|
use crate::cell::Cell;
|
||||||
use crate::task::LocalWaker;
|
use crate::task::LocalWaker;
|
||||||
@@ -21,6 +22,11 @@ pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
|
|||||||
(tx, rx)
|
(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
|
/// Represents the completion half of a oneshot through which the result of a
|
||||||
/// computation is signaled.
|
/// computation is signaled.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
@@ -77,9 +83,7 @@ impl<T> Sender<T> {
|
|||||||
|
|
||||||
impl<T> Drop for Sender<T> {
|
impl<T> Drop for Sender<T> {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
if self.inner.strong_count() == 2 {
|
self.inner.get_ref().rx_task.wake();
|
||||||
self.inner.get_ref().rx_task.wake();
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -104,6 +108,148 @@ impl<T> Future for Receiver<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -135,4 +281,31 @@ mod tests {
|
|||||||
drop(tx);
|
drop(tx);
|
||||||
assert!(rx.await.is_err());
|
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());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@@ -4,12 +4,14 @@ use std::fmt;
|
|||||||
use std::future::Future;
|
use std::future::Future;
|
||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
|
use std::rc::Rc;
|
||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
use actix_service::{IntoService, Service, Transform};
|
use actix_service::{IntoService, Service, Transform};
|
||||||
use futures::future::{ok, Ready};
|
use futures::future::{ok, Ready};
|
||||||
|
|
||||||
use crate::oneshot;
|
use crate::oneshot;
|
||||||
|
use crate::task::LocalWaker;
|
||||||
|
|
||||||
struct Record<I, E> {
|
struct Record<I, E> {
|
||||||
rx: oneshot::Receiver<Result<I, E>>,
|
rx: oneshot::Receiver<Result<I, E>>,
|
||||||
@@ -103,6 +105,7 @@ where
|
|||||||
|
|
||||||
pub struct InOrderService<S: Service> {
|
pub struct InOrderService<S: Service> {
|
||||||
service: S,
|
service: S,
|
||||||
|
waker: Rc<LocalWaker>,
|
||||||
acks: VecDeque<Record<S::Response, S::Error>>,
|
acks: VecDeque<Record<S::Response, S::Error>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -120,6 +123,7 @@ where
|
|||||||
Self {
|
Self {
|
||||||
service: service.into_service(),
|
service: service.into_service(),
|
||||||
acks: VecDeque::new(),
|
acks: VecDeque::new(),
|
||||||
|
waker: Rc::new(LocalWaker::new()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -137,6 +141,9 @@ where
|
|||||||
type Future = InOrderServiceResponse<S>;
|
type Future = InOrderServiceResponse<S>;
|
||||||
|
|
||||||
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||||
|
// poll_ready could be called from different task
|
||||||
|
self.waker.register(cx.waker());
|
||||||
|
|
||||||
// check acks
|
// check acks
|
||||||
while !self.acks.is_empty() {
|
while !self.acks.is_empty() {
|
||||||
let rec = self.acks.front_mut().unwrap();
|
let rec = self.acks.front_mut().unwrap();
|
||||||
@@ -165,9 +172,11 @@ where
|
|||||||
let (tx2, rx2) = oneshot::channel();
|
let (tx2, rx2) = oneshot::channel();
|
||||||
self.acks.push_back(Record { rx: rx1, tx: tx2 });
|
self.acks.push_back(Record { rx: rx1, tx: tx2 });
|
||||||
|
|
||||||
|
let waker = self.waker.clone();
|
||||||
let fut = self.service.call(request);
|
let fut = self.service.call(request);
|
||||||
actix_rt::spawn(async move {
|
actix_rt::spawn(async move {
|
||||||
let res = fut.await;
|
let res = fut.await;
|
||||||
|
waker.wake();
|
||||||
let _ = tx1.send(res);
|
let _ = tx1.send(res);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -202,7 +211,7 @@ mod tests {
|
|||||||
use super::*;
|
use super::*;
|
||||||
use actix_service::Service;
|
use actix_service::Service;
|
||||||
use futures::channel::oneshot;
|
use futures::channel::oneshot;
|
||||||
use futures::future::{lazy, FutureExt, LocalBoxFuture};
|
use futures::future::{lazy, poll_fn, FutureExt, LocalBoxFuture};
|
||||||
|
|
||||||
struct Srv;
|
struct Srv;
|
||||||
|
|
||||||
@@ -236,15 +245,18 @@ mod tests {
|
|||||||
let _ = actix_rt::System::new("test").block_on(async {
|
let _ = actix_rt::System::new("test").block_on(async {
|
||||||
let mut srv = InOrderService::new(Srv);
|
let mut srv = InOrderService::new(Srv);
|
||||||
|
|
||||||
|
let _ = lazy(|cx| srv.poll_ready(cx)).await;
|
||||||
let res1 = srv.call(rx1);
|
let res1 = srv.call(rx1);
|
||||||
let res2 = srv.call(rx2);
|
let res2 = srv.call(rx2);
|
||||||
let res3 = srv.call(rx3);
|
let res3 = srv.call(rx3);
|
||||||
|
|
||||||
let _ = lazy(|cx| srv.poll_ready(cx)).await;
|
actix_rt::spawn(async move {
|
||||||
|
let _ = poll_fn(|cx| {
|
||||||
// dispatcher do this
|
let _ = srv.poll_ready(cx);
|
||||||
actix_rt::time::delay_for(Duration::from_millis(100)).await;
|
Poll::<()>::Pending
|
||||||
let _ = lazy(|cx| srv.poll_ready(cx)).await;
|
})
|
||||||
|
.await;
|
||||||
|
});
|
||||||
|
|
||||||
assert_eq!(res1.await.unwrap(), 1);
|
assert_eq!(res1.await.unwrap(), 1);
|
||||||
assert_eq!(res2.await.unwrap(), 2);
|
assert_eq!(res2.await.unwrap(), 2);
|
||||||
|
@@ -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]
|
#[inline]
|
||||||
/// Registers the waker to be notified on calls to `wake`.
|
/// 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 {
|
unsafe {
|
||||||
*self.waker.get() = Some(waker.clone());
|
let w = self.waker.get();
|
||||||
|
let is_registered = (*w).is_some();
|
||||||
|
*w = Some(waker.clone());
|
||||||
|
is_registered
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -1,5 +1,23 @@
|
|||||||
# Changes
|
# 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
|
## [0.2.0] - 2019-12-07
|
||||||
|
|
||||||
* Update http to 0.2
|
* Update http to 0.2
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-router"
|
name = "actix-router"
|
||||||
version = "0.2.0"
|
version = "0.2.4"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Path router"
|
description = "Path router"
|
||||||
keywords = ["actix"]
|
keywords = ["actix"]
|
||||||
@@ -8,9 +8,7 @@ homepage = "https://actix.rs"
|
|||||||
repository = "https://github.com/actix/actix-net.git"
|
repository = "https://github.com/actix/actix-net.git"
|
||||||
documentation = "https://docs.rs/actix-router/"
|
documentation = "https://docs.rs/actix-router/"
|
||||||
license = "MIT/Apache-2.0"
|
license = "MIT/Apache-2.0"
|
||||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
workspace = ".."
|
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
name = "actix_router"
|
name = "actix_router"
|
||||||
@@ -21,8 +19,8 @@ default = ["http"]
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
regex = "1.3.1"
|
regex = "1.3.1"
|
||||||
serde = "1.0.80"
|
serde = "1.0.104"
|
||||||
bytestring = "0.1.0"
|
bytestring = "0.1.2"
|
||||||
log = "0.4.8"
|
log = "0.4.8"
|
||||||
http = { version="0.2.0", optional=true }
|
http = { version="0.2.0", optional=true }
|
||||||
|
|
||||||
|
@@ -492,7 +492,7 @@ mod tests {
|
|||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct Id {
|
struct Id {
|
||||||
id: String,
|
_id: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize)]
|
||||||
|
@@ -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")]
|
#[cfg(feature = "http")]
|
||||||
mod url;
|
mod url;
|
||||||
|
|
||||||
|
@@ -1,5 +1,4 @@
|
|||||||
use std::ops::Index;
|
use std::ops::Index;
|
||||||
use std::rc::Rc;
|
|
||||||
|
|
||||||
use serde::de;
|
use serde::de;
|
||||||
|
|
||||||
@@ -19,7 +18,7 @@ pub(crate) enum PathItem {
|
|||||||
pub struct Path<T> {
|
pub struct Path<T> {
|
||||||
path: T,
|
path: T,
|
||||||
pub(crate) skip: u16,
|
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> {
|
impl<T: Default> Default for Path<T> {
|
||||||
@@ -96,7 +95,7 @@ impl<T: ResourcePath> Path<T> {
|
|||||||
self.skip += n;
|
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 {
|
match value {
|
||||||
PathItem::Static(s) => self.segments.push((name, PathItem::Static(s))),
|
PathItem::Static(s) => self.segments.push((name, PathItem::Static(s))),
|
||||||
PathItem::Segment(begin, end) => self
|
PathItem::Segment(begin, end) => self
|
||||||
@@ -106,9 +105,8 @@ impl<T: ResourcePath> Path<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
pub fn add_static(&mut self, name: &str, value: &'static str) {
|
pub fn add_static(&mut self, name: &'static str, value: &'static str) {
|
||||||
self.segments
|
self.segments.push((name, PathItem::Static(value)));
|
||||||
.push((Rc::new(name.to_string()), PathItem::Static(value)));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
@@ -126,7 +124,7 @@ impl<T: ResourcePath> Path<T> {
|
|||||||
/// Get matched parameter by name without type conversion
|
/// Get matched parameter by name without type conversion
|
||||||
pub fn get(&self, key: &str) -> Option<&str> {
|
pub fn get(&self, key: &str) -> Option<&str> {
|
||||||
for item in self.segments.iter() {
|
for item in self.segments.iter() {
|
||||||
if key == item.0.as_str() {
|
if key == item.0 {
|
||||||
return match item.1 {
|
return match item.1 {
|
||||||
PathItem::Static(ref s) => Some(&s),
|
PathItem::Static(ref s) => Some(&s),
|
||||||
PathItem::Segment(s, e) => {
|
PathItem::Segment(s, e) => {
|
||||||
|
@@ -1,11 +1,11 @@
|
|||||||
use std::cmp::min;
|
use std::cmp::min;
|
||||||
|
use std::collections::HashMap;
|
||||||
use std::hash::{Hash, Hasher};
|
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::path::{Path, PathItem};
|
||||||
use crate::{Resource, ResourcePath};
|
use crate::{IntoPattern, Resource, ResourcePath};
|
||||||
|
|
||||||
const MAX_DYNAMIC_SEGMENTS: usize = 16;
|
const MAX_DYNAMIC_SEGMENTS: usize = 16;
|
||||||
|
|
||||||
@@ -31,22 +31,56 @@ enum PatternElement {
|
|||||||
enum PatternType {
|
enum PatternType {
|
||||||
Static(String),
|
Static(String),
|
||||||
Prefix(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 {
|
impl ResourceDef {
|
||||||
/// Parse path pattern and create new `Pattern` instance.
|
/// Parse path pattern and create new `Pattern` instance.
|
||||||
///
|
///
|
||||||
/// Panics if path pattern is wrong.
|
/// Panics if path pattern is malformed.
|
||||||
pub fn new(path: &str) -> Self {
|
pub fn new<T: IntoPattern>(path: T) -> Self {
|
||||||
ResourceDef::with_prefix(path, false)
|
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.
|
/// Parse path pattern and create new `Pattern` instance.
|
||||||
///
|
///
|
||||||
/// Use `prefix` type instead of `static`.
|
/// 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 {
|
pub fn prefix(path: &str) -> Self {
|
||||||
ResourceDef::with_prefix(path, true)
|
ResourceDef::with_prefix(path, true)
|
||||||
}
|
}
|
||||||
@@ -57,7 +91,7 @@ impl ResourceDef {
|
|||||||
///
|
///
|
||||||
/// Use `prefix` type instead of `static`.
|
/// 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 {
|
pub fn root_prefix(path: &str) -> Self {
|
||||||
ResourceDef::with_prefix(&insert_slash(path), true)
|
ResourceDef::with_prefix(&insert_slash(path), true)
|
||||||
}
|
}
|
||||||
@@ -85,7 +119,9 @@ impl ResourceDef {
|
|||||||
// actix creates one router per thread
|
// actix creates one router per thread
|
||||||
let names = re
|
let names = re
|
||||||
.capture_names()
|
.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();
|
.collect();
|
||||||
PatternType::Dynamic(re, names, len)
|
PatternType::Dynamic(re, names, len)
|
||||||
} else if for_prefix {
|
} else if for_prefix {
|
||||||
@@ -123,8 +159,9 @@ impl ResourceDef {
|
|||||||
pub fn is_match(&self, path: &str) -> bool {
|
pub fn is_match(&self, path: &str) -> bool {
|
||||||
match self.tp {
|
match self.tp {
|
||||||
PatternType::Static(ref s) => s == path,
|
PatternType::Static(ref s) => s == path,
|
||||||
PatternType::Dynamic(ref re, _, _) => re.is_match(path),
|
|
||||||
PatternType::Prefix(ref s) => path.starts_with(s),
|
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))
|
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
|
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) => {
|
PatternType::Dynamic(ref re, ref names, len) => {
|
||||||
let mut idx = 0;
|
let mut idx = 0;
|
||||||
let mut pos = 0;
|
let mut pos = 0;
|
||||||
@@ -219,24 +299,40 @@ impl ResourceDef {
|
|||||||
path.skip((pos + len) as u16);
|
path.skip((pos + len) as u16);
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
PatternType::Prefix(ref s) => {
|
PatternType::DynamicSet(ref re, ref params) => {
|
||||||
let rpath = path.path();
|
if let Some(idx) = re.matches(path.path()).into_iter().next() {
|
||||||
let len = if s == rpath {
|
let (ref pattern, ref names, len) = params[idx];
|
||||||
s.len()
|
let mut idx = 0;
|
||||||
} else if rpath.starts_with(s)
|
let mut pos = 0;
|
||||||
&& (s.ends_with('/') || rpath.split_at(s.len()).1.starts_with('/'))
|
let mut segments: [PathItem; MAX_DYNAMIC_SEGMENTS] =
|
||||||
{
|
[PathItem::Static(""); MAX_DYNAMIC_SEGMENTS];
|
||||||
if s.ends_with('/') {
|
|
||||||
s.len() - 1
|
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 {
|
} 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 {
|
} else {
|
||||||
return false;
|
false
|
||||||
};
|
}
|
||||||
let rpath_len = rpath.len();
|
|
||||||
path.skip(min(rpath_len, len) as u16);
|
|
||||||
true
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -263,6 +359,30 @@ impl ResourceDef {
|
|||||||
false
|
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) => {
|
PatternType::Dynamic(ref re, ref names, len) => {
|
||||||
let mut idx = 0;
|
let mut idx = 0;
|
||||||
let mut pos = 0;
|
let mut pos = 0;
|
||||||
@@ -298,29 +418,47 @@ impl ResourceDef {
|
|||||||
path.skip((pos + len) as u16);
|
path.skip((pos + len) as u16);
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
PatternType::Prefix(ref s) => {
|
PatternType::DynamicSet(ref re, ref params) => {
|
||||||
let len = {
|
let path = res.resource_path().path();
|
||||||
let rpath = res.resource_path().path();
|
if let Some(idx) = re.matches(path).into_iter().next() {
|
||||||
if s == rpath {
|
let (ref pattern, ref names, len) = params[idx];
|
||||||
s.len()
|
let mut idx = 0;
|
||||||
} else if rpath.starts_with(s)
|
let mut pos = 0;
|
||||||
&& (s.ends_with('/') || rpath.split_at(s.len()).1.starts_with('/'))
|
let mut segments: [PathItem; MAX_DYNAMIC_SEGMENTS] =
|
||||||
{
|
[PathItem::Static(""); MAX_DYNAMIC_SEGMENTS];
|
||||||
if s.ends_with('/') {
|
|
||||||
s.len() - 1
|
if let Some(captures) = pattern.captures(path) {
|
||||||
} else {
|
for (no, name) in names.iter().enumerate() {
|
||||||
s.len()
|
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 {
|
} else {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
};
|
|
||||||
if !check(res, user_data) {
|
if !check(res, user_data) {
|
||||||
return false;
|
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
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -476,7 +652,7 @@ impl<'a> From<&'a str> for ResourceDef {
|
|||||||
|
|
||||||
impl From<String> for ResourceDef {
|
impl From<String> for ResourceDef {
|
||||||
fn from(path: String) -> 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");
|
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]
|
#[test]
|
||||||
fn test_parse_tail() {
|
fn test_parse_tail() {
|
||||||
let re = ResourceDef::new("/user/-{id}*");
|
let re = ResourceDef::new("/user/-{id}*");
|
||||||
@@ -659,4 +894,50 @@ mod tests {
|
|||||||
assert_eq!(&path["name"], "test2");
|
assert_eq!(&path["name"], "test2");
|
||||||
assert_eq!(&path[0], "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/");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,4 +1,4 @@
|
|||||||
use crate::{Resource, ResourceDef, ResourcePath};
|
use crate::{IntoPattern, Resource, ResourceDef, ResourcePath};
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq)]
|
#[derive(Debug, Copy, Clone, PartialEq)]
|
||||||
pub struct ResourceId(pub u16);
|
pub struct ResourceId(pub u16);
|
||||||
@@ -70,7 +70,11 @@ pub struct RouterBuilder<T, U = ()> {
|
|||||||
|
|
||||||
impl<T, U> RouterBuilder<T, U> {
|
impl<T, U> RouterBuilder<T, U> {
|
||||||
/// Register resource for specified path.
|
/// 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
|
self.resources
|
||||||
.push((ResourceDef::new(path), resource, None));
|
.push((ResourceDef::new(path), resource, None));
|
||||||
self.resources.last_mut().unwrap()
|
self.resources.last_mut().unwrap()
|
||||||
|
@@ -1,9 +1,15 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
[0.1.1] - 2019-12-07
|
## [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
|
* Fix hash impl
|
||||||
|
|
||||||
[0.1.0] - 2019-12-07
|
## [0.1.0] - 2019-12-07
|
||||||
|
|
||||||
* Initial release
|
* Initial release
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "bytestring"
|
name = "bytestring"
|
||||||
version = "0.1.1"
|
version = "0.1.2"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "A UTF-8 encoded string with Bytes as a storage"
|
description = "A UTF-8 encoded string with Bytes as a storage"
|
||||||
keywords = ["actix"]
|
keywords = ["actix"]
|
||||||
@@ -9,11 +9,10 @@ repository = "https://github.com/actix/actix-net.git"
|
|||||||
documentation = "https://docs.rs/bytestring/"
|
documentation = "https://docs.rs/bytestring/"
|
||||||
license = "MIT/Apache-2.0"
|
license = "MIT/Apache-2.0"
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
workspace = ".."
|
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
name = "bytestring"
|
name = "bytestring"
|
||||||
path = "src/lib.rs"
|
path = "src/lib.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
bytes = "0.5.2"
|
bytes = "0.5.3"
|
||||||
|
@@ -6,14 +6,14 @@ use bytes::Bytes;
|
|||||||
|
|
||||||
/// A utf-8 encoded string with [`Bytes`] as a storage.
|
/// A utf-8 encoded string with [`Bytes`] as a storage.
|
||||||
///
|
///
|
||||||
/// [`Bytes`]: https://docs.rs/bytes/0.5.2/bytes/struct.Bytes.html
|
/// [`Bytes`]: https://docs.rs/bytes/0.5.3/bytes/struct.Bytes.html
|
||||||
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Default)]
|
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Default)]
|
||||||
pub struct ByteString(Bytes);
|
pub struct ByteString(Bytes);
|
||||||
|
|
||||||
impl ByteString {
|
impl ByteString {
|
||||||
/// Creates a new `ByteString`.
|
/// Creates a new `ByteString`.
|
||||||
pub fn new() -> String {
|
pub fn new() -> Self {
|
||||||
String::default()
|
ByteString(Bytes::new())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get a reference to the underlying bytes object.
|
/// Get a reference to the underlying bytes object.
|
||||||
@@ -27,12 +27,12 @@ impl ByteString {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Creates a new `ByteString` from a static str.
|
/// Creates a new `ByteString` from a static str.
|
||||||
pub fn from_static(src: &'static str) -> ByteString {
|
pub const fn from_static(src: &'static str) -> ByteString {
|
||||||
Self(Bytes::from_static(src.as_ref()))
|
Self(Bytes::from_static(src.as_bytes()))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Creates a new `ByteString` from a 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)
|
Self(src)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -147,6 +147,11 @@ mod test {
|
|||||||
use std::collections::hash_map::DefaultHasher;
|
use std::collections::hash_map::DefaultHasher;
|
||||||
use std::hash::{Hash, Hasher};
|
use std::hash::{Hash, Hasher};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_new() {
|
||||||
|
let _: ByteString = ByteString::new();
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_hash() {
|
fn test_hash() {
|
||||||
let mut hasher1 = DefaultHasher::default();
|
let mut hasher1 = DefaultHasher::default();
|
||||||
@@ -171,6 +176,7 @@ mod test {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_from_static_str() {
|
fn test_from_static_str() {
|
||||||
|
const _S: ByteString = ByteString::from_static("hello");
|
||||||
let _ = ByteString::from_static("str");
|
let _ = ByteString::from_static("str");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user