mirror of
https://github.com/fafhrd91/actix-net
synced 2025-08-18 17:25:32 +02:00
Compare commits
2 Commits
rt-v2.2.0
...
remove-mps
Author | SHA1 | Date | |
---|---|---|---|
|
45e3a5c0e6 | ||
|
564acfbf3a |
60
.github/workflows/ci.yml
vendored
60
.github/workflows/ci.yml
vendored
@@ -25,9 +25,6 @@ jobs:
|
|||||||
name: ${{ matrix.target.name }} / ${{ matrix.version }}
|
name: ${{ matrix.target.name }} / ${{ matrix.version }}
|
||||||
runs-on: ${{ matrix.target.os }}
|
runs-on: ${{ matrix.target.os }}
|
||||||
|
|
||||||
env:
|
|
||||||
VCPKGRS_DYNAMIC: 1
|
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Setup Routing
|
- name: Setup Routing
|
||||||
if: matrix.target.os == 'macos-latest'
|
if: matrix.target.os == 'macos-latest'
|
||||||
@@ -35,17 +32,6 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
|
|
||||||
# install OpenSSL on Windows
|
|
||||||
- name: Set vcpkg root
|
|
||||||
if: matrix.target.triple == 'x86_64-pc-windows-msvc' || matrix.target.triple == 'i686-pc-windows-msvc'
|
|
||||||
run: echo "VCPKG_ROOT=$env:VCPKG_INSTALLATION_ROOT" | Out-File -FilePath $env:GITHUB_ENV -Append
|
|
||||||
- name: Install OpenSSL
|
|
||||||
if: matrix.target.triple == 'x86_64-pc-windows-msvc'
|
|
||||||
run: vcpkg install openssl:x64-windows
|
|
||||||
- name: Install OpenSSL
|
|
||||||
if: matrix.target.triple == 'i686-pc-windows-msvc'
|
|
||||||
run: vcpkg install openssl:x86-windows
|
|
||||||
|
|
||||||
- name: Install ${{ matrix.version }}
|
- name: Install ${{ matrix.version }}
|
||||||
uses: actions-rs/toolchain@v1
|
uses: actions-rs/toolchain@v1
|
||||||
with:
|
with:
|
||||||
@@ -53,21 +39,21 @@ jobs:
|
|||||||
profile: minimal
|
profile: minimal
|
||||||
override: true
|
override: true
|
||||||
|
|
||||||
# - name: Install MSYS2
|
- name: Install MSYS2
|
||||||
# if: matrix.target.triple == 'x86_64-pc-windows-gnu'
|
if: matrix.target.triple == 'x86_64-pc-windows-gnu'
|
||||||
# uses: msys2/setup-msys2@v2
|
uses: msys2/setup-msys2@v2
|
||||||
# - name: Install MinGW Packages
|
- name: Install MinGW Packages
|
||||||
# if: matrix.target.triple == 'x86_64-pc-windows-gnu'
|
if: matrix.target.triple == 'x86_64-pc-windows-gnu'
|
||||||
# run: |
|
run: |
|
||||||
# msys2 -c 'pacman -Sy --noconfirm pacman'
|
msys2 -c 'pacman -Sy --noconfirm pacman'
|
||||||
# msys2 -c 'pacman --noconfirm -S base-devel pkg-config'
|
msys2 -c 'pacman --noconfirm -S base-devel pkg-config'
|
||||||
|
|
||||||
# - name: Generate Cargo.lock
|
- name: Generate Cargo.lock
|
||||||
# uses: actions-rs/cargo@v1
|
uses: actions-rs/cargo@v1
|
||||||
# with:
|
with:
|
||||||
# command: generate-lockfile
|
command: generate-lockfile
|
||||||
# - name: Cache Dependencies
|
- name: Cache Dependencies
|
||||||
# uses: Swatinem/rust-cache@v1.2.0
|
uses: Swatinem/rust-cache@v1.2.0
|
||||||
|
|
||||||
- name: Install cargo-hack
|
- name: Install cargo-hack
|
||||||
uses: actions-rs/cargo@v1
|
uses: actions-rs/cargo@v1
|
||||||
@@ -79,27 +65,13 @@ jobs:
|
|||||||
uses: actions-rs/cargo@v1
|
uses: actions-rs/cargo@v1
|
||||||
with:
|
with:
|
||||||
command: hack
|
command: hack
|
||||||
args: check --workspace --no-default-features
|
args: --clean-per-run check --workspace --no-default-features --tests
|
||||||
|
|
||||||
- name: check minimal + tests
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: hack
|
|
||||||
args: check --workspace --no-default-features --tests --examples
|
|
||||||
|
|
||||||
- name: check default
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: check
|
|
||||||
args: --workspace --tests --examples
|
|
||||||
|
|
||||||
- name: check full
|
- name: check full
|
||||||
# TODO: compile OpenSSL and run tests on MinGW
|
|
||||||
if: matrix.target.triple != 'x86_64-pc-windows-gnu'
|
|
||||||
uses: actions-rs/cargo@v1
|
uses: actions-rs/cargo@v1
|
||||||
with:
|
with:
|
||||||
command: check
|
command: check
|
||||||
args: --workspace --all-features --tests --examples
|
args: --workspace --bins --examples --tests
|
||||||
|
|
||||||
- name: tests
|
- name: tests
|
||||||
if: matrix.target.triple != 'x86_64-pc-windows-gnu'
|
if: matrix.target.triple != 'x86_64-pc-windows-gnu'
|
||||||
|
@@ -235,7 +235,7 @@ impl<T, U> Framed<T, U> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Flush write buffer to underlying I/O stream.
|
/// Flush write buffer to underlying I/O stream.
|
||||||
pub fn flush<I>(
|
pub fn poll_flush<I>(
|
||||||
mut self: Pin<&mut Self>,
|
mut self: Pin<&mut Self>,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Poll<Result<(), U::Error>>
|
) -> Poll<Result<(), U::Error>>
|
||||||
@@ -271,7 +271,7 @@ impl<T, U> Framed<T, U> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Flush write buffer and shutdown underlying I/O stream.
|
/// Flush write buffer and shutdown underlying I/O stream.
|
||||||
pub fn close<I>(
|
pub fn poll_close<I>(
|
||||||
mut self: Pin<&mut Self>,
|
mut self: Pin<&mut Self>,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Poll<Result<(), U::Error>>
|
) -> Poll<Result<(), U::Error>>
|
||||||
@@ -319,11 +319,11 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||||
self.flush(cx)
|
self.poll_flush(cx)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||||
self.close(cx)
|
self.poll_close(cx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -170,11 +170,13 @@ impl Quoter {
|
|||||||
idx += 1;
|
idx += 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
cloned.map(|data| {
|
if let Some(data) = cloned {
|
||||||
// SAFETY: we get data from http::Uri, which does UTF-8 checks already
|
// Unsafe: we get data from http::Uri, which does utf-8 checks already
|
||||||
// this code only decodes valid pct encoded values
|
// this code only decodes valid pct encoded values
|
||||||
unsafe { String::from_utf8_unchecked(data) }
|
Some(unsafe { String::from_utf8_unchecked(data) })
|
||||||
})
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -1,17 +1,6 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
## Unreleased - 2021-xx-xx
|
## Unreleased - 2021-xx-xx
|
||||||
|
|
||||||
|
|
||||||
## 2.2.0 - 2021-03-29
|
|
||||||
* **BREAKING** `ActixStream::{poll_read_ready, poll_write_ready}` methods now return
|
|
||||||
`Ready` object in ok variant. [#293]
|
|
||||||
* Breakage is acceptable since `ActixStream` was not intended to be public.
|
|
||||||
|
|
||||||
[#293] https://github.com/actix/actix-net/pull/293
|
|
||||||
|
|
||||||
|
|
||||||
## 2.1.0 - 2021-02-24
|
|
||||||
* Add `ActixStream` extension trait to include readiness methods. [#276]
|
* Add `ActixStream` extension trait to include readiness methods. [#276]
|
||||||
* Re-export `tokio::net::TcpSocket` in `net` module [#282]
|
* Re-export `tokio::net::TcpSocket` in `net` module [#282]
|
||||||
|
|
||||||
@@ -72,7 +61,10 @@
|
|||||||
|
|
||||||
|
|
||||||
## 2.0.0-beta.1 - 2020-12-28
|
## 2.0.0-beta.1 - 2020-12-28
|
||||||
|
### Added
|
||||||
* Add `System::attach_to_tokio` method. [#173]
|
* Add `System::attach_to_tokio` method. [#173]
|
||||||
|
|
||||||
|
### Changed
|
||||||
* Update `tokio` dependency to `1.0`. [#236]
|
* Update `tokio` dependency to `1.0`. [#236]
|
||||||
* Rename `time` module `delay_for` to `sleep`, `delay_until` to `sleep_until`, `Delay` to `Sleep`
|
* Rename `time` module `delay_for` to `sleep`, `delay_until` to `sleep_until`, `Delay` to `Sleep`
|
||||||
to stay aligned with Tokio's naming. [#236]
|
to stay aligned with Tokio's naming. [#236]
|
||||||
@@ -80,19 +72,27 @@
|
|||||||
* These methods now accept `&self` when calling. [#236]
|
* These methods now accept `&self` when calling. [#236]
|
||||||
* Remove `'static` lifetime requirement for `System::run` and `Builder::run`. [#236]
|
* Remove `'static` lifetime requirement for `System::run` and `Builder::run`. [#236]
|
||||||
* `Arbiter::spawn` now panics when `System` is not in scope. [#207]
|
* `Arbiter::spawn` now panics when `System` is not in scope. [#207]
|
||||||
|
|
||||||
|
### Fixed
|
||||||
* Fix work load issue by removing `PENDING` thread local. [#207]
|
* Fix work load issue by removing `PENDING` thread local. [#207]
|
||||||
|
|
||||||
[#207]: https://github.com/actix/actix-net/pull/207
|
[#207]: https://github.com/actix/actix-net/pull/207
|
||||||
[#236]: https://github.com/actix/actix-net/pull/236
|
[#236]: https://github.com/actix/actix-net/pull/236
|
||||||
|
|
||||||
|
## [1.1.1] - 2020-04-30
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
## 1.1.1 - 2020-04-30
|
|
||||||
* Fix memory leak due to [#94] (see [#129] for more detail)
|
* Fix memory leak due to [#94] (see [#129] for more detail)
|
||||||
|
|
||||||
[#129]: https://github.com/actix/actix-net/issues/129
|
[#129]: https://github.com/actix/actix-net/issues/129
|
||||||
|
|
||||||
|
## [1.1.0] - 2020-04-08
|
||||||
|
|
||||||
|
**This version has been yanked.**
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
## 1.1.0 - 2020-04-08 (YANKED)
|
|
||||||
* Expose `System::is_set` to check if current system has ben started [#99]
|
* Expose `System::is_set` to check if current system has ben started [#99]
|
||||||
* Add `Arbiter::is_running` to check if event loop is running [#124]
|
* Add `Arbiter::is_running` to check if event loop is running [#124]
|
||||||
* Add `Arbiter::local_join` associated function
|
* Add `Arbiter::local_join` associated function
|
||||||
@@ -102,57 +102,96 @@
|
|||||||
[#99]: https://github.com/actix/actix-net/pull/99
|
[#99]: https://github.com/actix/actix-net/pull/99
|
||||||
[#124]: https://github.com/actix/actix-net/pull/124
|
[#124]: https://github.com/actix/actix-net/pull/124
|
||||||
|
|
||||||
|
## [1.0.0] - 2019-12-11
|
||||||
|
|
||||||
## 1.0.0 - 2019-12-11
|
|
||||||
* Update dependencies
|
* Update dependencies
|
||||||
|
|
||||||
|
## [1.0.0-alpha.3] - 2019-12-07
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
## 1.0.0-alpha.3 - 2019-12-07
|
|
||||||
* Migrate to tokio 0.2
|
|
||||||
* Fix compilation on non-unix platforms
|
* Fix compilation on non-unix platforms
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Migrate to tokio 0.2
|
||||||
|
|
||||||
|
|
||||||
|
## [1.0.0-alpha.2] - 2019-12-02
|
||||||
|
|
||||||
|
Added
|
||||||
|
|
||||||
## 1.0.0-alpha.2 - 2019-12-02
|
|
||||||
* Export `main` and `test` attribute macros
|
* Export `main` and `test` attribute macros
|
||||||
|
|
||||||
* Export `time` module (re-export of tokio-timer)
|
* Export `time` module (re-export of tokio-timer)
|
||||||
|
|
||||||
* Export `net` module (re-export of tokio-net)
|
* Export `net` module (re-export of tokio-net)
|
||||||
|
|
||||||
|
|
||||||
## 1.0.0-alpha.1 - 2019-11-22
|
## [1.0.0-alpha.1] - 2019-11-22
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
* Migrate to std::future and tokio 0.2
|
* Migrate to std::future and tokio 0.2
|
||||||
|
|
||||||
|
|
||||||
## 0.2.6 - 2019-11-14
|
## [0.2.6] - 2019-11-14
|
||||||
* Allow to join arbiter's thread. #60
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
* Fix arbiter's thread panic message.
|
* Fix arbiter's thread panic message.
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
* Allow to join arbiter's thread. #60
|
||||||
|
|
||||||
|
|
||||||
|
## [0.2.5] - 2019-09-02
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
## 0.2.5 - 2019-09-02
|
|
||||||
* Add arbiter specific storage
|
* Add arbiter specific storage
|
||||||
|
|
||||||
|
|
||||||
## 0.2.4 - 2019-07-17
|
## [0.2.4] - 2019-07-17
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
* Avoid a copy of the Future when initializing the Box. #29
|
* Avoid a copy of the Future when initializing the Box. #29
|
||||||
|
|
||||||
|
|
||||||
## 0.2.3 - 2019-06-22
|
## [0.2.3] - 2019-06-22
|
||||||
* Allow to start System using existing CurrentThread Handle #22
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
* Allow to start System using exsiting CurrentThread Handle #22
|
||||||
|
|
||||||
|
|
||||||
## 0.2.2 - 2019-03-28
|
## [0.2.2] - 2019-03-28
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
* Moved `blocking` module to `actix-threadpool` crate
|
* Moved `blocking` module to `actix-threadpool` crate
|
||||||
|
|
||||||
|
|
||||||
## 0.2.1 - 2019-03-11
|
## [0.2.1] - 2019-03-11
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
* Added `blocking` module
|
* Added `blocking` module
|
||||||
* Added `Arbiter::exec_fn` - execute fn on the arbiter's thread
|
|
||||||
* Added `Arbiter::exec` - execute fn on the arbiter's thread and wait result
|
* Arbiter::exec_fn - execute fn on the arbiter's thread
|
||||||
|
|
||||||
|
* Arbiter::exec - execute fn on the arbiter's thread and wait result
|
||||||
|
|
||||||
|
|
||||||
## 0.2.0 - 2019-03-06
|
## [0.2.0] - 2019-03-06
|
||||||
|
|
||||||
* `run` method returns `io::Result<()>`
|
* `run` method returns `io::Result<()>`
|
||||||
|
|
||||||
* Removed `Handle`
|
* Removed `Handle`
|
||||||
|
|
||||||
|
|
||||||
## 0.1.0 - 2018-12-09
|
## [0.1.0] - 2018-12-09
|
||||||
|
|
||||||
* Initial release
|
* Initial release
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-rt"
|
name = "actix-rt"
|
||||||
version = "2.2.0"
|
version = "2.0.2"
|
||||||
authors = [
|
authors = [
|
||||||
"Nikolay Kim <fafhrd91@gmail.com>",
|
"Nikolay Kim <fafhrd91@gmail.com>",
|
||||||
"Rob Ede <robjtede@icloud.com>",
|
"Rob Ede <robjtede@icloud.com>",
|
||||||
@@ -8,7 +8,7 @@ authors = [
|
|||||||
description = "Tokio-based single-threaded async runtime for the Actix ecosystem"
|
description = "Tokio-based single-threaded async runtime for the Actix ecosystem"
|
||||||
keywords = ["async", "futures", "io", "runtime"]
|
keywords = ["async", "futures", "io", "runtime"]
|
||||||
homepage = "https://actix.rs"
|
homepage = "https://actix.rs"
|
||||||
repository = "https://github.com/actix/actix-net"
|
repository = "https://github.com/actix/actix-net.git"
|
||||||
documentation = "https://docs.rs/actix-rt"
|
documentation = "https://docs.rs/actix-rt"
|
||||||
categories = ["network-programming", "asynchronous"]
|
categories = ["network-programming", "asynchronous"]
|
||||||
license = "MIT OR Apache-2.0"
|
license = "MIT OR Apache-2.0"
|
||||||
@@ -26,7 +26,7 @@ macros = ["actix-macros"]
|
|||||||
actix-macros = { version = "0.2.0", optional = true }
|
actix-macros = { version = "0.2.0", optional = true }
|
||||||
|
|
||||||
futures-core = { version = "0.3", default-features = false }
|
futures-core = { version = "0.3", default-features = false }
|
||||||
tokio = { version = "1.3", features = ["rt", "net", "parking_lot", "signal", "sync", "time"] }
|
tokio = { version = "1.2", features = ["rt", "net", "parking_lot", "signal", "sync", "time"] }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
tokio = { version = "1.2", features = ["full"] }
|
tokio = { version = "1.2", features = ["full"] }
|
||||||
|
@@ -2,13 +2,4 @@
|
|||||||
|
|
||||||
> Tokio-based single-threaded async runtime for the Actix ecosystem.
|
> Tokio-based single-threaded async runtime for the Actix ecosystem.
|
||||||
|
|
||||||
[](https://crates.io/crates/actix-rt)
|
|
||||||
[](https://docs.rs/actix-rt/2.2.0)
|
|
||||||
[](https://blog.rust-lang.org/2020/03/12/Rust-1.46.html)
|
|
||||||

|
|
||||||
<br />
|
|
||||||
[](https://deps.rs/crate/actix-rt/2.2.0)
|
|
||||||

|
|
||||||
[](https://discord.gg/WghFtEH6Hb)
|
|
||||||
|
|
||||||
See crate documentation for more: https://docs.rs/actix-rt.
|
See crate documentation for more: https://docs.rs/actix-rt.
|
||||||
|
@@ -1,60 +0,0 @@
|
|||||||
//! An example on how to build a multi-thread tokio runtime for Actix System.
|
|
||||||
//! Then spawn async task that can make use of work stealing of tokio runtime.
|
|
||||||
|
|
||||||
use actix_rt::System;
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
System::with_tokio_rt(|| {
|
|
||||||
// build system with a multi-thread tokio runtime.
|
|
||||||
tokio::runtime::Builder::new_multi_thread()
|
|
||||||
.worker_threads(2)
|
|
||||||
.enable_all()
|
|
||||||
.build()
|
|
||||||
.unwrap()
|
|
||||||
})
|
|
||||||
.block_on(async_main());
|
|
||||||
}
|
|
||||||
|
|
||||||
// async main function that acts like #[actix_web::main] or #[tokio::main]
|
|
||||||
async fn async_main() {
|
|
||||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
|
||||||
|
|
||||||
// get a handle to system arbiter and spawn async task on it
|
|
||||||
System::current().arbiter().spawn(async {
|
|
||||||
// use tokio::spawn to get inside the context of multi thread tokio runtime
|
|
||||||
let h1 = tokio::spawn(async {
|
|
||||||
println!("thread id is {:?}", std::thread::current().id());
|
|
||||||
std::thread::sleep(std::time::Duration::from_secs(2));
|
|
||||||
});
|
|
||||||
|
|
||||||
// work stealing occurs for this task spawn
|
|
||||||
let h2 = tokio::spawn(async {
|
|
||||||
println!("thread id is {:?}", std::thread::current().id());
|
|
||||||
});
|
|
||||||
|
|
||||||
h1.await.unwrap();
|
|
||||||
h2.await.unwrap();
|
|
||||||
let _ = tx.send(());
|
|
||||||
});
|
|
||||||
|
|
||||||
rx.await.unwrap();
|
|
||||||
|
|
||||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
|
||||||
let now = std::time::Instant::now();
|
|
||||||
|
|
||||||
// without additional tokio::spawn, all spawned tasks run on single thread
|
|
||||||
System::current().arbiter().spawn(async {
|
|
||||||
println!("thread id is {:?}", std::thread::current().id());
|
|
||||||
std::thread::sleep(std::time::Duration::from_secs(2));
|
|
||||||
let _ = tx.send(());
|
|
||||||
});
|
|
||||||
|
|
||||||
// previous spawn task has blocked the system arbiter thread
|
|
||||||
// so this task will wait for 2 seconds until it can be run
|
|
||||||
System::current().arbiter().spawn(async move {
|
|
||||||
println!("thread id is {:?}", std::thread::current().id());
|
|
||||||
assert!(now.elapsed() > std::time::Duration::from_secs(2));
|
|
||||||
});
|
|
||||||
|
|
||||||
rx.await.unwrap();
|
|
||||||
}
|
|
@@ -72,14 +72,9 @@ pub mod signal {
|
|||||||
pub mod net {
|
pub mod net {
|
||||||
//! TCP/UDP/Unix bindings (mostly Tokio re-exports).
|
//! TCP/UDP/Unix bindings (mostly Tokio re-exports).
|
||||||
|
|
||||||
use std::{
|
use std::task::{Context, Poll};
|
||||||
future::Future,
|
|
||||||
io,
|
|
||||||
task::{Context, Poll},
|
|
||||||
};
|
|
||||||
|
|
||||||
pub use tokio::io::Ready;
|
use tokio::io::{AsyncRead, AsyncWrite};
|
||||||
use tokio::io::{AsyncRead, AsyncWrite, Interest};
|
|
||||||
pub use tokio::net::UdpSocket;
|
pub use tokio::net::UdpSocket;
|
||||||
pub use tokio::net::{TcpListener, TcpSocket, TcpStream};
|
pub use tokio::net::{TcpListener, TcpSocket, TcpStream};
|
||||||
|
|
||||||
@@ -87,55 +82,36 @@ pub mod net {
|
|||||||
pub use tokio::net::{UnixDatagram, UnixListener, UnixStream};
|
pub use tokio::net::{UnixDatagram, UnixListener, UnixStream};
|
||||||
|
|
||||||
/// Extension trait over async read+write types that can also signal readiness.
|
/// Extension trait over async read+write types that can also signal readiness.
|
||||||
#[doc(hidden)]
|
pub trait ActixStream: AsyncRead + AsyncWrite + Unpin + 'static {
|
||||||
pub trait ActixStream: AsyncRead + AsyncWrite + Unpin {
|
|
||||||
/// Poll stream and check read readiness of Self.
|
/// Poll stream and check read readiness of Self.
|
||||||
///
|
///
|
||||||
/// See [tokio::net::TcpStream::poll_read_ready] for detail on intended use.
|
/// See [tokio::net::TcpStream::poll_read_ready] for detail on intended use.
|
||||||
fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>>;
|
fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<std::io::Result<()>>;
|
||||||
|
|
||||||
/// Poll stream and check write readiness of Self.
|
/// Poll stream and check write readiness of Self.
|
||||||
///
|
///
|
||||||
/// See [tokio::net::TcpStream::poll_write_ready] for detail on intended use.
|
/// See [tokio::net::TcpStream::poll_write_ready] for detail on intended use.
|
||||||
fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>>;
|
fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<std::io::Result<()>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ActixStream for TcpStream {
|
impl ActixStream for TcpStream {
|
||||||
fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
|
fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||||
let ready = self.ready(Interest::READABLE);
|
TcpStream::poll_read_ready(self, cx)
|
||||||
tokio::pin!(ready);
|
|
||||||
ready.poll(cx)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
|
fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||||
let ready = self.ready(Interest::WRITABLE);
|
TcpStream::poll_write_ready(self, cx)
|
||||||
tokio::pin!(ready);
|
|
||||||
ready.poll(cx)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
impl ActixStream for UnixStream {
|
impl ActixStream for UnixStream {
|
||||||
fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
|
fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||||
let ready = self.ready(Interest::READABLE);
|
UnixStream::poll_read_ready(self, cx)
|
||||||
tokio::pin!(ready);
|
|
||||||
ready.poll(cx)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
|
fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||||
let ready = self.ready(Interest::WRITABLE);
|
UnixStream::poll_write_ready(self, cx)
|
||||||
tokio::pin!(ready);
|
|
||||||
ready.poll(cx)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<Io: ActixStream + ?Sized> ActixStream for Box<Io> {
|
|
||||||
fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
|
|
||||||
(**self).poll_read_ready(cx)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
|
|
||||||
(**self).poll_write_ready(cx)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,9 +1,6 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
## Unreleased - 2021-xx-xx
|
## Unreleased - 2021-xx-xx
|
||||||
* Prevent panic when shutdown_timeout is very large. [f9262db]
|
|
||||||
|
|
||||||
[f9262db]: https://github.com/actix/actix-net/commit/f9262db
|
|
||||||
|
|
||||||
|
|
||||||
## 2.0.0-beta.3 - 2021-02-06
|
## 2.0.0-beta.3 - 2021-02-06
|
||||||
|
@@ -24,7 +24,7 @@ default = []
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
actix-codec = "0.4.0-beta.1"
|
actix-codec = "0.4.0-beta.1"
|
||||||
actix-rt = { version = "2.0.0", default-features = false }
|
actix-rt = { version = "2.0.0", default-features = false }
|
||||||
actix-service = "2.0.0-beta.5"
|
actix-service = "2.0.0-beta.4"
|
||||||
actix-utils = "3.0.0-beta.2"
|
actix-utils = "3.0.0-beta.2"
|
||||||
|
|
||||||
futures-core = { version = "0.3.7", default-features = false, features = ["alloc"] }
|
futures-core = { version = "0.3.7", default-features = false, features = ["alloc"] }
|
||||||
|
@@ -2,7 +2,7 @@ use std::time::Duration;
|
|||||||
use std::{io, thread};
|
use std::{io, thread};
|
||||||
|
|
||||||
use actix_rt::{
|
use actix_rt::{
|
||||||
time::{sleep, Instant},
|
time::{sleep_until, Instant},
|
||||||
System,
|
System,
|
||||||
};
|
};
|
||||||
use log::{error, info};
|
use log::{error, info};
|
||||||
@@ -16,17 +16,14 @@ use crate::worker::{Conn, WorkerHandle};
|
|||||||
use crate::Token;
|
use crate::Token;
|
||||||
|
|
||||||
struct ServerSocketInfo {
|
struct ServerSocketInfo {
|
||||||
/// Address of socket. Mainly used for logging.
|
// addr for socket. mainly used for logging.
|
||||||
addr: SocketAddr,
|
addr: SocketAddr,
|
||||||
|
// be ware this is the crate token for identify socket and should not be confused with
|
||||||
/// Beware this is the crate token for identify socket and should not be confused
|
// mio::Token
|
||||||
/// with `mio::Token`.
|
|
||||||
token: Token,
|
token: Token,
|
||||||
|
|
||||||
lst: MioListener,
|
lst: MioListener,
|
||||||
|
// timeout is used to mark the deadline when this socket's listener should be registered again
|
||||||
/// Timeout is used to mark the deadline when this socket's listener should be registered again
|
// after an error.
|
||||||
/// after an error.
|
|
||||||
timeout: Option<Instant>,
|
timeout: Option<Instant>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -229,9 +226,10 @@ impl Accept {
|
|||||||
Some(WakerInterest::Stop) => {
|
Some(WakerInterest::Stop) => {
|
||||||
return self.deregister_all(&mut sockets);
|
return self.deregister_all(&mut sockets);
|
||||||
}
|
}
|
||||||
// waker queue is drained
|
// waker queue is drained.
|
||||||
None => {
|
None => {
|
||||||
// Reset the WakerQueue before break so it does not grow infinitely
|
// Reset the WakerQueue before break so it does not grow
|
||||||
|
// infinitely.
|
||||||
WakerQueue::reset(&mut guard);
|
WakerQueue::reset(&mut guard);
|
||||||
break 'waker;
|
break 'waker;
|
||||||
}
|
}
|
||||||
@@ -330,8 +328,8 @@ impl Accept {
|
|||||||
}
|
}
|
||||||
Err(tmp) => {
|
Err(tmp) => {
|
||||||
// worker lost contact and could be gone. a message is sent to
|
// worker lost contact and could be gone. a message is sent to
|
||||||
// `ServerBuilder` future to notify it a new worker should be made
|
// `ServerBuilder` future to notify it a new worker should be made.
|
||||||
// after that remove the fault worker
|
// after that remove the fault worker.
|
||||||
self.srv.worker_faulted(self.handles[self.next].idx);
|
self.srv.worker_faulted(self.handles[self.next].idx);
|
||||||
msg = tmp;
|
msg = tmp;
|
||||||
self.handles.swap_remove(self.next);
|
self.handles.swap_remove(self.next);
|
||||||
@@ -405,15 +403,15 @@ impl Accept {
|
|||||||
error!("Can not deregister server socket {}", err);
|
error!("Can not deregister server socket {}", err);
|
||||||
}
|
}
|
||||||
|
|
||||||
// sleep after error. write the timeout to socket info as later
|
// sleep after error. write the timeout to socket info as later the poll
|
||||||
// the poll would need it mark which socket and when it's
|
// would need it mark which socket and when it's listener should be
|
||||||
// listener should be registered
|
// registered.
|
||||||
info.timeout = Some(Instant::now() + Duration::from_millis(500));
|
info.timeout = Some(Instant::now() + Duration::from_millis(500));
|
||||||
|
|
||||||
// after the sleep a Timer interest is sent to Accept Poll
|
// after the sleep a Timer interest is sent to Accept Poll
|
||||||
let waker = self.waker.clone();
|
let waker = self.waker.clone();
|
||||||
System::current().arbiter().spawn(async move {
|
System::current().arbiter().spawn(async move {
|
||||||
sleep(Duration::from_millis(510)).await;
|
sleep_until(Instant::now() + Duration::from_millis(510)).await;
|
||||||
waker.wake(WakerInterest::Timer);
|
waker.wake(WakerInterest::Timer);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@@ -1,12 +1,12 @@
|
|||||||
use std::{
|
use std::future::Future;
|
||||||
future::Future,
|
use std::pin::Pin;
|
||||||
io, mem,
|
use std::task::{Context, Poll};
|
||||||
pin::Pin,
|
use std::time::Duration;
|
||||||
task::{Context, Poll},
|
use std::{io, mem};
|
||||||
time::Duration,
|
|
||||||
};
|
|
||||||
|
|
||||||
use actix_rt::{self as rt, net::TcpStream, time::sleep, System};
|
use actix_rt::net::TcpStream;
|
||||||
|
use actix_rt::time::{sleep_until, Instant};
|
||||||
|
use actix_rt::{self as rt, System};
|
||||||
use log::{error, info};
|
use log::{error, info};
|
||||||
use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver};
|
use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver};
|
||||||
use tokio::sync::oneshot;
|
use tokio::sync::oneshot;
|
||||||
@@ -122,13 +122,13 @@ impl ServerBuilder {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Stop Actix system.
|
/// Stop actix system.
|
||||||
pub fn system_exit(mut self) -> Self {
|
pub fn system_exit(mut self) -> Self {
|
||||||
self.exit = true;
|
self.exit = true;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Disable signal handling.
|
/// Disable signal handling
|
||||||
pub fn disable_signals(mut self) -> Self {
|
pub fn disable_signals(mut self) -> Self {
|
||||||
self.no_signals = true;
|
self.no_signals = true;
|
||||||
self
|
self
|
||||||
@@ -136,8 +136,9 @@ impl ServerBuilder {
|
|||||||
|
|
||||||
/// Timeout for graceful workers shutdown in seconds.
|
/// Timeout for graceful workers shutdown in seconds.
|
||||||
///
|
///
|
||||||
/// After receiving a stop signal, workers have this much time to finish serving requests.
|
/// After receiving a stop signal, workers have this much time to finish
|
||||||
/// Workers still alive after the timeout are force dropped.
|
/// serving requests. Workers still alive after the timeout are force
|
||||||
|
/// dropped.
|
||||||
///
|
///
|
||||||
/// By default shutdown timeout sets to 30 seconds.
|
/// By default shutdown timeout sets to 30 seconds.
|
||||||
pub fn shutdown_timeout(mut self, sec: u64) -> Self {
|
pub fn shutdown_timeout(mut self, sec: u64) -> Self {
|
||||||
@@ -146,10 +147,11 @@ impl ServerBuilder {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Execute external configuration as part of the server building process.
|
/// Execute external configuration as part of the server building
|
||||||
|
/// process.
|
||||||
///
|
///
|
||||||
/// This function is useful for moving parts of configuration to a different module or
|
/// This function is useful for moving parts of configuration to a
|
||||||
/// even library.
|
/// different module or even library.
|
||||||
pub fn configure<F>(mut self, f: F) -> io::Result<ServerBuilder>
|
pub fn configure<F>(mut self, f: F) -> io::Result<ServerBuilder>
|
||||||
where
|
where
|
||||||
F: Fn(&mut ServiceConfig) -> io::Result<()>,
|
F: Fn(&mut ServiceConfig) -> io::Result<()>,
|
||||||
@@ -266,7 +268,6 @@ impl ServerBuilder {
|
|||||||
|
|
||||||
self.sockets
|
self.sockets
|
||||||
.push((token, name.as_ref().to_string(), MioListener::from(lst)));
|
.push((token, name.as_ref().to_string(), MioListener::from(lst)));
|
||||||
|
|
||||||
Ok(self)
|
Ok(self)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -392,7 +393,7 @@ impl ServerBuilder {
|
|||||||
}
|
}
|
||||||
if exit {
|
if exit {
|
||||||
rt::spawn(async {
|
rt::spawn(async {
|
||||||
sleep(Duration::from_millis(300)).await;
|
sleep_until(Instant::now() + Duration::from_millis(300)).await;
|
||||||
System::current().stop();
|
System::current().stop();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -401,7 +402,7 @@ impl ServerBuilder {
|
|||||||
// we need to stop system if server was spawned
|
// we need to stop system if server was spawned
|
||||||
if self.exit {
|
if self.exit {
|
||||||
rt::spawn(async {
|
rt::spawn(async {
|
||||||
sleep(Duration::from_millis(300)).await;
|
sleep_until(Instant::now() + Duration::from_millis(300)).await;
|
||||||
System::current().stop();
|
System::current().stop();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@@ -92,10 +92,10 @@ impl TestServer {
|
|||||||
let port = addr.port();
|
let port = addr.port();
|
||||||
|
|
||||||
TestServerRuntime {
|
TestServerRuntime {
|
||||||
|
system,
|
||||||
addr,
|
addr,
|
||||||
host,
|
host,
|
||||||
port,
|
port,
|
||||||
system,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -5,7 +5,7 @@ use std::sync::Arc;
|
|||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use actix_rt::time::{sleep, Sleep};
|
use actix_rt::time::{sleep_until, Instant, Sleep};
|
||||||
use actix_rt::{spawn, Arbiter};
|
use actix_rt::{spawn, Arbiter};
|
||||||
use actix_utils::counter::Counter;
|
use actix_utils::counter::Counter;
|
||||||
use futures_core::future::LocalBoxFuture;
|
use futures_core::future::LocalBoxFuture;
|
||||||
@@ -361,8 +361,8 @@ impl Future for ServerWorker {
|
|||||||
if num != 0 {
|
if num != 0 {
|
||||||
info!("Graceful worker shutdown, {} connections", num);
|
info!("Graceful worker shutdown, {} connections", num);
|
||||||
self.state = WorkerState::Shutdown(
|
self.state = WorkerState::Shutdown(
|
||||||
Box::pin(sleep(Duration::from_secs(1))),
|
Box::pin(sleep_until(Instant::now() + Duration::from_secs(1))),
|
||||||
Box::pin(sleep(self.config.shutdown_timeout)),
|
Box::pin(sleep_until(Instant::now() + self.config.shutdown_timeout)),
|
||||||
Some(result),
|
Some(result),
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
@@ -438,7 +438,7 @@ impl Future for ServerWorker {
|
|||||||
|
|
||||||
// sleep for 1 second and then check again
|
// sleep for 1 second and then check again
|
||||||
if t1.as_mut().poll(cx).is_ready() {
|
if t1.as_mut().poll(cx).is_ready() {
|
||||||
*t1 = Box::pin(sleep(Duration::from_secs(1)));
|
*t1 = Box::pin(sleep_until(Instant::now() + Duration::from_secs(1)));
|
||||||
let _ = t1.as_mut().poll(cx);
|
let _ = t1.as_mut().poll(cx);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -3,14 +3,6 @@
|
|||||||
## Unreleased - 2021-xx-xx
|
## Unreleased - 2021-xx-xx
|
||||||
|
|
||||||
|
|
||||||
## 2.0.0-beta.5 - 2021-03-15
|
|
||||||
* Add default `Service` trait impl for `Rc<S: Service>` and `&S: Service`. [#288]
|
|
||||||
* Add `boxed::rc_service` function for constructing `boxed::RcService` type [#290]
|
|
||||||
|
|
||||||
[#288]: https://github.com/actix/actix-net/pull/288
|
|
||||||
[#290]: https://github.com/actix/actix-net/pull/290
|
|
||||||
|
|
||||||
|
|
||||||
## 2.0.0-beta.4 - 2021-02-04
|
## 2.0.0-beta.4 - 2021-02-04
|
||||||
* `Service::poll_ready` and `Service::call` receive `&self`. [#247]
|
* `Service::poll_ready` and `Service::call` receive `&self`. [#247]
|
||||||
* `apply_fn` and `apply_fn_factory` now receive `Fn(Req, &Service)` function type. [#247]
|
* `apply_fn` and `apply_fn_factory` now receive `Fn(Req, &Service)` function type. [#247]
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-service"
|
name = "actix-service"
|
||||||
version = "2.0.0-beta.5"
|
version = "2.0.0-beta.4"
|
||||||
authors = [
|
authors = [
|
||||||
"Nikolay Kim <fafhrd91@gmail.com>",
|
"Nikolay Kim <fafhrd91@gmail.com>",
|
||||||
"Rob Ede <robjtede@icloud.com>",
|
"Rob Ede <robjtede@icloud.com>",
|
||||||
|
@@ -3,11 +3,11 @@
|
|||||||
> Service trait and combinators for representing asynchronous request/response operations.
|
> Service trait and combinators for representing asynchronous request/response operations.
|
||||||
|
|
||||||
[](https://crates.io/crates/actix-service)
|
[](https://crates.io/crates/actix-service)
|
||||||
[](https://docs.rs/actix-service/2.0.0-beta.5)
|
[](https://docs.rs/actix-service/2.0.0-beta.4)
|
||||||
[](https://blog.rust-lang.org/2020/03/12/Rust-1.46.html)
|
[](https://blog.rust-lang.org/2020/03/12/Rust-1.46.html)
|
||||||

|

|
||||||
[](https://deps.rs/crate/actix-service/2.0.0-beta.5)
|
[](https://deps.rs/crate/actix-service/2.0.0-beta.4)
|
||||||

|
[](https://crates.io/crates/actix-service)
|
||||||
[](https://discord.gg/NWpN5mmg3x)
|
[](https://discord.gg/NWpN5mmg3x)
|
||||||
|
|
||||||
See documentation for detailed explanations of these components: https://docs.rs/actix-service.
|
See documentation for detailed explanations of these components: https://docs.rs/actix-service.
|
||||||
|
@@ -1,65 +1,21 @@
|
|||||||
//! Trait object forms of services and service factories.
|
use alloc::boxed::Box;
|
||||||
|
use core::{
|
||||||
use alloc::{boxed::Box, rc::Rc};
|
future::Future,
|
||||||
use core::{future::Future, pin::Pin};
|
marker::PhantomData,
|
||||||
|
pin::Pin,
|
||||||
|
task::{Context, Poll},
|
||||||
|
};
|
||||||
|
|
||||||
use crate::{Service, ServiceFactory};
|
use crate::{Service, ServiceFactory};
|
||||||
|
|
||||||
/// A boxed future without a Send bound or lifetime parameters.
|
|
||||||
pub type BoxFuture<T> = Pin<Box<dyn Future<Output = T>>>;
|
pub type BoxFuture<T> = Pin<Box<dyn Future<Output = T>>>;
|
||||||
|
|
||||||
macro_rules! service_object {
|
pub type BoxService<Req, Res, Err> =
|
||||||
($name: ident, $type: tt, $fn_name: ident) => {
|
Box<dyn Service<Req, Response = Res, Error = Err, Future = BoxFuture<Result<Res, Err>>>>;
|
||||||
/// Type alias for service trait object.
|
|
||||||
pub type $name<Req, Res, Err> = $type<
|
|
||||||
dyn Service<Req, Response = Res, Error = Err, Future = BoxFuture<Result<Res, Err>>>,
|
|
||||||
>;
|
|
||||||
|
|
||||||
/// Create service trait object.
|
|
||||||
pub fn $fn_name<S, Req>(service: S) -> $name<Req, S::Response, S::Error>
|
|
||||||
where
|
|
||||||
S: Service<Req> + 'static,
|
|
||||||
Req: 'static,
|
|
||||||
S::Future: 'static,
|
|
||||||
{
|
|
||||||
$type::new(ServiceWrapper::new(service))
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
service_object!(BoxService, Box, service);
|
|
||||||
service_object!(RcService, Rc, rc_service);
|
|
||||||
|
|
||||||
struct ServiceWrapper<S> {
|
|
||||||
inner: S,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<S> ServiceWrapper<S> {
|
|
||||||
fn new(inner: S) -> Self {
|
|
||||||
Self { inner }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<S, Req, Res, Err> Service<Req> for ServiceWrapper<S>
|
|
||||||
where
|
|
||||||
S: Service<Req, Response = Res, Error = Err>,
|
|
||||||
S::Future: 'static,
|
|
||||||
{
|
|
||||||
type Response = Res;
|
|
||||||
type Error = Err;
|
|
||||||
type Future = BoxFuture<Result<Res, Err>>;
|
|
||||||
|
|
||||||
crate::forward_ready!(inner);
|
|
||||||
|
|
||||||
fn call(&self, req: Req) -> Self::Future {
|
|
||||||
Box::pin(self.inner.call(req))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Wrapper for a service factory trait object that will produce a boxed trait object service.
|
|
||||||
pub struct BoxServiceFactory<Cfg, Req, Res, Err, InitErr>(Inner<Cfg, Req, Res, Err, InitErr>);
|
pub struct BoxServiceFactory<Cfg, Req, Res, Err, InitErr>(Inner<Cfg, Req, Res, Err, InitErr>);
|
||||||
|
|
||||||
/// Create service factory trait object.
|
/// Create boxed service factory
|
||||||
pub fn factory<SF, Req>(
|
pub fn factory<SF, Req>(
|
||||||
factory: SF,
|
factory: SF,
|
||||||
) -> BoxServiceFactory<SF::Config, Req, SF::Response, SF::Error, SF::InitError>
|
) -> BoxServiceFactory<SF::Config, Req, SF::Response, SF::Error, SF::InitError>
|
||||||
@@ -72,7 +28,20 @@ where
|
|||||||
SF::Error: 'static,
|
SF::Error: 'static,
|
||||||
SF::InitError: 'static,
|
SF::InitError: 'static,
|
||||||
{
|
{
|
||||||
BoxServiceFactory(Box::new(FactoryWrapper(factory)))
|
BoxServiceFactory(Box::new(FactoryWrapper {
|
||||||
|
factory,
|
||||||
|
_t: PhantomData,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create boxed service
|
||||||
|
pub fn service<S, Req>(service: S) -> BoxService<Req, S::Response, S::Error>
|
||||||
|
where
|
||||||
|
S: Service<Req> + 'static,
|
||||||
|
Req: 'static,
|
||||||
|
S::Future: 'static,
|
||||||
|
{
|
||||||
|
Box::new(ServiceWrapper(service, PhantomData))
|
||||||
}
|
}
|
||||||
|
|
||||||
type Inner<C, Req, Res, Err, InitErr> = Box<
|
type Inner<C, Req, Res, Err, InitErr> = Box<
|
||||||
@@ -97,9 +66,9 @@ where
|
|||||||
{
|
{
|
||||||
type Response = Res;
|
type Response = Res;
|
||||||
type Error = Err;
|
type Error = Err;
|
||||||
|
type InitError = InitErr;
|
||||||
type Config = C;
|
type Config = C;
|
||||||
type Service = BoxService<Req, Res, Err>;
|
type Service = BoxService<Req, Res, Err>;
|
||||||
type InitError = InitErr;
|
|
||||||
|
|
||||||
type Future = BoxFuture<Result<Self::Service, InitErr>>;
|
type Future = BoxFuture<Result<Self::Service, InitErr>>;
|
||||||
|
|
||||||
@@ -108,9 +77,12 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct FactoryWrapper<SF>(SF);
|
struct FactoryWrapper<SF, Req, Cfg> {
|
||||||
|
factory: SF,
|
||||||
|
_t: PhantomData<(Req, Cfg)>,
|
||||||
|
}
|
||||||
|
|
||||||
impl<SF, Req, Cfg, Res, Err, InitErr> ServiceFactory<Req> for FactoryWrapper<SF>
|
impl<SF, Req, Cfg, Res, Err, InitErr> ServiceFactory<Req> for FactoryWrapper<SF, Req, Cfg>
|
||||||
where
|
where
|
||||||
Req: 'static,
|
Req: 'static,
|
||||||
Res: 'static,
|
Res: 'static,
|
||||||
@@ -123,13 +95,47 @@ where
|
|||||||
{
|
{
|
||||||
type Response = Res;
|
type Response = Res;
|
||||||
type Error = Err;
|
type Error = Err;
|
||||||
|
type InitError = InitErr;
|
||||||
type Config = Cfg;
|
type Config = Cfg;
|
||||||
type Service = BoxService<Req, Res, Err>;
|
type Service = BoxService<Req, Res, Err>;
|
||||||
type InitError = InitErr;
|
|
||||||
type Future = BoxFuture<Result<Self::Service, Self::InitError>>;
|
type Future = BoxFuture<Result<Self::Service, Self::InitError>>;
|
||||||
|
|
||||||
fn new_service(&self, cfg: Cfg) -> Self::Future {
|
fn new_service(&self, cfg: Cfg) -> Self::Future {
|
||||||
let f = self.0.new_service(cfg);
|
let fut = self.factory.new_service(cfg);
|
||||||
Box::pin(async { f.await.map(|s| Box::new(ServiceWrapper::new(s)) as _) })
|
Box::pin(async {
|
||||||
|
let res = fut.await;
|
||||||
|
res.map(ServiceWrapper::boxed)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ServiceWrapper<S: Service<Req>, Req>(S, PhantomData<Req>);
|
||||||
|
|
||||||
|
impl<S, Req> ServiceWrapper<S, Req>
|
||||||
|
where
|
||||||
|
S: Service<Req> + 'static,
|
||||||
|
Req: 'static,
|
||||||
|
S::Future: 'static,
|
||||||
|
{
|
||||||
|
fn boxed(service: S) -> BoxService<Req, S::Response, S::Error> {
|
||||||
|
Box::new(ServiceWrapper(service, PhantomData))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<S, Req, Res, Err> Service<Req> for ServiceWrapper<S, Req>
|
||||||
|
where
|
||||||
|
S: Service<Req, Response = Res, Error = Err>,
|
||||||
|
S::Future: 'static,
|
||||||
|
{
|
||||||
|
type Response = Res;
|
||||||
|
type Error = Err;
|
||||||
|
type Future = BoxFuture<Result<Res, Err>>;
|
||||||
|
|
||||||
|
fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||||
|
self.0.poll_ready(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn call(&self, req: Req) -> Self::Future {
|
||||||
|
Box::pin(self.0.call(req))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,7 +1,4 @@
|
|||||||
use crate::{
|
use crate::{dev, Service, ServiceFactory};
|
||||||
map::Map, map_err::MapErr, transform_err::TransformMapInitErr, Service, ServiceFactory,
|
|
||||||
Transform,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub trait ServiceExt<Req>: Service<Req> {
|
pub trait ServiceExt<Req>: Service<Req> {
|
||||||
/// Map this service's output to a different type, returning a new service
|
/// Map this service's output to a different type, returning a new service
|
||||||
@@ -13,12 +10,12 @@ pub trait ServiceExt<Req>: Service<Req> {
|
|||||||
/// Note that this function consumes the receiving service and returns a
|
/// Note that this function consumes the receiving service and returns a
|
||||||
/// wrapped version of it, similar to the existing `map` methods in the
|
/// wrapped version of it, similar to the existing `map` methods in the
|
||||||
/// standard library.
|
/// standard library.
|
||||||
fn map<F, R>(self, f: F) -> Map<Self, F, Req, R>
|
fn map<F, R>(self, f: F) -> dev::Map<Self, F, Req, R>
|
||||||
where
|
where
|
||||||
Self: Sized,
|
Self: Sized,
|
||||||
F: FnMut(Self::Response) -> R,
|
F: FnMut(Self::Response) -> R,
|
||||||
{
|
{
|
||||||
Map::new(self, f)
|
dev::Map::new(self, f)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Map this service's error to a different error, returning a new service.
|
/// Map this service's error to a different error, returning a new service.
|
||||||
@@ -29,12 +26,12 @@ pub trait ServiceExt<Req>: Service<Req> {
|
|||||||
///
|
///
|
||||||
/// Note that this function consumes the receiving service and returns a
|
/// Note that this function consumes the receiving service and returns a
|
||||||
/// wrapped version of it.
|
/// wrapped version of it.
|
||||||
fn map_err<F, E>(self, f: F) -> MapErr<Self, Req, F, E>
|
fn map_err<F, E>(self, f: F) -> dev::MapErr<Self, Req, F, E>
|
||||||
where
|
where
|
||||||
Self: Sized,
|
Self: Sized,
|
||||||
F: Fn(Self::Error) -> E,
|
F: Fn(Self::Error) -> E,
|
||||||
{
|
{
|
||||||
MapErr::new(self, f)
|
dev::MapErr::new(self, f)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -70,17 +67,4 @@ pub trait ServiceFactoryExt<Req>: ServiceFactory<Req> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<SF, Req> ServiceFactoryExt<Req> for SF where SF: ServiceFactory<Req> {}
|
impl<S, Req> ServiceFactoryExt<Req> for S where S: ServiceFactory<Req> {}
|
||||||
|
|
||||||
pub trait TransformExt<S, Req>: Transform<S, Req> {
|
|
||||||
/// Return a new `Transform` whose init error is mapped to to a different type.
|
|
||||||
fn map_init_err<F, E>(self, f: F) -> TransformMapInitErr<Self, S, Req, F, E>
|
|
||||||
where
|
|
||||||
Self: Sized,
|
|
||||||
F: Fn(Self::InitError) -> E + Clone,
|
|
||||||
{
|
|
||||||
TransformMapInitErr::new(self, f)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T, Req> TransformExt<T, Req> for T where T: Transform<T, Req> {}
|
|
||||||
|
@@ -1,4 +1,4 @@
|
|||||||
use core::{future::Future, marker::PhantomData};
|
use core::{future::Future, marker::PhantomData, task::Poll};
|
||||||
|
|
||||||
use crate::{ok, IntoService, IntoServiceFactory, Ready, Service, ServiceFactory};
|
use crate::{ok, IntoService, IntoServiceFactory, Ready, Service, ServiceFactory};
|
||||||
|
|
||||||
@@ -15,7 +15,8 @@ where
|
|||||||
|
|
||||||
/// Create `ServiceFactory` for function that can produce services
|
/// Create `ServiceFactory` for function that can produce services
|
||||||
///
|
///
|
||||||
/// # Examples
|
/// # Example
|
||||||
|
///
|
||||||
/// ```
|
/// ```
|
||||||
/// use std::io;
|
/// use std::io;
|
||||||
/// use actix_service::{fn_factory, fn_service, Service, ServiceFactory};
|
/// use actix_service::{fn_factory, fn_service, Service, ServiceFactory};
|
||||||
@@ -61,10 +62,11 @@ where
|
|||||||
|
|
||||||
/// Create `ServiceFactory` for function that accepts config argument and can produce services
|
/// Create `ServiceFactory` for function that accepts config argument and can produce services
|
||||||
///
|
///
|
||||||
/// Any function that has following form `Fn(Config) -> Future<Output = Service>` could act as
|
/// Any function that has following form `Fn(Config) -> Future<Output = Service>` could
|
||||||
/// a `ServiceFactory`.
|
/// act as a `ServiceFactory`.
|
||||||
|
///
|
||||||
|
/// # Example
|
||||||
///
|
///
|
||||||
/// # Examples
|
|
||||||
/// ```
|
/// ```
|
||||||
/// use std::io;
|
/// use std::io;
|
||||||
/// use actix_service::{fn_factory_with_config, fn_service, Service, ServiceFactory};
|
/// use actix_service::{fn_factory_with_config, fn_service, Service, ServiceFactory};
|
||||||
|
@@ -21,7 +21,6 @@ mod apply_cfg;
|
|||||||
pub mod boxed;
|
pub mod boxed;
|
||||||
mod ext;
|
mod ext;
|
||||||
mod fn_service;
|
mod fn_service;
|
||||||
mod macros;
|
|
||||||
mod map;
|
mod map;
|
||||||
mod map_config;
|
mod map_config;
|
||||||
mod map_err;
|
mod map_err;
|
||||||
@@ -34,11 +33,11 @@ mod transform_err;
|
|||||||
|
|
||||||
pub use self::apply::{apply_fn, apply_fn_factory};
|
pub use self::apply::{apply_fn, apply_fn_factory};
|
||||||
pub use self::apply_cfg::{apply_cfg, apply_cfg_factory};
|
pub use self::apply_cfg::{apply_cfg, apply_cfg_factory};
|
||||||
pub use self::ext::{ServiceExt, ServiceFactoryExt, TransformExt};
|
pub use self::ext::{ServiceExt, ServiceFactoryExt};
|
||||||
pub use self::fn_service::{fn_factory, fn_factory_with_config, fn_service};
|
pub use self::fn_service::{fn_factory, fn_factory_with_config, fn_service};
|
||||||
pub use self::map_config::{map_config, unit_config};
|
pub use self::map_config::{map_config, unit_config};
|
||||||
pub use self::pipeline::{pipeline, pipeline_factory, Pipeline, PipelineFactory};
|
pub use self::pipeline::{pipeline, pipeline_factory, Pipeline, PipelineFactory};
|
||||||
pub use self::transform::{apply, ApplyTransform, Transform};
|
pub use self::transform::{apply, Transform};
|
||||||
|
|
||||||
#[allow(unused_imports)]
|
#[allow(unused_imports)]
|
||||||
use self::ready::{err, ok, ready, Ready};
|
use self::ready::{err, ok, ready, Ready};
|
||||||
@@ -151,7 +150,6 @@ pub trait ServiceFactory<Req> {
|
|||||||
fn new_service(&self, cfg: Self::Config) -> Self::Future;
|
fn new_service(&self, cfg: Self::Config) -> Self::Future;
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: remove implement on mut reference.
|
|
||||||
impl<'a, S, Req> Service<Req> for &'a mut S
|
impl<'a, S, Req> Service<Req> for &'a mut S
|
||||||
where
|
where
|
||||||
S: Service<Req> + 'a,
|
S: Service<Req> + 'a,
|
||||||
@@ -169,23 +167,6 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a, S, Req> Service<Req> for &'a S
|
|
||||||
where
|
|
||||||
S: Service<Req> + 'a,
|
|
||||||
{
|
|
||||||
type Response = S::Response;
|
|
||||||
type Error = S::Error;
|
|
||||||
type Future = S::Future;
|
|
||||||
|
|
||||||
fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
|
||||||
(**self).poll_ready(ctx)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn call(&self, request: Req) -> S::Future {
|
|
||||||
(**self).call(request)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<S, Req> Service<Req> for Box<S>
|
impl<S, Req> Service<Req> for Box<S>
|
||||||
where
|
where
|
||||||
S: Service<Req> + ?Sized,
|
S: Service<Req> + ?Sized,
|
||||||
@@ -203,25 +184,24 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S, Req> Service<Req> for Rc<S>
|
impl<S, Req> Service<Req> for RefCell<S>
|
||||||
where
|
where
|
||||||
S: Service<Req> + ?Sized,
|
S: Service<Req>,
|
||||||
{
|
{
|
||||||
type Response = S::Response;
|
type Response = S::Response;
|
||||||
type Error = S::Error;
|
type Error = S::Error;
|
||||||
type Future = S::Future;
|
type Future = S::Future;
|
||||||
|
|
||||||
fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||||
(**self).poll_ready(ctx)
|
self.borrow().poll_ready(ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(&self, request: Req) -> S::Future {
|
fn call(&self, request: Req) -> S::Future {
|
||||||
(**self).call(request)
|
self.borrow().call(request)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// This impl is deprecated since v2 because the `Service` trait now receives shared reference.
|
impl<S, Req> Service<Req> for Rc<RefCell<S>>
|
||||||
impl<S, Req> Service<Req> for RefCell<S>
|
|
||||||
where
|
where
|
||||||
S: Service<Req>,
|
S: Service<Req>,
|
||||||
{
|
{
|
||||||
@@ -314,3 +294,44 @@ where
|
|||||||
{
|
{
|
||||||
tp.into_service()
|
tp.into_service()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub mod dev {
|
||||||
|
pub use crate::apply::{Apply, ApplyFactory};
|
||||||
|
pub use crate::fn_service::{
|
||||||
|
FnService, FnServiceConfig, FnServiceFactory, FnServiceNoConfig,
|
||||||
|
};
|
||||||
|
pub use crate::map::{Map, MapServiceFactory};
|
||||||
|
pub use crate::map_config::{MapConfig, UnitConfig};
|
||||||
|
pub use crate::map_err::{MapErr, MapErrServiceFactory};
|
||||||
|
pub use crate::map_init_err::MapInitErr;
|
||||||
|
pub use crate::transform::ApplyTransform;
|
||||||
|
pub use crate::transform_err::TransformMapInitErr;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[macro_export]
|
||||||
|
macro_rules! always_ready {
|
||||||
|
() => {
|
||||||
|
#[inline]
|
||||||
|
fn poll_ready(
|
||||||
|
&self,
|
||||||
|
_: &mut ::core::task::Context<'_>,
|
||||||
|
) -> ::core::task::Poll<Result<(), Self::Error>> {
|
||||||
|
Poll::Ready(Ok(()))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
#[macro_export]
|
||||||
|
macro_rules! forward_ready {
|
||||||
|
($field:ident) => {
|
||||||
|
#[inline]
|
||||||
|
fn poll_ready(
|
||||||
|
&self,
|
||||||
|
cx: &mut ::core::task::Context<'_>,
|
||||||
|
) -> ::core::task::Poll<Result<(), Self::Error>> {
|
||||||
|
self.$field
|
||||||
|
.poll_ready(cx)
|
||||||
|
.map_err(::core::convert::Into::into)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
@@ -1,181 +0,0 @@
|
|||||||
/// A boilerplate implementation of [`Service::poll_ready`] that always signals readiness.
|
|
||||||
///
|
|
||||||
/// [`Service::poll_ready`]: crate::Service::poll_ready
|
|
||||||
///
|
|
||||||
/// # Examples
|
|
||||||
/// ```no_run
|
|
||||||
/// use actix_service::Service;
|
|
||||||
/// use futures_util::future::{ready, Ready};
|
|
||||||
///
|
|
||||||
/// struct IdentityService;
|
|
||||||
///
|
|
||||||
/// impl Service<u32> for IdentityService {
|
|
||||||
/// type Response = u32;
|
|
||||||
/// type Error = ();
|
|
||||||
/// type Future = Ready<Result<Self::Response, Self::Error>>;
|
|
||||||
///
|
|
||||||
/// actix_service::always_ready!();
|
|
||||||
///
|
|
||||||
/// fn call(&self, req: u32) -> Self::Future {
|
|
||||||
/// ready(Ok(req))
|
|
||||||
/// }
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
#[macro_export]
|
|
||||||
macro_rules! always_ready {
|
|
||||||
() => {
|
|
||||||
#[inline]
|
|
||||||
fn poll_ready(
|
|
||||||
&self,
|
|
||||||
_: &mut ::core::task::Context<'_>,
|
|
||||||
) -> ::core::task::Poll<Result<(), Self::Error>> {
|
|
||||||
::core::task::Poll::Ready(Ok(()))
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A boilerplate implementation of [`Service::poll_ready`] that forwards readiness checks to a
|
|
||||||
/// named struct field.
|
|
||||||
///
|
|
||||||
/// Tuple structs are not supported.
|
|
||||||
///
|
|
||||||
/// [`Service::poll_ready`]: crate::Service::poll_ready
|
|
||||||
///
|
|
||||||
/// # Examples
|
|
||||||
/// ```no_run
|
|
||||||
/// use actix_service::Service;
|
|
||||||
/// use futures_util::future::{ready, Ready};
|
|
||||||
///
|
|
||||||
/// struct WrapperService<S> {
|
|
||||||
/// inner: S,
|
|
||||||
/// }
|
|
||||||
///
|
|
||||||
/// impl<S> Service<()> for WrapperService<S>
|
|
||||||
/// where
|
|
||||||
/// S: Service<()>,
|
|
||||||
/// {
|
|
||||||
/// type Response = S::Response;
|
|
||||||
/// type Error = S::Error;
|
|
||||||
/// type Future = S::Future;
|
|
||||||
///
|
|
||||||
/// actix_service::forward_ready!(inner);
|
|
||||||
///
|
|
||||||
/// fn call(&self, req: ()) -> Self::Future {
|
|
||||||
/// self.inner.call(req)
|
|
||||||
/// }
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
#[macro_export]
|
|
||||||
macro_rules! forward_ready {
|
|
||||||
($field:ident) => {
|
|
||||||
#[inline]
|
|
||||||
fn poll_ready(
|
|
||||||
&self,
|
|
||||||
cx: &mut ::core::task::Context<'_>,
|
|
||||||
) -> ::core::task::Poll<Result<(), Self::Error>> {
|
|
||||||
self.$field
|
|
||||||
.poll_ready(cx)
|
|
||||||
.map_err(::core::convert::Into::into)
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use core::{
|
|
||||||
cell::Cell,
|
|
||||||
convert::Infallible,
|
|
||||||
task::{self, Context, Poll},
|
|
||||||
};
|
|
||||||
|
|
||||||
use futures_util::{
|
|
||||||
future::{ready, Ready},
|
|
||||||
task::noop_waker,
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::Service;
|
|
||||||
|
|
||||||
struct IdentityService;
|
|
||||||
|
|
||||||
impl Service<u32> for IdentityService {
|
|
||||||
type Response = u32;
|
|
||||||
type Error = Infallible;
|
|
||||||
type Future = Ready<Result<Self::Response, Self::Error>>;
|
|
||||||
|
|
||||||
always_ready!();
|
|
||||||
|
|
||||||
fn call(&self, req: u32) -> Self::Future {
|
|
||||||
ready(Ok(req))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct CountdownService(Cell<u32>);
|
|
||||||
|
|
||||||
impl Service<()> for CountdownService {
|
|
||||||
type Response = ();
|
|
||||||
type Error = Infallible;
|
|
||||||
type Future = Ready<Result<Self::Response, Self::Error>>;
|
|
||||||
|
|
||||||
fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
|
||||||
let count = self.0.get();
|
|
||||||
|
|
||||||
if count == 0 {
|
|
||||||
Poll::Ready(Ok(()))
|
|
||||||
} else {
|
|
||||||
self.0.set(count - 1);
|
|
||||||
cx.waker().wake_by_ref();
|
|
||||||
Poll::Pending
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn call(&self, _: ()) -> Self::Future {
|
|
||||||
ready(Ok(()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct WrapperService<S> {
|
|
||||||
inner: S,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<S> Service<()> for WrapperService<S>
|
|
||||||
where
|
|
||||||
S: Service<()>,
|
|
||||||
{
|
|
||||||
type Response = S::Response;
|
|
||||||
type Error = S::Error;
|
|
||||||
type Future = S::Future;
|
|
||||||
|
|
||||||
forward_ready!(inner);
|
|
||||||
|
|
||||||
fn call(&self, req: ()) -> Self::Future {
|
|
||||||
self.inner.call(req)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_always_ready_macro() {
|
|
||||||
let waker = noop_waker();
|
|
||||||
let mut cx = task::Context::from_waker(&waker);
|
|
||||||
|
|
||||||
let svc = IdentityService;
|
|
||||||
|
|
||||||
assert!(svc.poll_ready(&mut cx).is_ready());
|
|
||||||
assert!(svc.poll_ready(&mut cx).is_ready());
|
|
||||||
assert!(svc.poll_ready(&mut cx).is_ready());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_forward_ready_macro() {
|
|
||||||
let waker = noop_waker();
|
|
||||||
let mut cx = task::Context::from_waker(&waker);
|
|
||||||
|
|
||||||
let svc = WrapperService {
|
|
||||||
inner: CountdownService(Cell::new(3)),
|
|
||||||
};
|
|
||||||
|
|
||||||
assert!(svc.poll_ready(&mut cx).is_pending());
|
|
||||||
assert!(svc.poll_ready(&mut cx).is_pending());
|
|
||||||
assert!(svc.poll_ready(&mut cx).is_pending());
|
|
||||||
assert!(svc.poll_ready(&mut cx).is_ready());
|
|
||||||
}
|
|
||||||
}
|
|
@@ -180,7 +180,7 @@ where
|
|||||||
F: Fn(A::Error) -> E,
|
F: Fn(A::Error) -> E,
|
||||||
{
|
{
|
||||||
fn new(fut: A::Future, f: F) -> Self {
|
fn new(fut: A::Future, f: F) -> Self {
|
||||||
MapErrServiceFuture { fut, f }
|
MapErrServiceFuture { f, fut }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -9,9 +9,10 @@ use core::{
|
|||||||
use futures_core::ready;
|
use futures_core::ready;
|
||||||
use pin_project_lite::pin_project;
|
use pin_project_lite::pin_project;
|
||||||
|
|
||||||
|
use crate::transform_err::TransformMapInitErr;
|
||||||
use crate::{IntoServiceFactory, Service, ServiceFactory};
|
use crate::{IntoServiceFactory, Service, ServiceFactory};
|
||||||
|
|
||||||
/// Apply a [`Transform`] to a [`Service`].
|
/// Apply transform to a service.
|
||||||
pub fn apply<T, S, I, Req>(t: T, factory: I) -> ApplyTransform<T, S, Req>
|
pub fn apply<T, S, I, Req>(t: T, factory: I) -> ApplyTransform<T, S, Req>
|
||||||
where
|
where
|
||||||
I: IntoServiceFactory<S, Req>,
|
I: IntoServiceFactory<S, Req>,
|
||||||
@@ -24,8 +25,9 @@ where
|
|||||||
/// The `Transform` trait defines the interface of a service factory that wraps inner service
|
/// The `Transform` trait defines the interface of a service factory that wraps inner service
|
||||||
/// during construction.
|
/// during construction.
|
||||||
///
|
///
|
||||||
/// Transform(middleware) wraps inner service and runs during inbound and/or outbound processing in
|
/// Transform(middleware) wraps inner service and runs during
|
||||||
/// the request/response lifecycle. It may modify request and/or response.
|
/// inbound and/or outbound processing in the request/response lifecycle.
|
||||||
|
/// It may modify request and/or response.
|
||||||
///
|
///
|
||||||
/// For example, timeout transform:
|
/// For example, timeout transform:
|
||||||
///
|
///
|
||||||
@@ -49,19 +51,20 @@ where
|
|||||||
/// fn call(&self, req: S::Request) -> Self::Future {
|
/// fn call(&self, req: S::Request) -> Self::Future {
|
||||||
/// TimeoutServiceResponse {
|
/// TimeoutServiceResponse {
|
||||||
/// fut: self.service.call(req),
|
/// fut: self.service.call(req),
|
||||||
/// sleep: Sleep::new(clock::now() + self.timeout),
|
/// sleep: Delay::new(clock::now() + self.timeout),
|
||||||
/// }
|
/// }
|
||||||
/// }
|
/// }
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
///
|
///
|
||||||
/// Timeout service in above example is decoupled from underlying service implementation and could
|
/// Timeout service in above example is decoupled from underlying service implementation
|
||||||
/// be applied to any service.
|
/// and could be applied to any service.
|
||||||
///
|
///
|
||||||
/// The `Transform` trait defines the interface of a Service factory. `Transform` is often
|
/// The `Transform` trait defines the interface of a Service factory. `Transform`
|
||||||
/// implemented for middleware, defining how to construct a middleware Service. A Service that is
|
/// is often implemented for middleware, defining how to construct a
|
||||||
/// constructed by the factory takes the Service that follows it during execution as a parameter,
|
/// middleware Service. A Service that is constructed by the factory takes
|
||||||
/// assuming ownership of the next Service.
|
/// the Service that follows it during execution as a parameter, assuming
|
||||||
|
/// ownership of the next Service.
|
||||||
///
|
///
|
||||||
/// Factory for `Timeout` middleware from the above example could look like this:
|
/// Factory for `Timeout` middleware from the above example could look like this:
|
||||||
///
|
///
|
||||||
@@ -82,15 +85,15 @@ where
|
|||||||
/// type Future = Ready<Result<Self::Transform, Self::InitError>>;
|
/// type Future = Ready<Result<Self::Transform, Self::InitError>>;
|
||||||
///
|
///
|
||||||
/// fn new_transform(&self, service: S) -> Self::Future {
|
/// fn new_transform(&self, service: S) -> Self::Future {
|
||||||
/// ready(Ok(TimeoutService {
|
/// ok(TimeoutService {
|
||||||
/// service,
|
/// service,
|
||||||
/// timeout: self.timeout,
|
/// timeout: self.timeout,
|
||||||
/// }))
|
/// })
|
||||||
/// }
|
/// }
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
pub trait Transform<S, Req> {
|
pub trait Transform<S, Req> {
|
||||||
/// Responses produced by the service.
|
/// Responses given by the service.
|
||||||
type Response;
|
type Response;
|
||||||
|
|
||||||
/// Errors produced by the service.
|
/// Errors produced by the service.
|
||||||
@@ -107,6 +110,16 @@ pub trait Transform<S, Req> {
|
|||||||
|
|
||||||
/// Creates and returns a new Transform component, asynchronously
|
/// Creates and returns a new Transform component, asynchronously
|
||||||
fn new_transform(&self, service: S) -> Self::Future;
|
fn new_transform(&self, service: S) -> Self::Future;
|
||||||
|
|
||||||
|
/// Map this transform's factory error to a different error,
|
||||||
|
/// returning a new transform service factory.
|
||||||
|
fn map_init_err<F, E>(self, f: F) -> TransformMapInitErr<Self, S, Req, F, E>
|
||||||
|
where
|
||||||
|
Self: Sized,
|
||||||
|
F: Fn(Self::InitError) -> E + Clone,
|
||||||
|
{
|
||||||
|
TransformMapInitErr::new(self, f)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, S, Req> Transform<S, Req> for Rc<T>
|
impl<T, S, Req> Transform<S, Req> for Rc<T>
|
||||||
@@ -139,7 +152,7 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Apply a [`Transform`] to a [`Service`].
|
/// `Apply` transform to new service
|
||||||
pub struct ApplyTransform<T, S, Req>(Rc<(T, S)>, PhantomData<Req>);
|
pub struct ApplyTransform<T, S, Req>(Rc<(T, S)>, PhantomData<Req>);
|
||||||
|
|
||||||
impl<T, S, Req> ApplyTransform<T, S, Req>
|
impl<T, S, Req> ApplyTransform<T, S, Req>
|
||||||
|
@@ -9,8 +9,10 @@ use pin_project_lite::pin_project;
|
|||||||
|
|
||||||
use super::Transform;
|
use super::Transform;
|
||||||
|
|
||||||
/// Transform for the [`TransformExt::map_init_err`] combinator, changing the type of a new
|
/// Transform for the `map_init_err` combinator, changing the type of a new
|
||||||
/// [`Transform`]'s initialization error.
|
/// transform's init error.
|
||||||
|
///
|
||||||
|
/// This is created by the `Transform::map_init_err` method.
|
||||||
pub struct TransformMapInitErr<T, S, Req, F, E> {
|
pub struct TransformMapInitErr<T, S, Req, F, E> {
|
||||||
transform: T,
|
transform: T,
|
||||||
mapper: F,
|
mapper: F,
|
||||||
|
@@ -1,28 +1,9 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
## Unreleased - 2021-xx-xx
|
## Unreleased - 2021-xx-xx
|
||||||
|
|
||||||
|
|
||||||
## 3.0.0-beta.5 - 2021-03-29
|
|
||||||
* Changed `connect::ssl::rustls::RustlsConnectorService` to return error when `DNSNameRef`
|
|
||||||
generation failed instead of panic. [#296]
|
|
||||||
* Remove `connect::ssl::openssl::OpensslConnectServiceFactory`. [#297]
|
|
||||||
* Remove `connect::ssl::openssl::OpensslConnectService`. [#297]
|
|
||||||
* Add `connect::ssl::native_tls` module for native tls support. [#295]
|
|
||||||
* Rename `accept::{nativetls => native_tls}`. [#295]
|
|
||||||
* Remove `connect::TcpConnectService` type. service caller expect a `TcpStream` should use
|
|
||||||
`connect::ConnectService` instead and call `Connection<T, TcpStream>::into_parts`. [#299]
|
|
||||||
|
|
||||||
[#295]: https://github.com/actix/actix-net/pull/295
|
|
||||||
[#296]: https://github.com/actix/actix-net/pull/296
|
|
||||||
[#297]: https://github.com/actix/actix-net/pull/297
|
|
||||||
[#299]: https://github.com/actix/actix-net/pull/299
|
|
||||||
|
|
||||||
|
|
||||||
## 3.0.0-beta.4 - 2021-02-24
|
|
||||||
* Rename `accept::openssl::{SslStream => TlsStream}`.
|
* Rename `accept::openssl::{SslStream => TlsStream}`.
|
||||||
* Add `connect::Connect::set_local_addr` to attach local `IpAddr`. [#282]
|
* Add `connect::Connect::set_local_addr` to attach local `Ipaddr`. [#282]
|
||||||
* `connector::TcpConnector` service will try to bind to local_addr of `IpAddr` when given. [#282]
|
* `connector::TcpConnector` service would try to bind to local_addr of `IpAddr` when given [#282]
|
||||||
|
|
||||||
[#282]: https://github.com/actix/actix-net/pull/282
|
[#282]: https://github.com/actix/actix-net/pull/282
|
||||||
|
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-tls"
|
name = "actix-tls"
|
||||||
version = "3.0.0-beta.5"
|
version = "3.0.0-beta.3"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "TLS acceptor and connector services for Actix ecosystem"
|
description = "TLS acceptor and connector services for Actix ecosystem"
|
||||||
keywords = ["network", "tls", "ssl", "async", "transport"]
|
keywords = ["network", "tls", "ssl", "async", "transport"]
|
||||||
@@ -41,8 +41,8 @@ uri = ["http"]
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-codec = "0.4.0-beta.1"
|
actix-codec = "0.4.0-beta.1"
|
||||||
actix-rt = { version = "2.2.0", default-features = false }
|
actix-rt = { version = "2.0.0", default-features = false }
|
||||||
actix-service = "2.0.0-beta.5"
|
actix-service = "2.0.0-beta.4"
|
||||||
actix-utils = "3.0.0-beta.2"
|
actix-utils = "3.0.0-beta.2"
|
||||||
|
|
||||||
derive_more = "0.99.5"
|
derive_more = "0.99.5"
|
||||||
@@ -62,8 +62,14 @@ webpki-roots = { version = "0.21", optional = true }
|
|||||||
# native-tls
|
# native-tls
|
||||||
tokio-native-tls = { version = "0.3", optional = true }
|
tokio-native-tls = { version = "0.3", optional = true }
|
||||||
|
|
||||||
|
[target.'cfg(windows)'.dependencies.tls-openssl]
|
||||||
|
version = "0.10.9"
|
||||||
|
package = "openssl"
|
||||||
|
features = ["vendored"]
|
||||||
|
optional = true
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-rt = "2.2.0"
|
actix-rt = "2.0.0"
|
||||||
actix-server = "2.0.0-beta.3"
|
actix-server = "2.0.0-beta.3"
|
||||||
bytes = "1"
|
bytes = "1"
|
||||||
env_logger = "0.8"
|
env_logger = "0.8"
|
||||||
@@ -72,5 +78,5 @@ log = "0.4"
|
|||||||
trust-dns-resolver = "0.20.0"
|
trust-dns-resolver = "0.20.0"
|
||||||
|
|
||||||
[[example]]
|
[[example]]
|
||||||
name = "tcp-rustls"
|
name = "basic"
|
||||||
required-features = ["accept", "rustls"]
|
required-features = ["accept", "rustls"]
|
||||||
|
@@ -16,7 +16,7 @@ pub mod openssl;
|
|||||||
pub mod rustls;
|
pub mod rustls;
|
||||||
|
|
||||||
#[cfg(feature = "native-tls")]
|
#[cfg(feature = "native-tls")]
|
||||||
pub mod native_tls;
|
pub mod nativetls;
|
||||||
|
|
||||||
pub(crate) static MAX_CONN: AtomicUsize = AtomicUsize::new(256);
|
pub(crate) static MAX_CONN: AtomicUsize = AtomicUsize::new(256);
|
||||||
|
|
||||||
|
@@ -6,7 +6,7 @@ use std::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use actix_codec::{AsyncRead, AsyncWrite, ReadBuf};
|
use actix_codec::{AsyncRead, AsyncWrite, ReadBuf};
|
||||||
use actix_rt::net::{ActixStream, Ready};
|
use actix_rt::net::ActixStream;
|
||||||
use actix_service::{Service, ServiceFactory};
|
use actix_service::{Service, ServiceFactory};
|
||||||
use actix_utils::counter::Counter;
|
use actix_utils::counter::Counter;
|
||||||
use futures_core::future::LocalBoxFuture;
|
use futures_core::future::LocalBoxFuture;
|
||||||
@@ -80,11 +80,11 @@ impl<T: ActixStream> AsyncWrite for TlsStream<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<T: ActixStream> ActixStream for TlsStream<T> {
|
impl<T: ActixStream> ActixStream for TlsStream<T> {
|
||||||
fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
|
fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||||
T::poll_read_ready((&**self).get_ref().get_ref().get_ref(), cx)
|
T::poll_read_ready((&**self).get_ref().get_ref().get_ref(), cx)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
|
fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||||
T::poll_write_ready((&**self).get_ref().get_ref().get_ref(), cx)
|
T::poll_write_ready((&**self).get_ref().get_ref().get_ref(), cx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -113,7 +113,7 @@ impl Clone for Acceptor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: ActixStream + 'static> ServiceFactory<T> for Acceptor {
|
impl<T: ActixStream> ServiceFactory<T> for Acceptor {
|
||||||
type Response = TlsStream<T>;
|
type Response = TlsStream<T>;
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
type Config = ();
|
type Config = ();
|
||||||
@@ -138,7 +138,16 @@ pub struct NativeTlsAcceptorService {
|
|||||||
conns: Counter,
|
conns: Counter,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: ActixStream + 'static> Service<T> for NativeTlsAcceptorService {
|
impl Clone for NativeTlsAcceptorService {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
Self {
|
||||||
|
acceptor: self.acceptor.clone(),
|
||||||
|
conns: self.conns.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: ActixStream> Service<T> for NativeTlsAcceptorService {
|
||||||
type Response = TlsStream<T>;
|
type Response = TlsStream<T>;
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
type Future = LocalBoxFuture<'static, Result<TlsStream<T>, Error>>;
|
type Future = LocalBoxFuture<'static, Result<TlsStream<T>, Error>>;
|
||||||
@@ -153,9 +162,9 @@ impl<T: ActixStream + 'static> Service<T> for NativeTlsAcceptorService {
|
|||||||
|
|
||||||
fn call(&self, io: T) -> Self::Future {
|
fn call(&self, io: T) -> Self::Future {
|
||||||
let guard = self.conns.get();
|
let guard = self.conns.get();
|
||||||
let acceptor = self.acceptor.clone();
|
let this = self.clone();
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
let io = acceptor.accept(io).await;
|
let io = this.acceptor.accept(io).await;
|
||||||
drop(guard);
|
drop(guard);
|
||||||
io.map(Into::into)
|
io.map(Into::into)
|
||||||
})
|
})
|
@@ -7,7 +7,7 @@ use std::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use actix_codec::{AsyncRead, AsyncWrite, ReadBuf};
|
use actix_codec::{AsyncRead, AsyncWrite, ReadBuf};
|
||||||
use actix_rt::net::{ActixStream, Ready};
|
use actix_rt::net::ActixStream;
|
||||||
use actix_service::{Service, ServiceFactory};
|
use actix_service::{Service, ServiceFactory};
|
||||||
use actix_utils::counter::{Counter, CounterGuard};
|
use actix_utils::counter::{Counter, CounterGuard};
|
||||||
use futures_core::{future::LocalBoxFuture, ready};
|
use futures_core::{future::LocalBoxFuture, ready};
|
||||||
@@ -82,11 +82,11 @@ impl<T: ActixStream> AsyncWrite for TlsStream<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<T: ActixStream> ActixStream for TlsStream<T> {
|
impl<T: ActixStream> ActixStream for TlsStream<T> {
|
||||||
fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
|
fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||||
T::poll_read_ready((&**self).get_ref(), cx)
|
T::poll_read_ready((&**self).get_ref(), cx)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
|
fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||||
T::poll_write_ready((&**self).get_ref(), cx)
|
T::poll_write_ready((&**self).get_ref(), cx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -8,7 +8,7 @@ use std::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use actix_codec::{AsyncRead, AsyncWrite, ReadBuf};
|
use actix_codec::{AsyncRead, AsyncWrite, ReadBuf};
|
||||||
use actix_rt::net::{ActixStream, Ready};
|
use actix_rt::net::ActixStream;
|
||||||
use actix_service::{Service, ServiceFactory};
|
use actix_service::{Service, ServiceFactory};
|
||||||
use actix_utils::counter::{Counter, CounterGuard};
|
use actix_utils::counter::{Counter, CounterGuard};
|
||||||
use futures_core::future::LocalBoxFuture;
|
use futures_core::future::LocalBoxFuture;
|
||||||
@@ -82,11 +82,11 @@ impl<T: ActixStream> AsyncWrite for TlsStream<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<T: ActixStream> ActixStream for TlsStream<T> {
|
impl<T: ActixStream> ActixStream for TlsStream<T> {
|
||||||
fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
|
fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||||
T::poll_read_ready((&**self).get_ref().0, cx)
|
T::poll_read_ready((&**self).get_ref().0, cx)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
|
fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||||
T::poll_write_ready((&**self).get_ref().0, cx)
|
T::poll_write_ready((&**self).get_ref().0, cx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -72,7 +72,7 @@ pub enum TcpConnectorResponse<T> {
|
|||||||
port: u16,
|
port: u16,
|
||||||
local_addr: Option<IpAddr>,
|
local_addr: Option<IpAddr>,
|
||||||
addrs: Option<VecDeque<SocketAddr>>,
|
addrs: Option<VecDeque<SocketAddr>>,
|
||||||
stream: ReusableBoxFuture<Result<TcpStream, io::Error>>,
|
stream: Option<ReusableBoxFuture<Result<TcpStream, io::Error>>>,
|
||||||
},
|
},
|
||||||
Error(Option<ConnectError>),
|
Error(Option<ConnectError>),
|
||||||
}
|
}
|
||||||
@@ -103,22 +103,18 @@ impl<T: Address> TcpConnectorResponse<T> {
|
|||||||
port,
|
port,
|
||||||
local_addr,
|
local_addr,
|
||||||
addrs: None,
|
addrs: None,
|
||||||
stream: ReusableBoxFuture::new(connect(addr, local_addr)),
|
stream: Some(ReusableBoxFuture::new(connect(addr, local_addr))),
|
||||||
},
|
},
|
||||||
|
|
||||||
// when resolver returns multiple socket addr for request they would be popped from
|
// when resolver returns multiple socket addr for request they would be popped from
|
||||||
// front end of queue and returns with the first successful tcp connection.
|
// front end of queue and returns with the first successful tcp connection.
|
||||||
ConnectAddrs::Multi(mut addrs) => {
|
ConnectAddrs::Multi(addrs) => TcpConnectorResponse::Response {
|
||||||
let addr = addrs.pop_front().unwrap();
|
req: Some(req),
|
||||||
|
port,
|
||||||
TcpConnectorResponse::Response {
|
local_addr,
|
||||||
req: Some(req),
|
addrs: Some(addrs),
|
||||||
port,
|
stream: None,
|
||||||
local_addr,
|
},
|
||||||
addrs: Some(addrs),
|
|
||||||
stream: ReusableBoxFuture::new(connect(addr, local_addr)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -137,31 +133,40 @@ impl<T: Address> Future for TcpConnectorResponse<T> {
|
|||||||
addrs,
|
addrs,
|
||||||
stream,
|
stream,
|
||||||
} => loop {
|
} => loop {
|
||||||
match ready!(stream.poll(cx)) {
|
if let Some(new) = stream.as_mut() {
|
||||||
Ok(sock) => {
|
match ready!(new.poll(cx)) {
|
||||||
let req = req.take().unwrap();
|
Ok(sock) => {
|
||||||
trace!(
|
let req = req.take().unwrap();
|
||||||
"TCP connector: successfully connected to {:?} - {:?}",
|
trace!(
|
||||||
req.hostname(),
|
"TCP connector: successfully connected to {:?} - {:?}",
|
||||||
sock.peer_addr()
|
req.hostname(),
|
||||||
);
|
sock.peer_addr()
|
||||||
return Poll::Ready(Ok(Connection::new(sock, req)));
|
);
|
||||||
}
|
return Poll::Ready(Ok(Connection::new(sock, req)));
|
||||||
|
}
|
||||||
|
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
trace!(
|
trace!(
|
||||||
"TCP connector: failed to connect to {:?} port: {}",
|
"TCP connector: failed to connect to {:?} port: {}",
|
||||||
req.as_ref().unwrap().hostname(),
|
req.as_ref().unwrap().hostname(),
|
||||||
port,
|
port,
|
||||||
);
|
);
|
||||||
|
|
||||||
if let Some(addr) = addrs.as_mut().and_then(|addrs| addrs.pop_front()) {
|
if addrs.is_none() || addrs.as_ref().unwrap().is_empty() {
|
||||||
stream.set(connect(addr, *local_addr));
|
return Poll::Ready(Err(ConnectError::Io(err)));
|
||||||
} else {
|
}
|
||||||
return Poll::Ready(Err(ConnectError::Io(err)));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// try to connect
|
||||||
|
let addr = addrs.as_mut().unwrap().pop_front().unwrap();
|
||||||
|
|
||||||
|
let fut = connect(addr, *local_addr);
|
||||||
|
match stream {
|
||||||
|
Some(rbf) => rbf.set(fut),
|
||||||
|
None => *stream = Some(ReusableBoxFuture::new(fut)),
|
||||||
|
}
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -26,20 +26,20 @@ pub mod ssl;
|
|||||||
mod uri;
|
mod uri;
|
||||||
|
|
||||||
use actix_rt::net::TcpStream;
|
use actix_rt::net::TcpStream;
|
||||||
use actix_service::{Service, ServiceFactory};
|
use actix_service::{pipeline, pipeline_factory, Service, ServiceFactory};
|
||||||
|
|
||||||
pub use self::connect::{Address, Connect, Connection};
|
pub use self::connect::{Address, Connect, Connection};
|
||||||
pub use self::connector::{TcpConnector, TcpConnectorFactory};
|
pub use self::connector::{TcpConnector, TcpConnectorFactory};
|
||||||
pub use self::error::ConnectError;
|
pub use self::error::ConnectError;
|
||||||
pub use self::resolve::{Resolve, Resolver, ResolverFactory};
|
pub use self::resolve::{Resolve, Resolver, ResolverFactory};
|
||||||
pub use self::service::{ConnectService, ConnectServiceFactory};
|
pub use self::service::{ConnectService, ConnectServiceFactory, TcpConnectService};
|
||||||
|
|
||||||
/// Create TCP connector service.
|
/// Create TCP connector service.
|
||||||
pub fn new_connector<T: Address + 'static>(
|
pub fn new_connector<T: Address + 'static>(
|
||||||
resolver: Resolver,
|
resolver: Resolver,
|
||||||
) -> impl Service<Connect<T>, Response = Connection<T, TcpStream>, Error = ConnectError> + Clone
|
) -> impl Service<Connect<T>, Response = Connection<T, TcpStream>, Error = ConnectError> + Clone
|
||||||
{
|
{
|
||||||
ConnectServiceFactory::new(resolver).service()
|
pipeline(resolver).and_then(TcpConnector)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create TCP connector service factory.
|
/// Create TCP connector service factory.
|
||||||
@@ -52,7 +52,7 @@ pub fn new_connector_factory<T: Address + 'static>(
|
|||||||
Error = ConnectError,
|
Error = ConnectError,
|
||||||
InitError = (),
|
InitError = (),
|
||||||
> + Clone {
|
> + Clone {
|
||||||
ConnectServiceFactory::new(resolver)
|
pipeline_factory(ResolverFactory::new(resolver)).and_then(TcpConnectorFactory)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create connector service with default parameters.
|
/// Create connector service with default parameters.
|
||||||
|
@@ -34,6 +34,14 @@ impl ConnectServiceFactory {
|
|||||||
resolver: self.resolver.service(),
|
resolver: self.resolver.service(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Construct new tcp stream service
|
||||||
|
pub fn tcp_service(&self) -> TcpConnectService {
|
||||||
|
TcpConnectService {
|
||||||
|
tcp: self.tcp.service(),
|
||||||
|
resolver: self.resolver.service(),
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Clone for ConnectServiceFactory {
|
impl Clone for ConnectServiceFactory {
|
||||||
@@ -55,7 +63,7 @@ impl<T: Address> ServiceFactory<Connect<T>> for ConnectServiceFactory {
|
|||||||
|
|
||||||
fn new_service(&self, _: ()) -> Self::Future {
|
fn new_service(&self, _: ()) -> Self::Future {
|
||||||
let service = self.service();
|
let service = self.service();
|
||||||
Box::pin(async { Ok(service) })
|
Box::pin(async move { Ok(service) })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -127,3 +135,44 @@ impl<T: Address> Future for ConnectServiceResponse<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct TcpConnectService {
|
||||||
|
tcp: TcpConnector,
|
||||||
|
resolver: Resolver,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Address> Service<Connect<T>> for TcpConnectService {
|
||||||
|
type Response = TcpStream;
|
||||||
|
type Error = ConnectError;
|
||||||
|
type Future = TcpConnectServiceResponse<T>;
|
||||||
|
|
||||||
|
actix_service::always_ready!();
|
||||||
|
|
||||||
|
fn call(&self, req: Connect<T>) -> Self::Future {
|
||||||
|
TcpConnectServiceResponse {
|
||||||
|
fut: ConnectFuture::Resolve(self.resolver.call(req)),
|
||||||
|
tcp: self.tcp,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct TcpConnectServiceResponse<T: Address> {
|
||||||
|
fut: ConnectFuture<T>,
|
||||||
|
tcp: TcpConnector,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Address> Future for TcpConnectServiceResponse<T> {
|
||||||
|
type Output = Result<TcpStream, ConnectError>;
|
||||||
|
|
||||||
|
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||||
|
loop {
|
||||||
|
match ready!(self.fut.poll_connect(cx))? {
|
||||||
|
ConnectOutput::Resolved(res) => {
|
||||||
|
self.fut = ConnectFuture::Connect(self.tcp.call(res));
|
||||||
|
}
|
||||||
|
ConnectOutput::Connected(conn) => return Poll::Ready(Ok(conn.into_parts().0)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@@ -5,6 +5,3 @@ pub mod openssl;
|
|||||||
|
|
||||||
#[cfg(feature = "rustls")]
|
#[cfg(feature = "rustls")]
|
||||||
pub mod rustls;
|
pub mod rustls;
|
||||||
|
|
||||||
#[cfg(feature = "native-tls")]
|
|
||||||
pub mod native_tls;
|
|
||||||
|
@@ -1,88 +0,0 @@
|
|||||||
use std::io;
|
|
||||||
|
|
||||||
use actix_rt::net::ActixStream;
|
|
||||||
use actix_service::{Service, ServiceFactory};
|
|
||||||
use futures_core::future::LocalBoxFuture;
|
|
||||||
use log::trace;
|
|
||||||
use tokio_native_tls::{TlsConnector as TokioNativetlsConnector, TlsStream};
|
|
||||||
|
|
||||||
pub use tokio_native_tls::native_tls::TlsConnector;
|
|
||||||
|
|
||||||
use crate::connect::{Address, Connection};
|
|
||||||
|
|
||||||
/// Native-tls connector factory and service
|
|
||||||
pub struct NativetlsConnector {
|
|
||||||
connector: TokioNativetlsConnector,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl NativetlsConnector {
|
|
||||||
pub fn new(connector: TlsConnector) -> Self {
|
|
||||||
Self {
|
|
||||||
connector: TokioNativetlsConnector::from(connector),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl NativetlsConnector {
|
|
||||||
pub fn service(connector: TlsConnector) -> Self {
|
|
||||||
Self::new(connector)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Clone for NativetlsConnector {
|
|
||||||
fn clone(&self) -> Self {
|
|
||||||
Self {
|
|
||||||
connector: self.connector.clone(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: Address, U> ServiceFactory<Connection<T, U>> for NativetlsConnector
|
|
||||||
where
|
|
||||||
U: ActixStream + 'static,
|
|
||||||
{
|
|
||||||
type Response = Connection<T, TlsStream<U>>;
|
|
||||||
type Error = io::Error;
|
|
||||||
type Config = ();
|
|
||||||
type Service = Self;
|
|
||||||
type InitError = ();
|
|
||||||
type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>;
|
|
||||||
|
|
||||||
fn new_service(&self, _: ()) -> Self::Future {
|
|
||||||
let connector = self.clone();
|
|
||||||
Box::pin(async { Ok(connector) })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// NativetlsConnector is both it's ServiceFactory and Service impl type.
|
|
||||||
// As the factory and service share the same type and state.
|
|
||||||
impl<T, U> Service<Connection<T, U>> for NativetlsConnector
|
|
||||||
where
|
|
||||||
T: Address,
|
|
||||||
U: ActixStream + 'static,
|
|
||||||
{
|
|
||||||
type Response = Connection<T, TlsStream<U>>;
|
|
||||||
type Error = io::Error;
|
|
||||||
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
|
|
||||||
|
|
||||||
actix_service::always_ready!();
|
|
||||||
|
|
||||||
fn call(&self, stream: Connection<T, U>) -> Self::Future {
|
|
||||||
let (io, stream) = stream.replace_io(());
|
|
||||||
let connector = self.connector.clone();
|
|
||||||
Box::pin(async move {
|
|
||||||
trace!("SSL Handshake start for: {:?}", stream.host());
|
|
||||||
connector
|
|
||||||
.connect(stream.host(), io)
|
|
||||||
.await
|
|
||||||
.map(|res| {
|
|
||||||
trace!("SSL Handshake success: {:?}", stream.host());
|
|
||||||
stream.replace_io(res).1
|
|
||||||
})
|
|
||||||
.map_err(|e| {
|
|
||||||
trace!("SSL Handshake error: {:?}", e);
|
|
||||||
io::Error::new(io::ErrorKind::Other, format!("{}", e))
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,11 +1,13 @@
|
|||||||
use std::{
|
use std::{
|
||||||
|
fmt,
|
||||||
future::Future,
|
future::Future,
|
||||||
io,
|
io,
|
||||||
pin::Pin,
|
pin::Pin,
|
||||||
task::{Context, Poll},
|
task::{Context, Poll},
|
||||||
};
|
};
|
||||||
|
|
||||||
use actix_rt::net::ActixStream;
|
use actix_codec::{AsyncRead, AsyncWrite};
|
||||||
|
use actix_rt::net::TcpStream;
|
||||||
use actix_service::{Service, ServiceFactory};
|
use actix_service::{Service, ServiceFactory};
|
||||||
use futures_core::{future::LocalBoxFuture, ready};
|
use futures_core::{future::LocalBoxFuture, ready};
|
||||||
use log::trace;
|
use log::trace;
|
||||||
@@ -13,7 +15,10 @@ use log::trace;
|
|||||||
pub use openssl::ssl::{Error as SslError, HandshakeError, SslConnector, SslMethod};
|
pub use openssl::ssl::{Error as SslError, HandshakeError, SslConnector, SslMethod};
|
||||||
pub use tokio_openssl::SslStream;
|
pub use tokio_openssl::SslStream;
|
||||||
|
|
||||||
use crate::connect::{Address, Connection};
|
use crate::connect::resolve::Resolve;
|
||||||
|
use crate::connect::{
|
||||||
|
Address, Connect, ConnectError, ConnectService, ConnectServiceFactory, Connection, Resolver,
|
||||||
|
};
|
||||||
|
|
||||||
/// OpenSSL connector factory
|
/// OpenSSL connector factory
|
||||||
pub struct OpensslConnector {
|
pub struct OpensslConnector {
|
||||||
@@ -40,8 +45,8 @@ impl Clone for OpensslConnector {
|
|||||||
|
|
||||||
impl<T, U> ServiceFactory<Connection<T, U>> for OpensslConnector
|
impl<T, U> ServiceFactory<Connection<T, U>> for OpensslConnector
|
||||||
where
|
where
|
||||||
T: Address,
|
T: Address + 'static,
|
||||||
U: ActixStream + 'static,
|
U: AsyncRead + AsyncWrite + Unpin + fmt::Debug + 'static,
|
||||||
{
|
{
|
||||||
type Response = Connection<T, SslStream<U>>;
|
type Response = Connection<T, SslStream<U>>;
|
||||||
type Error = io::Error;
|
type Error = io::Error;
|
||||||
@@ -70,8 +75,8 @@ impl Clone for OpensslConnectorService {
|
|||||||
|
|
||||||
impl<T, U> Service<Connection<T, U>> for OpensslConnectorService
|
impl<T, U> Service<Connection<T, U>> for OpensslConnectorService
|
||||||
where
|
where
|
||||||
T: Address,
|
T: Address + 'static,
|
||||||
U: ActixStream,
|
U: AsyncRead + AsyncWrite + Unpin + fmt::Debug + 'static,
|
||||||
{
|
{
|
||||||
type Response = Connection<T, SslStream<U>>;
|
type Response = Connection<T, SslStream<U>>;
|
||||||
type Error = io::Error;
|
type Error = io::Error;
|
||||||
@@ -107,8 +112,7 @@ pub struct ConnectAsyncExt<T, U> {
|
|||||||
|
|
||||||
impl<T: Address, U> Future for ConnectAsyncExt<T, U>
|
impl<T: Address, U> Future for ConnectAsyncExt<T, U>
|
||||||
where
|
where
|
||||||
T: Address,
|
U: AsyncRead + AsyncWrite + Unpin + fmt::Debug + 'static,
|
||||||
U: ActixStream,
|
|
||||||
{
|
{
|
||||||
type Output = Result<Connection<T, SslStream<U>>, io::Error>;
|
type Output = Result<Connection<T, SslStream<U>>, io::Error>;
|
||||||
|
|
||||||
@@ -128,3 +132,115 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub struct OpensslConnectServiceFactory {
|
||||||
|
tcp: ConnectServiceFactory,
|
||||||
|
openssl: OpensslConnector,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OpensslConnectServiceFactory {
|
||||||
|
/// Construct new OpensslConnectService factory
|
||||||
|
pub fn new(connector: SslConnector) -> Self {
|
||||||
|
OpensslConnectServiceFactory {
|
||||||
|
tcp: ConnectServiceFactory::new(Resolver::Default),
|
||||||
|
openssl: OpensslConnector::new(connector),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Construct new connect service with custom DNS resolver
|
||||||
|
pub fn with_resolver(connector: SslConnector, resolver: impl Resolve + 'static) -> Self {
|
||||||
|
OpensslConnectServiceFactory {
|
||||||
|
tcp: ConnectServiceFactory::new(Resolver::new_custom(resolver)),
|
||||||
|
openssl: OpensslConnector::new(connector),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Construct OpenSSL connect service
|
||||||
|
pub fn service(&self) -> OpensslConnectService {
|
||||||
|
OpensslConnectService {
|
||||||
|
tcp: self.tcp.service(),
|
||||||
|
openssl: OpensslConnectorService {
|
||||||
|
connector: self.openssl.connector.clone(),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Clone for OpensslConnectServiceFactory {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
OpensslConnectServiceFactory {
|
||||||
|
tcp: self.tcp.clone(),
|
||||||
|
openssl: self.openssl.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Address + 'static> ServiceFactory<Connect<T>> for OpensslConnectServiceFactory {
|
||||||
|
type Response = SslStream<TcpStream>;
|
||||||
|
type Error = ConnectError;
|
||||||
|
type Config = ();
|
||||||
|
type Service = OpensslConnectService;
|
||||||
|
type InitError = ();
|
||||||
|
type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>;
|
||||||
|
|
||||||
|
fn new_service(&self, _: ()) -> Self::Future {
|
||||||
|
let service = self.service();
|
||||||
|
Box::pin(async { Ok(service) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct OpensslConnectService {
|
||||||
|
tcp: ConnectService,
|
||||||
|
openssl: OpensslConnectorService,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Address + 'static> Service<Connect<T>> for OpensslConnectService {
|
||||||
|
type Response = SslStream<TcpStream>;
|
||||||
|
type Error = ConnectError;
|
||||||
|
type Future = OpensslConnectServiceResponse<T>;
|
||||||
|
|
||||||
|
actix_service::always_ready!();
|
||||||
|
|
||||||
|
fn call(&self, req: Connect<T>) -> Self::Future {
|
||||||
|
OpensslConnectServiceResponse {
|
||||||
|
fut1: Some(self.tcp.call(req)),
|
||||||
|
fut2: None,
|
||||||
|
openssl: self.openssl.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct OpensslConnectServiceResponse<T: Address + 'static> {
|
||||||
|
fut1: Option<<ConnectService as Service<Connect<T>>>::Future>,
|
||||||
|
fut2: Option<<OpensslConnectorService as Service<Connection<T, TcpStream>>>::Future>,
|
||||||
|
openssl: OpensslConnectorService,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Address> Future for OpensslConnectServiceResponse<T> {
|
||||||
|
type Output = Result<SslStream<TcpStream>, ConnectError>;
|
||||||
|
|
||||||
|
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||||
|
if let Some(ref mut fut) = self.fut1 {
|
||||||
|
match ready!(Pin::new(fut).poll(cx)) {
|
||||||
|
Ok(res) => {
|
||||||
|
let _ = self.fut1.take();
|
||||||
|
self.fut2 = Some(self.openssl.call(res));
|
||||||
|
}
|
||||||
|
Err(e) => return Poll::Ready(Err(e)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(ref mut fut) = self.fut2 {
|
||||||
|
match ready!(Pin::new(fut).poll(cx)) {
|
||||||
|
Ok(connect) => Poll::Ready(Ok(connect.into_parts().0)),
|
||||||
|
Err(e) => Poll::Ready(Err(ConnectError::Io(io::Error::new(
|
||||||
|
io::ErrorKind::Other,
|
||||||
|
e,
|
||||||
|
)))),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Poll::Pending
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
use std::{
|
use std::{
|
||||||
|
fmt,
|
||||||
future::Future,
|
future::Future,
|
||||||
io,
|
|
||||||
pin::Pin,
|
pin::Pin,
|
||||||
sync::Arc,
|
sync::Arc,
|
||||||
task::{Context, Poll},
|
task::{Context, Poll},
|
||||||
@@ -10,7 +10,7 @@ pub use tokio_rustls::rustls::Session;
|
|||||||
pub use tokio_rustls::{client::TlsStream, rustls::ClientConfig};
|
pub use tokio_rustls::{client::TlsStream, rustls::ClientConfig};
|
||||||
pub use webpki_roots::TLS_SERVER_ROOTS;
|
pub use webpki_roots::TLS_SERVER_ROOTS;
|
||||||
|
|
||||||
use actix_rt::net::ActixStream;
|
use actix_codec::{AsyncRead, AsyncWrite};
|
||||||
use actix_service::{Service, ServiceFactory};
|
use actix_service::{Service, ServiceFactory};
|
||||||
use futures_core::{future::LocalBoxFuture, ready};
|
use futures_core::{future::LocalBoxFuture, ready};
|
||||||
use log::trace;
|
use log::trace;
|
||||||
@@ -44,13 +44,12 @@ impl Clone for RustlsConnector {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, U> ServiceFactory<Connection<T, U>> for RustlsConnector
|
impl<T: Address, U> ServiceFactory<Connection<T, U>> for RustlsConnector
|
||||||
where
|
where
|
||||||
T: Address,
|
U: AsyncRead + AsyncWrite + Unpin + fmt::Debug,
|
||||||
U: ActixStream + 'static,
|
|
||||||
{
|
{
|
||||||
type Response = Connection<T, TlsStream<U>>;
|
type Response = Connection<T, TlsStream<U>>;
|
||||||
type Error = io::Error;
|
type Error = std::io::Error;
|
||||||
type Config = ();
|
type Config = ();
|
||||||
type Service = RustlsConnectorService;
|
type Service = RustlsConnectorService;
|
||||||
type InitError = ();
|
type InitError = ();
|
||||||
@@ -77,55 +76,43 @@ impl Clone for RustlsConnectorService {
|
|||||||
impl<T, U> Service<Connection<T, U>> for RustlsConnectorService
|
impl<T, U> Service<Connection<T, U>> for RustlsConnectorService
|
||||||
where
|
where
|
||||||
T: Address,
|
T: Address,
|
||||||
U: ActixStream,
|
U: AsyncRead + AsyncWrite + Unpin + fmt::Debug,
|
||||||
{
|
{
|
||||||
type Response = Connection<T, TlsStream<U>>;
|
type Response = Connection<T, TlsStream<U>>;
|
||||||
type Error = io::Error;
|
type Error = std::io::Error;
|
||||||
type Future = RustlsConnectorServiceFuture<T, U>;
|
type Future = ConnectAsyncExt<T, U>;
|
||||||
|
|
||||||
actix_service::always_ready!();
|
actix_service::always_ready!();
|
||||||
|
|
||||||
fn call(&self, connection: Connection<T, U>) -> Self::Future {
|
fn call(&self, stream: Connection<T, U>) -> Self::Future {
|
||||||
trace!("SSL Handshake start for: {:?}", connection.host());
|
trace!("SSL Handshake start for: {:?}", stream.host());
|
||||||
let (stream, connection) = connection.replace_io(());
|
let (io, stream) = stream.replace_io(());
|
||||||
|
let host = DNSNameRef::try_from_ascii_str(stream.host())
|
||||||
match DNSNameRef::try_from_ascii_str(connection.host()) {
|
.expect("rustls currently only handles hostname-based connections. See https://github.com/briansmith/webpki/issues/54");
|
||||||
Ok(host) => RustlsConnectorServiceFuture::Future {
|
ConnectAsyncExt {
|
||||||
connect: TlsConnector::from(self.connector.clone()).connect(host, stream),
|
fut: TlsConnector::from(self.connector.clone()).connect(host, io),
|
||||||
connection: Some(connection),
|
stream: Some(stream),
|
||||||
},
|
|
||||||
Err(_) => RustlsConnectorServiceFuture::InvalidDns,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub enum RustlsConnectorServiceFuture<T, U> {
|
pub struct ConnectAsyncExt<T, U> {
|
||||||
/// See issue https://github.com/briansmith/webpki/issues/54
|
fut: Connect<U>,
|
||||||
InvalidDns,
|
stream: Option<Connection<T, ()>>,
|
||||||
Future {
|
|
||||||
connect: Connect<U>,
|
|
||||||
connection: Option<Connection<T, ()>>,
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, U> Future for RustlsConnectorServiceFuture<T, U>
|
impl<T, U> Future for ConnectAsyncExt<T, U>
|
||||||
where
|
where
|
||||||
T: Address,
|
T: Address,
|
||||||
U: ActixStream,
|
U: AsyncRead + AsyncWrite + Unpin + fmt::Debug,
|
||||||
{
|
{
|
||||||
type Output = Result<Connection<T, TlsStream<U>>, io::Error>;
|
type Output = Result<Connection<T, TlsStream<U>>, std::io::Error>;
|
||||||
|
|
||||||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||||
match self.get_mut() {
|
let this = self.get_mut();
|
||||||
Self::InvalidDns => Poll::Ready(Err(
|
let stream = ready!(Pin::new(&mut this.fut).poll(cx))?;
|
||||||
io::Error::new(io::ErrorKind::Other, "rustls currently only handles hostname-based connections. See https://github.com/briansmith/webpki/issues/54")
|
let s = this.stream.take().unwrap();
|
||||||
)),
|
trace!("SSL Handshake success: {:?}", s.host());
|
||||||
Self::Future { connect, connection } => {
|
Poll::Ready(Ok(s.replace_io(stream).1))
|
||||||
let stream = ready!(Pin::new(connect).poll(cx))?;
|
|
||||||
let connection = connection.take().unwrap();
|
|
||||||
trace!("SSL Handshake success: {:?}", connection.host());
|
|
||||||
Poll::Ready(Ok(connection.replace_io(stream).1))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -16,7 +16,7 @@ name = "actix_tracing"
|
|||||||
path = "src/lib.rs"
|
path = "src/lib.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-service = "2.0.0-beta.5"
|
actix-service = "2.0.0-beta.4"
|
||||||
|
|
||||||
futures-util = { version = "0.3.4", default-features = false }
|
futures-util = { version = "0.3.4", default-features = false }
|
||||||
tracing = "0.1"
|
tracing = "0.1"
|
||||||
|
@@ -7,7 +7,7 @@
|
|||||||
use core::marker::PhantomData;
|
use core::marker::PhantomData;
|
||||||
|
|
||||||
use actix_service::{
|
use actix_service::{
|
||||||
apply, ApplyTransform, IntoServiceFactory, Service, ServiceFactory, Transform,
|
apply, dev::ApplyTransform, IntoServiceFactory, Service, ServiceFactory, Transform,
|
||||||
};
|
};
|
||||||
use futures_util::future::{ok, Either, Ready};
|
use futures_util::future::{ok, Either, Ready};
|
||||||
use tracing_futures::{Instrument, Instrumented};
|
use tracing_futures::{Instrument, Instrumented};
|
||||||
|
@@ -1,15 +1,6 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
## Unreleased - 2021-xx-xx
|
## Unreleased - 2021-xx-xx
|
||||||
* Add `async fn mpsc::Receiver::recv`. [#286]
|
|
||||||
* `SendError` inner field is now public. [#286]
|
|
||||||
* Rename `Dispatcher::{get_sink => tx}`. [#286]
|
|
||||||
* Rename `Dispatcher::{get_ref => service}`. [#286]
|
|
||||||
* Rename `Dispatcher::{get_mut => service_mut}`. [#286]
|
|
||||||
* Rename `Dispatcher::{get_framed => framed}`. [#286]
|
|
||||||
* Rename `Dispatcher::{get_framed_mut => framed_mut}`. [#286]
|
|
||||||
|
|
||||||
[#286]: https://github.com/actix/actix-net/pull/286
|
|
||||||
|
|
||||||
|
|
||||||
## 3.0.0-beta.2 - 2021-02-06
|
## 3.0.0-beta.2 - 2021-02-06
|
||||||
|
@@ -18,12 +18,13 @@ path = "src/lib.rs"
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
actix-codec = "0.4.0-beta.1"
|
actix-codec = "0.4.0-beta.1"
|
||||||
actix-rt = { version = "2.0.0", default-features = false }
|
actix-rt = { version = "2.0.0", default-features = false }
|
||||||
actix-service = "2.0.0-beta.5"
|
actix-service = "2.0.0-beta.4"
|
||||||
|
|
||||||
futures-core = { version = "0.3.7", default-features = false }
|
futures-core = { version = "0.3.7", default-features = false }
|
||||||
futures-sink = { version = "0.3.7", default-features = false }
|
futures-sink = { version = "0.3.7", default-features = false }
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
pin-project-lite = "0.2.0"
|
pin-project-lite = "0.2.0"
|
||||||
|
tokio = { version = "1", features = ["sync"] }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-rt = "2.0.0"
|
actix-rt = "2.0.0"
|
||||||
|
@@ -1,21 +1,20 @@
|
|||||||
//! Framed dispatcher service and related utilities.
|
//! Framed dispatcher service and related utilities.
|
||||||
|
|
||||||
#![allow(type_alias_bounds)]
|
use core::{
|
||||||
|
fmt,
|
||||||
use core::future::Future;
|
future::Future,
|
||||||
use core::pin::Pin;
|
mem,
|
||||||
use core::task::{Context, Poll};
|
pin::Pin,
|
||||||
use core::{fmt, mem};
|
task::{Context, Poll},
|
||||||
|
};
|
||||||
|
|
||||||
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
|
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
|
||||||
use actix_service::{IntoService, Service};
|
use actix_service::{IntoService, Service};
|
||||||
use futures_core::stream::Stream;
|
|
||||||
use log::debug;
|
use log::debug;
|
||||||
use pin_project_lite::pin_project;
|
use pin_project_lite::pin_project;
|
||||||
|
use tokio::sync::mpsc;
|
||||||
|
|
||||||
use crate::mpsc;
|
/// Framed transport errors.
|
||||||
|
|
||||||
/// Framed transport errors
|
|
||||||
pub enum DispatcherError<E, U: Encoder<I> + Decoder, I> {
|
pub enum DispatcherError<E, U: Encoder<I> + Decoder, I> {
|
||||||
Service(E),
|
Service(E),
|
||||||
Encoder(<U as Encoder<I>>::Error),
|
Encoder(<U as Encoder<I>>::Error),
|
||||||
@@ -64,8 +63,7 @@ pub enum Message<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pin_project! {
|
pin_project! {
|
||||||
/// Dispatcher is a future that reads frames from Framed object
|
/// Dispatcher is a future that reads frames from Framed object and passes them to the service.
|
||||||
/// and passes them to the service.
|
|
||||||
pub struct Dispatcher<S, T, U, I>
|
pub struct Dispatcher<S, T, U, I>
|
||||||
where
|
where
|
||||||
S: Service<<U as Decoder>::Item, Response = I>,
|
S: Service<<U as Decoder>::Item, Response = I>,
|
||||||
@@ -82,8 +80,8 @@ pin_project! {
|
|||||||
state: State<S, U, I>,
|
state: State<S, U, I>,
|
||||||
#[pin]
|
#[pin]
|
||||||
framed: Framed<T, U>,
|
framed: Framed<T, U>,
|
||||||
rx: mpsc::Receiver<Result<Message<I>, S::Error>>,
|
rx: mpsc::UnboundedReceiver<Result<Message<I>, S::Error>>,
|
||||||
tx: mpsc::Sender<Result<Message<I>, S::Error>>,
|
tx: mpsc::UnboundedSender<Result<Message<I>, S::Error>>,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,7 +132,7 @@ where
|
|||||||
where
|
where
|
||||||
F: IntoService<S, <U as Decoder>::Item>,
|
F: IntoService<S, <U as Decoder>::Item>,
|
||||||
{
|
{
|
||||||
let (tx, rx) = mpsc::channel();
|
let (tx, rx) = mpsc::unbounded_channel();
|
||||||
Dispatcher {
|
Dispatcher {
|
||||||
framed,
|
framed,
|
||||||
rx,
|
rx,
|
||||||
@@ -144,27 +142,8 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Construct new `Dispatcher` instance with customer `mpsc::Receiver`
|
/// Get sink
|
||||||
pub fn with_rx<F>(
|
pub fn tx(&self) -> mpsc::UnboundedSender<Result<Message<I>, S::Error>> {
|
||||||
framed: Framed<T, U>,
|
|
||||||
service: F,
|
|
||||||
rx: mpsc::Receiver<Result<Message<I>, S::Error>>,
|
|
||||||
) -> Self
|
|
||||||
where
|
|
||||||
F: IntoService<S, <U as Decoder>::Item>,
|
|
||||||
{
|
|
||||||
let tx = rx.sender();
|
|
||||||
Dispatcher {
|
|
||||||
framed,
|
|
||||||
rx,
|
|
||||||
tx,
|
|
||||||
service: service.into_service(),
|
|
||||||
state: State::Processing,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get sender handle.
|
|
||||||
pub fn tx(&self) -> mpsc::Sender<Result<Message<I>, S::Error>> {
|
|
||||||
self.tx.clone()
|
self.tx.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -178,7 +157,8 @@ where
|
|||||||
&mut self.service
|
&mut self.service
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get reference to a framed instance wrapped by `Dispatcher` instance.
|
/// Get reference to a framed instance wrapped by `Dispatcher`
|
||||||
|
/// instance.
|
||||||
pub fn framed(&self) -> &Framed<T, U> {
|
pub fn framed(&self) -> &Framed<T, U> {
|
||||||
&self.framed
|
&self.framed
|
||||||
}
|
}
|
||||||
@@ -245,7 +225,7 @@ where
|
|||||||
loop {
|
loop {
|
||||||
let mut this = self.as_mut().project();
|
let mut this = self.as_mut().project();
|
||||||
while !this.framed.is_write_buf_full() {
|
while !this.framed.is_write_buf_full() {
|
||||||
match Pin::new(&mut this.rx).poll_next(cx) {
|
match this.rx.poll_recv(cx) {
|
||||||
Poll::Ready(Some(Ok(Message::Item(msg)))) => {
|
Poll::Ready(Some(Ok(Message::Item(msg)))) => {
|
||||||
if let Err(err) = this.framed.as_mut().write(msg) {
|
if let Err(err) = this.framed.as_mut().write(msg) {
|
||||||
*this.state = State::FramedError(DispatcherError::Encoder(err));
|
*this.state = State::FramedError(DispatcherError::Encoder(err));
|
||||||
@@ -265,9 +245,9 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
if !this.framed.is_write_buf_empty() {
|
if !this.framed.is_write_buf_empty() {
|
||||||
match this.framed.flush(cx) {
|
match this.framed.poll_flush(cx) {
|
||||||
Poll::Pending => break,
|
Poll::Pending => break,
|
||||||
Poll::Ready(Ok(_)) => {}
|
Poll::Ready(Ok(_)) => (),
|
||||||
Poll::Ready(Err(err)) => {
|
Poll::Ready(Err(err)) => {
|
||||||
debug!("Error sending data: {:?}", err);
|
debug!("Error sending data: {:?}", err);
|
||||||
*this.state = State::FramedError(DispatcherError::Encoder(err));
|
*this.state = State::FramedError(DispatcherError::Encoder(err));
|
||||||
@@ -297,40 +277,43 @@ where
|
|||||||
type Output = Result<(), DispatcherError<S::Error, U, I>>;
|
type Output = Result<(), DispatcherError<S::Error, U, I>>;
|
||||||
|
|
||||||
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> {
|
||||||
loop {
|
let this = self.as_mut().project();
|
||||||
let this = self.as_mut().project();
|
|
||||||
|
|
||||||
return match this.state {
|
match this.state {
|
||||||
State::Processing => {
|
State::Processing => {
|
||||||
if self.as_mut().poll_read(cx) || self.as_mut().poll_write(cx) {
|
if self.as_mut().poll_read(cx) || self.as_mut().poll_write(cx) {
|
||||||
continue;
|
self.poll(cx)
|
||||||
} else {
|
} else {
|
||||||
Poll::Pending
|
Poll::Pending
|
||||||
}
|
|
||||||
}
|
}
|
||||||
State::Error(_) => {
|
}
|
||||||
// flush write buffer
|
|
||||||
if !this.framed.is_write_buf_empty() && this.framed.flush(cx).is_pending() {
|
|
||||||
return Poll::Pending;
|
|
||||||
}
|
|
||||||
Poll::Ready(Err(this.state.take_error()))
|
|
||||||
}
|
|
||||||
State::FlushAndStop => {
|
|
||||||
if !this.framed.is_write_buf_empty() {
|
|
||||||
this.framed.flush(cx).map(|res| {
|
|
||||||
if let Err(err) = res {
|
|
||||||
debug!("Error sending data: {:?}", err);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
State::Error(_) => {
|
||||||
})
|
// flush write buffer
|
||||||
} else {
|
if !this.framed.is_write_buf_empty() && this.framed.poll_flush(cx).is_pending()
|
||||||
Poll::Ready(Ok(()))
|
{
|
||||||
}
|
return Poll::Pending;
|
||||||
}
|
}
|
||||||
State::FramedError(_) => Poll::Ready(Err(this.state.take_framed_error())),
|
|
||||||
State::Stopping => Poll::Ready(Ok(())),
|
Poll::Ready(Err(this.state.take_error()))
|
||||||
};
|
}
|
||||||
|
|
||||||
|
State::FlushAndStop => {
|
||||||
|
if !this.framed.is_write_buf_empty() {
|
||||||
|
this.framed.poll_flush(cx).map(|res| {
|
||||||
|
if let Err(err) = res {
|
||||||
|
debug!("Error sending data: {:?}", err);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
Poll::Ready(Ok(()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
State::FramedError(_) => Poll::Ready(Err(this.state.take_framed_error())),
|
||||||
|
State::Stopping => Poll::Ready(Ok(())),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -7,9 +7,5 @@
|
|||||||
|
|
||||||
pub mod counter;
|
pub mod counter;
|
||||||
pub mod dispatcher;
|
pub mod dispatcher;
|
||||||
pub mod mpsc;
|
|
||||||
mod poll_fn;
|
|
||||||
pub mod task;
|
pub mod task;
|
||||||
pub mod timeout;
|
pub mod timeout;
|
||||||
|
|
||||||
use self::poll_fn::poll_fn;
|
|
||||||
|
@@ -1,253 +0,0 @@
|
|||||||
//! A multi-producer, single-consumer, futures-aware, FIFO queue.
|
|
||||||
|
|
||||||
use core::{
|
|
||||||
cell::RefCell,
|
|
||||||
fmt,
|
|
||||||
pin::Pin,
|
|
||||||
task::{Context, Poll},
|
|
||||||
};
|
|
||||||
|
|
||||||
use std::{collections::VecDeque, error::Error, rc::Rc};
|
|
||||||
|
|
||||||
use futures_core::stream::Stream;
|
|
||||||
use futures_sink::Sink;
|
|
||||||
|
|
||||||
use crate::{poll_fn, task::LocalWaker};
|
|
||||||
|
|
||||||
/// Creates a unbounded in-memory channel with buffered storage.
|
|
||||||
///
|
|
||||||
/// [Sender]s and [Receiver]s are `!Send`.
|
|
||||||
pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
|
|
||||||
let shared = Rc::new(RefCell::new(Shared {
|
|
||||||
has_receiver: true,
|
|
||||||
buffer: VecDeque::new(),
|
|
||||||
blocked_recv: LocalWaker::new(),
|
|
||||||
}));
|
|
||||||
|
|
||||||
let sender = Sender {
|
|
||||||
shared: shared.clone(),
|
|
||||||
};
|
|
||||||
|
|
||||||
let receiver = Receiver { shared };
|
|
||||||
|
|
||||||
(sender, receiver)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
struct Shared<T> {
|
|
||||||
buffer: VecDeque<T>,
|
|
||||||
blocked_recv: LocalWaker,
|
|
||||||
has_receiver: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The transmission end of a channel.
|
|
||||||
///
|
|
||||||
/// This is created by the `channel` function.
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct Sender<T> {
|
|
||||||
shared: Rc<RefCell<Shared<T>>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> Unpin for Sender<T> {}
|
|
||||||
|
|
||||||
impl<T> Sender<T> {
|
|
||||||
/// Sends the provided message along this channel.
|
|
||||||
pub fn send(&self, item: T) -> Result<(), SendError<T>> {
|
|
||||||
let mut shared = self.shared.borrow_mut();
|
|
||||||
|
|
||||||
if !shared.has_receiver {
|
|
||||||
// receiver was dropped
|
|
||||||
return Err(SendError(item));
|
|
||||||
};
|
|
||||||
|
|
||||||
shared.buffer.push_back(item);
|
|
||||||
shared.blocked_recv.wake();
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Closes the sender half.
|
|
||||||
///
|
|
||||||
/// This prevents any further messages from being sent on the channel, by any sender, while
|
|
||||||
/// still enabling the receiver to drain messages that are already buffered.
|
|
||||||
pub fn close(&mut self) {
|
|
||||||
self.shared.borrow_mut().has_receiver = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> Clone for Sender<T> {
|
|
||||||
fn clone(&self) -> Self {
|
|
||||||
Sender {
|
|
||||||
shared: self.shared.clone(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> Sink<T> for Sender<T> {
|
|
||||||
type Error = SendError<T>;
|
|
||||||
|
|
||||||
fn poll_ready(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
|
||||||
Poll::Ready(Ok(()))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn start_send(self: Pin<&mut Self>, item: T) -> Result<(), SendError<T>> {
|
|
||||||
self.send(item)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), SendError<T>>> {
|
|
||||||
Poll::Ready(Ok(()))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
|
||||||
Poll::Ready(Ok(()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> Drop for Sender<T> {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
let count = Rc::strong_count(&self.shared);
|
|
||||||
let shared = self.shared.borrow_mut();
|
|
||||||
|
|
||||||
// check is last sender is about to drop
|
|
||||||
if shared.has_receiver && count == 2 {
|
|
||||||
// Wake up receiver as its stream has ended
|
|
||||||
shared.blocked_recv.wake();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The receiving end of a channel which implements the `Stream` trait.
|
|
||||||
///
|
|
||||||
/// This is created by the [`channel`] function.
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct Receiver<T> {
|
|
||||||
shared: Rc<RefCell<Shared<T>>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> Receiver<T> {
|
|
||||||
/// Receive the next value.
|
|
||||||
///
|
|
||||||
/// Returns `None` if the channel is empty and has been [closed](Sender::close) explicitly or
|
|
||||||
/// when all senders have been dropped and, therefore, no more values can ever be sent though
|
|
||||||
/// this channel.
|
|
||||||
pub async fn recv(&mut self) -> Option<T> {
|
|
||||||
let mut this = Pin::new(self);
|
|
||||||
poll_fn(|cx| this.as_mut().poll_next(cx)).await
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Create an associated [Sender].
|
|
||||||
pub fn sender(&self) -> Sender<T> {
|
|
||||||
Sender {
|
|
||||||
shared: self.shared.clone(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> Unpin for Receiver<T> {}
|
|
||||||
|
|
||||||
impl<T> Stream for Receiver<T> {
|
|
||||||
type Item = T;
|
|
||||||
|
|
||||||
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
|
||||||
let mut shared = self.shared.borrow_mut();
|
|
||||||
|
|
||||||
if Rc::strong_count(&self.shared) == 1 {
|
|
||||||
// All senders have been dropped, so drain the buffer and end the stream.
|
|
||||||
return Poll::Ready(shared.buffer.pop_front());
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(msg) = shared.buffer.pop_front() {
|
|
||||||
Poll::Ready(Some(msg))
|
|
||||||
} else {
|
|
||||||
shared.blocked_recv.register(cx.waker());
|
|
||||||
Poll::Pending
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> Drop for Receiver<T> {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
let mut shared = self.shared.borrow_mut();
|
|
||||||
shared.buffer.clear();
|
|
||||||
shared.has_receiver = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Error returned when attempting to send after the channels' [Receiver] is dropped or closed.
|
|
||||||
pub struct SendError<T>(pub T);
|
|
||||||
|
|
||||||
impl<T> SendError<T> {
|
|
||||||
/// Returns the message that was attempted to be sent but failed.
|
|
||||||
pub fn into_inner(self) -> T {
|
|
||||||
self.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> fmt::Debug for SendError<T> {
|
|
||||||
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
fmt.debug_tuple("SendError").field(&"...").finish()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> fmt::Display for SendError<T> {
|
|
||||||
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
write!(fmt, "send failed because receiver is gone")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> Error for SendError<T> {}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use futures_util::future::lazy;
|
|
||||||
use futures_util::{stream::Stream, StreamExt};
|
|
||||||
|
|
||||||
#[actix_rt::test]
|
|
||||||
async fn test_mpsc() {
|
|
||||||
let (tx, mut rx) = channel();
|
|
||||||
tx.send("test").unwrap();
|
|
||||||
assert_eq!(rx.next().await.unwrap(), "test");
|
|
||||||
|
|
||||||
let tx2 = tx.clone();
|
|
||||||
tx2.send("test2").unwrap();
|
|
||||||
assert_eq!(rx.next().await.unwrap(), "test2");
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
lazy(|cx| Pin::new(&mut rx).poll_next(cx)).await,
|
|
||||||
Poll::Pending
|
|
||||||
);
|
|
||||||
drop(tx2);
|
|
||||||
assert_eq!(
|
|
||||||
lazy(|cx| Pin::new(&mut rx).poll_next(cx)).await,
|
|
||||||
Poll::Pending
|
|
||||||
);
|
|
||||||
drop(tx);
|
|
||||||
assert_eq!(rx.next().await, None);
|
|
||||||
|
|
||||||
let (tx, rx) = channel();
|
|
||||||
tx.send("test").unwrap();
|
|
||||||
drop(rx);
|
|
||||||
assert!(tx.send("test").is_err());
|
|
||||||
|
|
||||||
let (mut tx, _) = channel();
|
|
||||||
let tx2 = tx.clone();
|
|
||||||
tx.close();
|
|
||||||
assert!(tx.send("test").is_err());
|
|
||||||
assert!(tx2.send("test").is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[actix_rt::test]
|
|
||||||
async fn test_recv() {
|
|
||||||
let (tx, mut rx) = channel();
|
|
||||||
tx.send("test").unwrap();
|
|
||||||
assert_eq!(rx.recv().await.unwrap(), "test");
|
|
||||||
drop(tx);
|
|
||||||
|
|
||||||
let (tx, mut rx) = channel();
|
|
||||||
tx.send("test").unwrap();
|
|
||||||
assert_eq!(rx.recv().await.unwrap(), "test");
|
|
||||||
drop(tx);
|
|
||||||
assert!(rx.recv().await.is_none());
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,65 +0,0 @@
|
|||||||
//! Simple "poll function" future and factory.
|
|
||||||
|
|
||||||
use core::{
|
|
||||||
fmt,
|
|
||||||
future::Future,
|
|
||||||
task::{self, Poll},
|
|
||||||
};
|
|
||||||
use std::pin::Pin;
|
|
||||||
|
|
||||||
/// Create a future driven by the provided function that receives a task context.
|
|
||||||
pub(crate) fn poll_fn<F, T>(f: F) -> PollFn<F>
|
|
||||||
where
|
|
||||||
F: FnMut(&mut task::Context<'_>) -> Poll<T>,
|
|
||||||
{
|
|
||||||
PollFn { f }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A Future driven by the inner function.
|
|
||||||
pub(crate) struct PollFn<F> {
|
|
||||||
f: F,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<F> Unpin for PollFn<F> {}
|
|
||||||
|
|
||||||
impl<F> fmt::Debug for PollFn<F> {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
f.debug_struct("PollFn").finish()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<F, T> Future for PollFn<F>
|
|
||||||
where
|
|
||||||
F: FnMut(&mut task::Context<'_>) -> task::Poll<T>,
|
|
||||||
{
|
|
||||||
type Output = T;
|
|
||||||
|
|
||||||
fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
|
|
||||||
(self.f)(cx)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[actix_rt::test]
|
|
||||||
async fn test_poll_fn() {
|
|
||||||
let res = poll_fn(|_| Poll::Ready(42)).await;
|
|
||||||
assert_eq!(res, 42);
|
|
||||||
|
|
||||||
let mut i = 5;
|
|
||||||
let res = poll_fn(|cx| {
|
|
||||||
i -= 1;
|
|
||||||
|
|
||||||
if i > 0 {
|
|
||||||
cx.waker().wake_by_ref();
|
|
||||||
Poll::Pending
|
|
||||||
} else {
|
|
||||||
Poll::Ready(42)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
assert_eq!(res, 42);
|
|
||||||
}
|
|
||||||
}
|
|
@@ -9,14 +9,11 @@ use core::{cell::Cell, fmt, marker::PhantomData, task::Waker};
|
|||||||
/// logical task.
|
/// logical task.
|
||||||
///
|
///
|
||||||
/// Consumers should call [`register`] before checking the result of a computation and producers
|
/// Consumers should call [`register`] before checking the result of a computation and producers
|
||||||
/// should call [`wake`] after producing the computation (this differs from the usual `thread::park`
|
/// should call `wake` after producing the computation (this differs from the usual `thread::park`
|
||||||
/// pattern). It is also permitted for [`wake`] to be called _before_ [`register`]. This results in
|
/// pattern). It is also permitted for [`wake`] to be called _before_ [`register`]. This results in
|
||||||
/// a no-op.
|
/// a no-op.
|
||||||
///
|
///
|
||||||
/// A single `LocalWaker` may be reused for any number of calls to [`register`] or [`wake`].
|
/// A single `LocalWaker` may be reused for any number of calls to [`register`] or [`wake`].
|
||||||
///
|
|
||||||
/// [`register`]: LocalWaker::register
|
|
||||||
/// [`wake`]: LocalWaker::wake
|
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub struct LocalWaker {
|
pub struct LocalWaker {
|
||||||
pub(crate) waker: Cell<Option<Waker>>,
|
pub(crate) waker: Cell<Option<Waker>>,
|
||||||
|
@@ -197,6 +197,7 @@ where
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
|
use core::task::Poll;
|
||||||
use core::time::Duration;
|
use core::time::Duration;
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
Reference in New Issue
Block a user