mirror of
https://github.com/fafhrd91/actix-net
synced 2025-08-14 12:20:30 +02:00
Compare commits
168 Commits
router-v0.
...
testing-v1
Author | SHA1 | Date | |
---|---|---|---|
|
11a1e11858 | ||
|
d0b27ee7e6 | ||
|
2d2b0591a2 | ||
|
abbc5f715f | ||
|
140a6c76e3 | ||
|
2395b28c5e | ||
|
aad4812ba6 | ||
|
ac6c78c476 | ||
|
8218a098e8 | ||
|
49a6f525be | ||
|
f59ff82395 | ||
|
f7cc62564d | ||
|
b125e2bdce | ||
|
a5c185e80e | ||
|
523cee0351 | ||
|
343b3c09fc | ||
|
8a10580663 | ||
|
1b4a117063 | ||
|
700997fe48 | ||
|
4c5568ed70 | ||
|
7d0cfe1b4d | ||
|
e35c261c9f | ||
|
115ef3fcb3 | ||
|
c0482e2532 | ||
|
6906f25e01 | ||
|
06bca19524 | ||
|
e9e2185296 | ||
|
aae52a80ab | ||
|
65e2e8052e | ||
|
783880bb0a | ||
|
69e8df9d62 | ||
|
9addf1a36b | ||
|
187a58472d | ||
|
30aa0b7bb6 | ||
|
e775d08d76 | ||
|
d5f95b54b7 | ||
|
904f90abc2 | ||
|
950c73077c | ||
|
732731a9c8 | ||
|
0dd5a7ce1d | ||
|
7105091e51 | ||
|
08959dfc21 | ||
|
2792433ad6 | ||
|
437a7b05c6 | ||
|
3d125c5381 | ||
|
fbf7d6ef33 | ||
|
e6b6f08369 | ||
|
4e806b3e3f | ||
|
f5b07053fc | ||
|
dd3bec83bf | ||
|
f955e49930 | ||
|
4be11b541b | ||
|
baba533407 | ||
|
2bf50826b0 | ||
|
41b2a3b2e2 | ||
|
7fdd4a1118 | ||
|
cb30f9e86a | ||
|
873f69be51 | ||
|
0967061f30 | ||
|
59902cb3a3 | ||
|
857e50120b | ||
|
36a2edf1cd | ||
|
346bd072d3 | ||
|
8d3d58b3b7 | ||
|
c41b5d8dd4 | ||
|
693d5132a9 | ||
|
f7dac3feb4 | ||
|
ebc11d03f2 | ||
|
e3ad5de270 | ||
|
91118bb2ce | ||
|
6628688bcf | ||
|
b9567359fd | ||
|
7dbc0264b1 | ||
|
1b7c969f6a | ||
|
f1685d8253 | ||
|
e3b6a33b97 | ||
|
13b503435f | ||
|
98f0290f65 | ||
|
b8f66f5e7f | ||
|
dd59ee498e | ||
|
83320efa31 | ||
|
c69bc11e3e | ||
|
aad5c42ad7 | ||
|
4d37858fc6 | ||
|
d402f08bb5 | ||
|
fa25e30427 | ||
|
602db1779e | ||
|
4f2910c6b3 | ||
|
9f7d6bc068 | ||
|
6908b58943 | ||
|
043057ecbd | ||
|
e12bf9200b | ||
|
03d431e663 | ||
|
f0d352604e | ||
|
2f67e4f563 | ||
|
d1155d60ec | ||
|
28d9c6a760 | ||
|
a970c2c997 | ||
|
d5a6c83207 | ||
|
ee0db9a617 | ||
|
e5b5df1261 | ||
|
dbfa13d6be | ||
|
e7c2439543 | ||
|
3116db5168 | ||
|
5940731ef0 | ||
|
aed5fecc8a | ||
|
a751899aad | ||
|
fa800aeba3 | ||
|
2f89483635 | ||
|
3048073919 | ||
|
4bbba803c1 | ||
|
4dcdeb6795 | ||
|
3b4f222242 | ||
|
7c5fa25b23 | ||
|
3551d6674d | ||
|
9f00daea80 | ||
|
7dddeab2a8 | ||
|
dcbcc40da2 | ||
|
b0d44198ba | ||
|
974bd6b01e | ||
|
5779da0f49 | ||
|
1918c8d4f8 | ||
|
e21c58930b | ||
|
59c5e9be6a | ||
|
a2a9d9764d | ||
|
bf0a9d2f6e | ||
|
119027f822 | ||
|
0fe8038d23 | ||
|
b599bc4a0c | ||
|
a80e1f8370 | ||
|
5fe759cc02 | ||
|
05549f0b42 | ||
|
b1430eaded | ||
|
0d3f9e74c5 | ||
|
cab73791ed | ||
|
a7ac1a76ed | ||
|
37bedff6fb | ||
|
33fd6adc11 | ||
|
4305cdba2c | ||
|
52ecb4bcc5 | ||
|
b28f32e82c | ||
|
081205a02f | ||
|
8bb81c0768 | ||
|
c7a8743bf9 | ||
|
f26fcc703b | ||
|
ce4587df82 | ||
|
9957f28137 | ||
|
9d84d14ef4 | ||
|
60bfa1bfb1 | ||
|
2c81c22b3e | ||
|
dded482514 | ||
|
631cb86947 | ||
|
2e5e69c9ba | ||
|
e315cf2893 | ||
|
13fd615966 | ||
|
c094f84b85 | ||
|
25012d290a | ||
|
32202188cc | ||
|
bf734a31dc | ||
|
d29e7c4ba6 | ||
|
7163e2c2a2 | ||
|
1d810b4561 | ||
|
0913badd61 | ||
|
8b3062cd6e | ||
|
35218a4df1 | ||
|
d47f1fb730 | ||
|
1ad0bbfb7f | ||
|
c38a25f102 |
@@ -1,41 +0,0 @@
|
|||||||
environment:
|
|
||||||
global:
|
|
||||||
PROJECT_NAME: actix-net
|
|
||||||
matrix:
|
|
||||||
# Stable channel
|
|
||||||
- TARGET: i686-pc-windows-msvc
|
|
||||||
CHANNEL: stable
|
|
||||||
- TARGET: x86_64-pc-windows-gnu
|
|
||||||
CHANNEL: stable
|
|
||||||
- TARGET: x86_64-pc-windows-msvc
|
|
||||||
CHANNEL: stable
|
|
||||||
# Nightly channel
|
|
||||||
- TARGET: i686-pc-windows-msvc
|
|
||||||
CHANNEL: nightly
|
|
||||||
- TARGET: x86_64-pc-windows-gnu
|
|
||||||
CHANNEL: nightly
|
|
||||||
- TARGET: x86_64-pc-windows-msvc
|
|
||||||
CHANNEL: nightly
|
|
||||||
|
|
||||||
# Install Rust and Cargo
|
|
||||||
# (Based on from https://github.com/rust-lang/libc/blob/master/appveyor.yml)
|
|
||||||
install:
|
|
||||||
- ps: >-
|
|
||||||
If ($Env:TARGET -eq 'x86_64-pc-windows-gnu') {
|
|
||||||
$Env:PATH += ';C:\msys64\mingw64\bin'
|
|
||||||
} ElseIf ($Env:TARGET -eq 'i686-pc-windows-gnu') {
|
|
||||||
$Env:PATH += ';C:\MinGW\bin'
|
|
||||||
}
|
|
||||||
- curl -sSf -o rustup-init.exe https://win.rustup.rs
|
|
||||||
- rustup-init.exe --default-host %TARGET% --default-toolchain %CHANNEL% -y
|
|
||||||
- set PATH=%PATH%;C:\Users\appveyor\.cargo\bin
|
|
||||||
- rustc -Vv
|
|
||||||
- cargo -V
|
|
||||||
|
|
||||||
# 'cargo test' takes care of building for us, so disable Appveyor's build stage.
|
|
||||||
build: false
|
|
||||||
|
|
||||||
# Equivalent to Travis' `script` phase
|
|
||||||
test_script:
|
|
||||||
- cargo clean
|
|
||||||
- cargo test
|
|
23
.github/workflows/bench.yml
vendored
Normal file
23
.github/workflows/bench.yml
vendored
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
name: Benchmark (Linux)
|
||||||
|
|
||||||
|
on: [push, pull_request]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
check_benchmark:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@master
|
||||||
|
|
||||||
|
- name: Install Rust
|
||||||
|
uses: actions-rs/toolchain@v1
|
||||||
|
with:
|
||||||
|
toolchain: nightly
|
||||||
|
profile: minimal
|
||||||
|
override: true
|
||||||
|
|
||||||
|
- name: Check benchmark
|
||||||
|
uses: actions-rs/cargo@v1
|
||||||
|
with:
|
||||||
|
command: bench
|
||||||
|
args: --package=actix-service
|
18
.github/workflows/clippy.yml
vendored
Normal file
18
.github/workflows/clippy.yml
vendored
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
on: pull_request
|
||||||
|
|
||||||
|
name: Clippy Check
|
||||||
|
jobs:
|
||||||
|
clippy_check:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@master
|
||||||
|
- uses: actions-rs/toolchain@v1
|
||||||
|
with:
|
||||||
|
toolchain: nightly
|
||||||
|
components: clippy
|
||||||
|
profile: minimal
|
||||||
|
override: true
|
||||||
|
- uses: actions-rs/clippy-check@v1
|
||||||
|
with:
|
||||||
|
token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
args: --all-features --all --tests
|
76
.github/workflows/linux.yml
vendored
Normal file
76
.github/workflows/linux.yml
vendored
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
name: CI (Linux)
|
||||||
|
|
||||||
|
on: [push, pull_request]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build_and_test:
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
version:
|
||||||
|
- 1.39.0
|
||||||
|
- stable
|
||||||
|
- nightly
|
||||||
|
|
||||||
|
name: ${{ matrix.version }} - x86_64-unknown-linux-gnu
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@master
|
||||||
|
|
||||||
|
- name: Install ${{ matrix.version }}
|
||||||
|
uses: actions-rs/toolchain@v1
|
||||||
|
with:
|
||||||
|
toolchain: ${{ matrix.version }}-x86_64-unknown-linux-gnu
|
||||||
|
profile: minimal
|
||||||
|
override: true
|
||||||
|
|
||||||
|
- name: Generate Cargo.lock
|
||||||
|
uses: actions-rs/cargo@v1
|
||||||
|
with:
|
||||||
|
command: generate-lockfile
|
||||||
|
- name: Cache cargo registry
|
||||||
|
uses: actions/cache@v1
|
||||||
|
with:
|
||||||
|
path: ~/.cargo/registry
|
||||||
|
key: ${{ matrix.version }}-x86_64-unknown-linux-gnu-cargo-registry-trimmed-${{ hashFiles('**/Cargo.lock') }}
|
||||||
|
- name: Cache cargo index
|
||||||
|
uses: actions/cache@v1
|
||||||
|
with:
|
||||||
|
path: ~/.cargo/git
|
||||||
|
key: ${{ matrix.version }}-x86_64-unknown-linux-gnu-cargo-index-trimmed-${{ hashFiles('**/Cargo.lock') }}
|
||||||
|
- name: Cache cargo build
|
||||||
|
uses: actions/cache@v1
|
||||||
|
with:
|
||||||
|
path: target
|
||||||
|
key: ${{ matrix.version }}-x86_64-unknown-linux-gnu-cargo-build-trimmed-${{ hashFiles('**/Cargo.lock') }}
|
||||||
|
|
||||||
|
- name: check build
|
||||||
|
uses: actions-rs/cargo@v1
|
||||||
|
with:
|
||||||
|
command: check
|
||||||
|
args: --all --bins --examples --tests
|
||||||
|
|
||||||
|
- name: tests
|
||||||
|
uses: actions-rs/cargo@v1
|
||||||
|
timeout-minutes: 40
|
||||||
|
with:
|
||||||
|
command: test
|
||||||
|
args: --all --all-features --no-fail-fast -- --nocapture
|
||||||
|
|
||||||
|
- name: Generate coverage file
|
||||||
|
if: matrix.version == 'stable' && (github.ref == 'refs/heads/master' || github.event_name == 'pull_request')
|
||||||
|
run: |
|
||||||
|
cargo install cargo-tarpaulin
|
||||||
|
cargo tarpaulin --out Xml --workspace --all-features
|
||||||
|
|
||||||
|
- name: Upload to Codecov
|
||||||
|
if: matrix.version == 'stable' && (github.ref == 'refs/heads/master' || github.event_name == 'pull_request')
|
||||||
|
uses: codecov/codecov-action@v1
|
||||||
|
with:
|
||||||
|
file: cobertura.xml
|
||||||
|
|
||||||
|
- name: Clear the cargo caches
|
||||||
|
run: |
|
||||||
|
cargo install cargo-cache --no-default-features --features ci-autoclean
|
||||||
|
cargo-cache
|
37
.github/workflows/macos.yml
vendored
Normal file
37
.github/workflows/macos.yml
vendored
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
name: CI (macOS)
|
||||||
|
|
||||||
|
on: [push, pull_request]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build_and_test:
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
version:
|
||||||
|
- stable
|
||||||
|
- nightly
|
||||||
|
|
||||||
|
name: ${{ matrix.version }} - x86_64-apple-darwin
|
||||||
|
runs-on: macos-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@master
|
||||||
|
|
||||||
|
- name: Install ${{ matrix.version }}
|
||||||
|
uses: actions-rs/toolchain@v1
|
||||||
|
with:
|
||||||
|
toolchain: ${{ matrix.version }}-x86_64-apple-darwin
|
||||||
|
profile: minimal
|
||||||
|
override: true
|
||||||
|
|
||||||
|
- name: check build
|
||||||
|
uses: actions-rs/cargo@v1
|
||||||
|
with:
|
||||||
|
command: check
|
||||||
|
args: --all --bins --examples --tests
|
||||||
|
|
||||||
|
- name: tests
|
||||||
|
uses: actions-rs/cargo@v1
|
||||||
|
with:
|
||||||
|
command: test
|
||||||
|
args: --all --all-features --no-fail-fast -- --nocapture
|
58
.github/workflows/main.yml
vendored
58
.github/workflows/main.yml
vendored
@@ -1,58 +0,0 @@
|
|||||||
name: CI
|
|
||||||
|
|
||||||
on: [push, pull_request]
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
build_and_test:
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
toolchain:
|
|
||||||
- x86_64-pc-windows-msvc
|
|
||||||
- x86_64-pc-windows-gnu
|
|
||||||
- i686-pc-windows-msvc
|
|
||||||
- x86_64-apple-darwin
|
|
||||||
version:
|
|
||||||
- stable
|
|
||||||
- nightly
|
|
||||||
include:
|
|
||||||
- toolchain: x86_64-pc-windows-msvc
|
|
||||||
os: windows-latest
|
|
||||||
- toolchain: x86_64-pc-windows-gnu
|
|
||||||
os: windows-latest
|
|
||||||
- toolchain: i686-pc-windows-msvc
|
|
||||||
os: windows-latest
|
|
||||||
- toolchain: x86_64-apple-darwin
|
|
||||||
os: macOS-latest
|
|
||||||
|
|
||||||
name: ${{ matrix.version }} - ${{ matrix.toolchain }}
|
|
||||||
runs-on: ${{ matrix.os }}
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@master
|
|
||||||
|
|
||||||
- name: Install ${{ matrix.version }}
|
|
||||||
uses: actions-rs/toolchain@v1
|
|
||||||
with:
|
|
||||||
toolchain: ${{ matrix.version }}-${{ matrix.toolchain }}
|
|
||||||
default: true
|
|
||||||
|
|
||||||
- name: check nightly
|
|
||||||
if: matrix.version == 'nightly'
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: check
|
|
||||||
args: --all --benches --bins --examples --tests
|
|
||||||
|
|
||||||
- name: check stable
|
|
||||||
if: matrix.version == 'stable'
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: check
|
|
||||||
args: --all --bins --examples --tests
|
|
||||||
|
|
||||||
- name: tests
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: test
|
|
||||||
args: --all -- --nocapture
|
|
39
.github/workflows/windows-mingw.yml
vendored
Normal file
39
.github/workflows/windows-mingw.yml
vendored
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
name: CI (Windows-mingw)
|
||||||
|
|
||||||
|
on: [push, pull_request]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build_and_test:
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
version:
|
||||||
|
- stable
|
||||||
|
- nightly
|
||||||
|
|
||||||
|
name: ${{ matrix.version }} - x86_64-pc-windows-gnu
|
||||||
|
runs-on: windows-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@master
|
||||||
|
|
||||||
|
- name: Install ${{ matrix.version }}
|
||||||
|
uses: actions-rs/toolchain@v1
|
||||||
|
with:
|
||||||
|
toolchain: ${{ matrix.version }}-x86_64-pc-windows-gnu
|
||||||
|
profile: minimal
|
||||||
|
override: true
|
||||||
|
|
||||||
|
- name: Install MSYS2
|
||||||
|
uses: numworks/setup-msys2@v1
|
||||||
|
|
||||||
|
- name: Install packages
|
||||||
|
run: |
|
||||||
|
msys2do pacman -Sy --noconfirm pacman
|
||||||
|
msys2do pacman --noconfirm -S base-devel pkg-config
|
||||||
|
|
||||||
|
- name: check build
|
||||||
|
uses: actions-rs/cargo@v1
|
||||||
|
with:
|
||||||
|
command: check
|
||||||
|
args: --all --bins --examples --tests
|
63
.github/workflows/windows.yml
vendored
Normal file
63
.github/workflows/windows.yml
vendored
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
name: CI (Windows)
|
||||||
|
|
||||||
|
on: [push, pull_request]
|
||||||
|
|
||||||
|
env:
|
||||||
|
VCPKGRS_DYNAMIC: 1
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build_and_test:
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
version:
|
||||||
|
- stable
|
||||||
|
- nightly
|
||||||
|
target:
|
||||||
|
- x86_64-pc-windows-msvc
|
||||||
|
- i686-pc-windows-msvc
|
||||||
|
|
||||||
|
name: ${{ matrix.version }} - ${{ matrix.target }}
|
||||||
|
runs-on: windows-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@master
|
||||||
|
|
||||||
|
- name: Install ${{ matrix.version }}
|
||||||
|
uses: actions-rs/toolchain@v1
|
||||||
|
with:
|
||||||
|
toolchain: ${{ matrix.version }}-${{ matrix.target }}
|
||||||
|
profile: minimal
|
||||||
|
override: true
|
||||||
|
|
||||||
|
- name: Install OpenSSL (x64)
|
||||||
|
if: matrix.target == 'x86_64-pc-windows-msvc'
|
||||||
|
run: |
|
||||||
|
vcpkg integrate install
|
||||||
|
vcpkg install openssl:x64-windows
|
||||||
|
Get-ChildItem C:\vcpkg\installed\x64-windows\bin
|
||||||
|
Get-ChildItem C:\vcpkg\installed\x64-windows\lib
|
||||||
|
Copy-Item C:\vcpkg\installed\x64-windows\bin\libcrypto-1_1-x64.dll C:\vcpkg\installed\x64-windows\bin\libcrypto.dll
|
||||||
|
Copy-Item C:\vcpkg\installed\x64-windows\bin\libssl-1_1-x64.dll C:\vcpkg\installed\x64-windows\bin\libssl.dll
|
||||||
|
|
||||||
|
- name: Install OpenSSL (x86)
|
||||||
|
if: matrix.target == 'i686-pc-windows-msvc'
|
||||||
|
run: |
|
||||||
|
vcpkg integrate install
|
||||||
|
vcpkg install openssl:x86-windows
|
||||||
|
Get-ChildItem C:\vcpkg\installed\x86-windows\bin
|
||||||
|
Get-ChildItem C:\vcpkg\installed\x86-windows\lib
|
||||||
|
Copy-Item C:\vcpkg\installed\x86-windows\bin\libcrypto-1_1.dll C:\vcpkg\installed\x86-windows\bin\libcrypto.dll
|
||||||
|
Copy-Item C:\vcpkg\installed\x86-windows\bin\libssl-1_1.dll C:\vcpkg\installed\x86-windows\bin\libssl.dll
|
||||||
|
|
||||||
|
- name: check build
|
||||||
|
uses: actions-rs/cargo@v1
|
||||||
|
with:
|
||||||
|
command: check
|
||||||
|
args: --all --bins --examples --tests
|
||||||
|
|
||||||
|
- name: tests
|
||||||
|
uses: actions-rs/cargo@v1
|
||||||
|
with:
|
||||||
|
command: test
|
||||||
|
args: --all --all-features --no-fail-fast -- --nocapture
|
49
.travis.yml
49
.travis.yml
@@ -1,49 +0,0 @@
|
|||||||
language: rust
|
|
||||||
sudo: required
|
|
||||||
dist: trusty
|
|
||||||
|
|
||||||
cache:
|
|
||||||
cargo: true
|
|
||||||
apt: true
|
|
||||||
|
|
||||||
matrix:
|
|
||||||
include:
|
|
||||||
- rust: stable
|
|
||||||
- rust: beta
|
|
||||||
- rust: nightly-2019-11-07
|
|
||||||
allow_failures:
|
|
||||||
- rust: nightly-2019-11-07
|
|
||||||
|
|
||||||
env:
|
|
||||||
global:
|
|
||||||
- RUSTFLAGS="-C link-dead-code"
|
|
||||||
- OPENSSL_VERSION=openssl-1.0.2
|
|
||||||
|
|
||||||
before_install:
|
|
||||||
- sudo add-apt-repository -y ppa:0k53d-karl-f830m/openssl
|
|
||||||
- sudo apt-get update -qq
|
|
||||||
- sudo apt-get install -y openssl libssl-dev libelf-dev libdw-dev cmake gcc binutils-dev libiberty-dev
|
|
||||||
|
|
||||||
before_cache: |
|
|
||||||
if [[ "$TRAVIS_RUST_VERSION" == "nightly-2019-11-07" ]]; then
|
|
||||||
RUSTFLAGS="--cfg procmacro2_semver_exempt" cargo install --version 0.6.11 cargo-tarpaulin
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Add clippy
|
|
||||||
before_script:
|
|
||||||
- export PATH=$PATH:~/.cargo/bin
|
|
||||||
|
|
||||||
script:
|
|
||||||
- |
|
|
||||||
if [[ "$TRAVIS_RUST_VERSION" != "nightly-2019-11-07" ]]; then
|
|
||||||
cargo clean
|
|
||||||
cargo test --all --all-features -- --nocapture
|
|
||||||
fi
|
|
||||||
|
|
||||||
after_success:
|
|
||||||
- |
|
|
||||||
if [[ "$TRAVIS_RUST_VERSION" == "nightly-2019-11-07" ]]; then
|
|
||||||
taskset -c 0 cargo tarpaulin --all --all-features --out Xml
|
|
||||||
echo "Uploaded code coverage"
|
|
||||||
bash <(curl -s https://codecov.io/bash)
|
|
||||||
fi
|
|
@@ -10,6 +10,7 @@ members = [
|
|||||||
"actix-testing",
|
"actix-testing",
|
||||||
"actix-threadpool",
|
"actix-threadpool",
|
||||||
"actix-tls",
|
"actix-tls",
|
||||||
|
"actix-tracing",
|
||||||
"actix-utils",
|
"actix-utils",
|
||||||
"router",
|
"router",
|
||||||
"string",
|
"string",
|
||||||
@@ -26,6 +27,7 @@ actix-service = { path = "actix-service" }
|
|||||||
actix-testing = { path = "actix-testing" }
|
actix-testing = { path = "actix-testing" }
|
||||||
actix-threadpool = { path = "actix-threadpool" }
|
actix-threadpool = { path = "actix-threadpool" }
|
||||||
actix-tls = { path = "actix-tls" }
|
actix-tls = { path = "actix-tls" }
|
||||||
|
actix-tracing = { path = "actix-tracing" }
|
||||||
actix-utils = { path = "actix-utils" }
|
actix-utils = { path = "actix-utils" }
|
||||||
actix-router = { path = "router" }
|
actix-router = { path = "router" }
|
||||||
bytestring = { path = "string" }
|
bytestring = { path = "string" }
|
||||||
|
29
README.md
29
README.md
@@ -1,7 +1,16 @@
|
|||||||
# Actix net [](https://travis-ci.org/actix/actix-net) [](https://codecov.io/gh/actix/actix-net) [](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
# Actix net [](https://codecov.io/gh/actix/actix-net) [](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||||
|
|
||||||
Actix net - framework for composable network services
|
Actix net - framework for composable network services
|
||||||
|
|
||||||
|
## Build statuses
|
||||||
|
|
||||||
|
| Platform | Build Status |
|
||||||
|
| ---------------- | ------------ |
|
||||||
|
| Linux | [](https://github.com/actix/actix-net/actions?query=workflow%3A"CI+(Linux)") |
|
||||||
|
| macOS | [](https://github.com/actix/actix-net/actions?query=workflow%3A"CI+(macOS)") |
|
||||||
|
| Windows | [](https://github.com/actix/actix-net/actions?query=workflow%3A"CI+(Windows)") |
|
||||||
|
| Windows (MinGW) | [](https://github.com/actix/actix-net/actions?query=workflow%3A"CI+(Windows-mingw)") |
|
||||||
|
|
||||||
## Documentation & community resources
|
## Documentation & community resources
|
||||||
|
|
||||||
* [Chat on gitter](https://gitter.im/actix/actix)
|
* [Chat on gitter](https://gitter.im/actix/actix)
|
||||||
@@ -30,14 +39,16 @@ fn main() -> io::Result<()> {
|
|||||||
let num = num.clone();
|
let num = num.clone();
|
||||||
let acceptor = acceptor.clone();
|
let acceptor = acceptor.clone();
|
||||||
|
|
||||||
// service for converting incoming TcpStream to a SslStream<TcpStream>
|
// construct transformation pipeline
|
||||||
fn_service(move |stream: Io<tokio_tcp::TcpStream>| {
|
pipeline(
|
||||||
SslAcceptorExt::accept_async(&acceptor, stream.into_parts().0)
|
// service for converting incoming TcpStream to a SslStream<TcpStream>
|
||||||
.map_err(|e| println!("Openssl error: {}", e))
|
fn_service(move |stream: actix_rt::net::TcpStream| async move {
|
||||||
})
|
SslAcceptorExt::accept_async(&acceptor, stream.into_parts().0).await
|
||||||
// .and_then() combinator uses other service to convert incoming `Request` to a
|
.map_err(|e| println!("Openssl error: {}", e))
|
||||||
// `Response` and then uses that response as an input for next
|
}))
|
||||||
// service. in this case, on success we use `logger` service
|
// .and_then() combinator chains result of previos service call to argument
|
||||||
|
/// for next service calll. in this case, on success we chain
|
||||||
|
/// ssl stream to the `logger` service.
|
||||||
.and_then(fn_service(logger))
|
.and_then(fn_service(logger))
|
||||||
// Next service counts number of connections
|
// Next service counts number of connections
|
||||||
.and_then(move |_| {
|
.and_then(move |_| {
|
||||||
|
@@ -1,5 +1,15 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
* Use `.advance()` intead of `.split_to()`
|
||||||
|
|
||||||
|
## [0.2.0] - 2019-12-10
|
||||||
|
|
||||||
|
* Use specific futures dependencies
|
||||||
|
|
||||||
|
## [0.2.0-alpha.4]
|
||||||
|
|
||||||
|
* Fix buffer remaining capacity calcualtion
|
||||||
|
|
||||||
## [0.2.0-alpha.3]
|
## [0.2.0-alpha.3]
|
||||||
|
|
||||||
* Use tokio 0.2
|
* Use tokio 0.2
|
||||||
@@ -10,17 +20,14 @@
|
|||||||
|
|
||||||
* Migrated to `std::future`
|
* Migrated to `std::future`
|
||||||
|
|
||||||
|
|
||||||
## [0.1.2] - 2019-03-27
|
## [0.1.2] - 2019-03-27
|
||||||
|
|
||||||
* Added `Framed::map_io()` method.
|
* Added `Framed::map_io()` method.
|
||||||
|
|
||||||
|
|
||||||
## [0.1.1] - 2019-03-06
|
## [0.1.1] - 2019-03-06
|
||||||
|
|
||||||
* Added `FramedParts::with_read_buffer()` method.
|
* Added `FramedParts::with_read_buffer()` method.
|
||||||
|
|
||||||
|
|
||||||
## [0.1.0] - 2018-12-09
|
## [0.1.0] - 2018-12-09
|
||||||
|
|
||||||
* Move codec to separate crate
|
* Move codec to separate crate
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-codec"
|
name = "actix-codec"
|
||||||
version = "0.2.0-alpha.3"
|
version = "0.2.0"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Utilities for encoding and decoding frames"
|
description = "Utilities for encoding and decoding frames"
|
||||||
keywords = ["network", "framework", "async", "futures"]
|
keywords = ["network", "framework", "async", "futures"]
|
||||||
@@ -9,7 +9,6 @@ repository = "https://github.com/actix/actix-net.git"
|
|||||||
documentation = "https://docs.rs/actix-codec/"
|
documentation = "https://docs.rs/actix-codec/"
|
||||||
categories = ["network-programming", "asynchronous"]
|
categories = ["network-programming", "asynchronous"]
|
||||||
license = "MIT/Apache-2.0"
|
license = "MIT/Apache-2.0"
|
||||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
workspace = ".."
|
workspace = ".."
|
||||||
|
|
||||||
@@ -20,7 +19,9 @@ path = "src/lib.rs"
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
bitflags = "1.2.1"
|
bitflags = "1.2.1"
|
||||||
bytes = "0.5.2"
|
bytes = "0.5.2"
|
||||||
futures = "0.3.1"
|
futures-core = { version = "0.3.4", default-features = false }
|
||||||
|
futures-sink = { version = "0.3.4", default-features = false }
|
||||||
tokio = { version = "0.2.4", default-features=false }
|
tokio = { version = "0.2.4", default-features=false }
|
||||||
tokio-util = { version = "0.2.0", default-features=false, features=["codec"] }
|
tokio-util = { version = "0.2.0", default-features=false, features=["codec"] }
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
|
pin-project = "0.4.8"
|
||||||
|
@@ -2,8 +2,10 @@ use std::pin::Pin;
|
|||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
use std::{fmt, io};
|
use std::{fmt, io};
|
||||||
|
|
||||||
use bytes::{BufMut, BytesMut};
|
use bytes::{Buf, BytesMut};
|
||||||
use futures::{ready, Sink, Stream};
|
use futures_core::{ready, Stream};
|
||||||
|
use futures_sink::Sink;
|
||||||
|
use pin_project::pin_project;
|
||||||
|
|
||||||
use crate::{AsyncRead, AsyncWrite, Decoder, Encoder};
|
use crate::{AsyncRead, AsyncWrite, Decoder, Encoder};
|
||||||
|
|
||||||
@@ -19,9 +21,9 @@ bitflags::bitflags! {
|
|||||||
|
|
||||||
/// A unified `Stream` and `Sink` interface to an underlying I/O object, using
|
/// A unified `Stream` and `Sink` interface to an underlying I/O object, using
|
||||||
/// the `Encoder` and `Decoder` traits to encode and decode frames.
|
/// the `Encoder` and `Decoder` traits to encode and decode frames.
|
||||||
///
|
#[pin_project]
|
||||||
/// You can create a `Framed` instance by using the `AsyncRead::framed` adapter.
|
|
||||||
pub struct Framed<T, U> {
|
pub struct Framed<T, U> {
|
||||||
|
#[pin]
|
||||||
io: T,
|
io: T,
|
||||||
codec: U,
|
codec: U,
|
||||||
flags: Flags,
|
flags: Flags,
|
||||||
@@ -29,8 +31,6 @@ pub struct Framed<T, U> {
|
|||||||
write_buf: BytesMut,
|
write_buf: BytesMut,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, U> Unpin for Framed<T, U> {}
|
|
||||||
|
|
||||||
impl<T, U> Framed<T, U>
|
impl<T, U> Framed<T, U>
|
||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite,
|
T: AsyncRead + AsyncWrite,
|
||||||
@@ -49,10 +49,6 @@ where
|
|||||||
/// `Sink`; grouping this into a single object is often useful for layering
|
/// `Sink`; grouping this into a single object is often useful for layering
|
||||||
/// things like gzip or TLS, which require both read and write access to the
|
/// things like gzip or TLS, which require both read and write access to the
|
||||||
/// underlying object.
|
/// underlying object.
|
||||||
///
|
|
||||||
/// If you want to work more directly with the streams and sink, consider
|
|
||||||
/// calling `split` on the `Framed` returned by this method, which will
|
|
||||||
/// break them into separate objects, allowing them to interact more easily.
|
|
||||||
pub fn new(io: T, codec: U) -> Framed<T, U> {
|
pub fn new(io: T, codec: U) -> Framed<T, U> {
|
||||||
Framed {
|
Framed {
|
||||||
io,
|
io,
|
||||||
@@ -82,10 +78,6 @@ impl<T, U> Framed<T, U> {
|
|||||||
/// This objects takes a stream and a readbuffer and a writebuffer. These
|
/// This objects takes a stream and a readbuffer and a writebuffer. These
|
||||||
/// field can be obtained from an existing `Framed` with the
|
/// field can be obtained from an existing `Framed` with the
|
||||||
/// `into_parts` method.
|
/// `into_parts` method.
|
||||||
///
|
|
||||||
/// If you want to work more directly with the streams and sink, consider
|
|
||||||
/// calling `split` on the `Framed` returned by this method, which will
|
|
||||||
/// break them into separate objects, allowing them to interact more easily.
|
|
||||||
pub fn from_parts(parts: FramedParts<T, U>) -> Framed<T, U> {
|
pub fn from_parts(parts: FramedParts<T, U>) -> Framed<T, U> {
|
||||||
Framed {
|
Framed {
|
||||||
io: parts.io,
|
io: parts.io,
|
||||||
@@ -136,15 +128,6 @@ impl<T, U> Framed<T, U> {
|
|||||||
self.write_buf.len() >= HW
|
self.write_buf.len() >= HW
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Consumes the `Frame`, returning its underlying I/O stream.
|
|
||||||
///
|
|
||||||
/// Note that care should be taken to not tamper with the underlying stream
|
|
||||||
/// of data coming in as it may corrupt the stream of frames otherwise
|
|
||||||
/// being worked with.
|
|
||||||
pub fn into_inner(self) -> T {
|
|
||||||
self.io
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Consume the `Frame`, returning `Frame` with different codec.
|
/// Consume the `Frame`, returning `Frame` with different codec.
|
||||||
pub fn into_framed<U2>(self, codec: U2) -> Framed<T, U2> {
|
pub fn into_framed<U2>(self, codec: U2) -> Framed<T, U2> {
|
||||||
Framed {
|
Framed {
|
||||||
@@ -203,40 +186,45 @@ impl<T, U> Framed<T, U> {
|
|||||||
|
|
||||||
impl<T, U> Framed<T, U> {
|
impl<T, U> Framed<T, U> {
|
||||||
/// Serialize item and Write to the inner buffer
|
/// Serialize item and Write to the inner buffer
|
||||||
pub fn write(&mut self, item: <U as Encoder>::Item) -> Result<(), <U as Encoder>::Error>
|
pub fn write(mut self: Pin<&mut Self>, item: <U as Encoder>::Item) -> Result<(), <U as Encoder>::Error>
|
||||||
where
|
where
|
||||||
T: AsyncWrite,
|
T: AsyncWrite,
|
||||||
U: Encoder,
|
U: Encoder,
|
||||||
{
|
{
|
||||||
let remaining = self.write_buf.remaining_mut();
|
let this = self.as_mut().project();
|
||||||
|
let remaining = this.write_buf.capacity() - this.write_buf.len();
|
||||||
if remaining < LW {
|
if remaining < LW {
|
||||||
self.write_buf.reserve(HW - remaining);
|
this.write_buf.reserve(HW - remaining);
|
||||||
}
|
}
|
||||||
|
|
||||||
self.codec.encode(item, &mut self.write_buf)?;
|
this.codec.encode(item, this.write_buf)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Check if framed is able to write more data
|
/// Check if framed is able to write more data.
|
||||||
pub fn is_ready(&self) -> bool {
|
///
|
||||||
|
/// `Framed` object considers ready if there is free space in write buffer.
|
||||||
|
pub fn is_write_ready(&self) -> bool {
|
||||||
self.write_buf.len() < HW
|
self.write_buf.len() < HW
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn next_item(&mut self, cx: &mut Context<'_>) -> Poll<Option<Result<U::Item, U::Error>>>
|
/// Try to read underlying I/O stream and decode item.
|
||||||
|
pub fn next_item(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Result<U::Item, U::Error>>>
|
||||||
where
|
where
|
||||||
T: AsyncRead,
|
T: AsyncRead,
|
||||||
U: Decoder,
|
U: Decoder,
|
||||||
{
|
{
|
||||||
loop {
|
loop {
|
||||||
|
let mut this = self.as_mut().project();
|
||||||
// Repeatedly call `decode` or `decode_eof` as long as it is
|
// Repeatedly call `decode` or `decode_eof` as long as it is
|
||||||
// "readable". Readable is defined as not having returned `None`. If
|
// "readable". Readable is defined as not having returned `None`. If
|
||||||
// the upstream has returned EOF, and the decoder is no longer
|
// the upstream has returned EOF, and the decoder is no longer
|
||||||
// readable, it can be assumed that the decoder will never become
|
// readable, it can be assumed that the decoder will never become
|
||||||
// readable again, at which point the stream is terminated.
|
// readable again, at which point the stream is terminated.
|
||||||
|
|
||||||
if self.flags.contains(Flags::READABLE) {
|
if this.flags.contains(Flags::READABLE) {
|
||||||
if self.flags.contains(Flags::EOF) {
|
if this.flags.contains(Flags::EOF) {
|
||||||
match self.codec.decode_eof(&mut self.read_buf) {
|
match this.codec.decode_eof(&mut this.read_buf) {
|
||||||
Ok(Some(frame)) => return Poll::Ready(Some(Ok(frame))),
|
Ok(Some(frame)) => return Poll::Ready(Some(Ok(frame))),
|
||||||
Ok(None) => return Poll::Ready(None),
|
Ok(None) => return Poll::Ready(None),
|
||||||
Err(e) => return Poll::Ready(Some(Err(e))),
|
Err(e) => return Poll::Ready(Some(Err(e))),
|
||||||
@@ -245,86 +233,82 @@ impl<T, U> Framed<T, U> {
|
|||||||
|
|
||||||
log::trace!("attempting to decode a frame");
|
log::trace!("attempting to decode a frame");
|
||||||
|
|
||||||
match self.codec.decode(&mut self.read_buf) {
|
match this.codec.decode(&mut this.read_buf) {
|
||||||
Ok(Some(frame)) => {
|
Ok(Some(frame)) => {
|
||||||
log::trace!("frame decoded from buffer");
|
log::trace!("frame decoded from buffer");
|
||||||
return Poll::Ready(Some(Ok(frame)));
|
return Poll::Ready(Some(Ok(frame)));
|
||||||
}
|
}
|
||||||
Err(e) => return Poll::Ready(Some(Err(e))),
|
Err(e) => return Poll::Ready(Some(Err(e))),
|
||||||
_ => {
|
_ => (), // Need more data
|
||||||
// Need more data
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
self.flags.remove(Flags::READABLE);
|
this.flags.remove(Flags::READABLE);
|
||||||
}
|
}
|
||||||
|
|
||||||
debug_assert!(!self.flags.contains(Flags::EOF));
|
debug_assert!(!this.flags.contains(Flags::EOF));
|
||||||
|
|
||||||
// Otherwise, try to read more data and try again. Make sure we've got room
|
// Otherwise, try to read more data and try again. Make sure we've got room
|
||||||
let remaining = self.read_buf.remaining_mut();
|
let remaining = this.read_buf.capacity() - this.read_buf.len();
|
||||||
if remaining < LW {
|
if remaining < LW {
|
||||||
self.read_buf.reserve(HW - remaining)
|
this.read_buf.reserve(HW - remaining)
|
||||||
}
|
}
|
||||||
let cnt = match unsafe {
|
let cnt = match this.io.poll_read_buf(cx, &mut this.read_buf) {
|
||||||
Pin::new_unchecked(&mut self.io).poll_read_buf(cx, &mut self.read_buf)
|
|
||||||
} {
|
|
||||||
Poll::Pending => return Poll::Pending,
|
Poll::Pending => return Poll::Pending,
|
||||||
Poll::Ready(Err(e)) => return Poll::Ready(Some(Err(e.into()))),
|
Poll::Ready(Err(e)) => return Poll::Ready(Some(Err(e.into()))),
|
||||||
Poll::Ready(Ok(cnt)) => cnt,
|
Poll::Ready(Ok(cnt)) => cnt,
|
||||||
};
|
};
|
||||||
|
|
||||||
if cnt == 0 {
|
if cnt == 0 {
|
||||||
self.flags.insert(Flags::EOF);
|
this.flags.insert(Flags::EOF);
|
||||||
}
|
}
|
||||||
self.flags.insert(Flags::READABLE);
|
this.flags.insert(Flags::READABLE);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn flush(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), U::Error>>
|
/// Flush write buffer to underlying I/O stream.
|
||||||
|
pub fn flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), U::Error>>
|
||||||
where
|
where
|
||||||
T: AsyncWrite,
|
T: AsyncWrite,
|
||||||
U: Encoder,
|
U: Encoder,
|
||||||
{
|
{
|
||||||
|
let mut this = self.as_mut().project();
|
||||||
log::trace!("flushing framed transport");
|
log::trace!("flushing framed transport");
|
||||||
|
|
||||||
while !self.write_buf.is_empty() {
|
while !this.write_buf.is_empty() {
|
||||||
log::trace!("writing; remaining={}", self.write_buf.len());
|
log::trace!("writing; remaining={}", this.write_buf.len());
|
||||||
|
|
||||||
let n = ready!(unsafe {
|
let n = ready!(
|
||||||
Pin::new_unchecked(&mut self.io).poll_write(cx, &self.write_buf)
|
this.io.as_mut().poll_write(cx, this.write_buf)
|
||||||
})?;
|
)?;
|
||||||
|
|
||||||
if n == 0 {
|
if n == 0 {
|
||||||
return Poll::Ready(Err(io::Error::new(
|
return Poll::Ready(Err(io::Error::new(
|
||||||
io::ErrorKind::WriteZero,
|
io::ErrorKind::WriteZero,
|
||||||
"failed to \
|
"failed to write frame to transport",
|
||||||
write frame to transport",
|
|
||||||
)
|
)
|
||||||
.into()));
|
.into()));
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Add a way to `bytes` to do this w/o returning the drained
|
// remove written data
|
||||||
// data.
|
this.write_buf.advance(n);
|
||||||
let _ = self.write_buf.split_to(n);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Try flushing the underlying IO
|
// Try flushing the underlying IO
|
||||||
ready!(unsafe { Pin::new_unchecked(&mut self.io).poll_flush(cx) })?;
|
ready!(this.io.poll_flush(cx))?;
|
||||||
|
|
||||||
log::trace!("framed transport flushed");
|
log::trace!("framed transport flushed");
|
||||||
Poll::Ready(Ok(()))
|
Poll::Ready(Ok(()))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn close(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), U::Error>>
|
/// Flush write buffer and shutdown underlying I/O stream.
|
||||||
|
pub fn close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), U::Error>>
|
||||||
where
|
where
|
||||||
T: AsyncWrite,
|
T: AsyncWrite,
|
||||||
U: Encoder,
|
U: Encoder,
|
||||||
{
|
{
|
||||||
unsafe {
|
let mut this = self.as_mut().project();
|
||||||
ready!(Pin::new_unchecked(&mut self.io).poll_flush(cx))?;
|
ready!(this.io.as_mut().poll_flush(cx))?;
|
||||||
ready!(Pin::new_unchecked(&mut self.io).poll_shutdown(cx))?;
|
ready!(this.io.as_mut().poll_shutdown(cx))?;
|
||||||
}
|
|
||||||
Poll::Ready(Ok(()))
|
Poll::Ready(Ok(()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -336,7 +320,7 @@ where
|
|||||||
{
|
{
|
||||||
type Item = Result<U::Item, U::Error>;
|
type Item = Result<U::Item, U::Error>;
|
||||||
|
|
||||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||||
self.next_item(cx)
|
self.next_item(cx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -350,7 +334,7 @@ where
|
|||||||
type Error = U::Error;
|
type Error = U::Error;
|
||||||
|
|
||||||
fn poll_ready(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
fn poll_ready(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||||
if self.is_ready() {
|
if self.is_write_ready() {
|
||||||
Poll::Ready(Ok(()))
|
Poll::Ready(Ok(()))
|
||||||
} else {
|
} else {
|
||||||
Poll::Pending
|
Poll::Pending
|
||||||
@@ -358,21 +342,21 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn start_send(
|
fn start_send(
|
||||||
mut self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
item: <U as Encoder>::Item,
|
item: <U as Encoder>::Item,
|
||||||
) -> Result<(), Self::Error> {
|
) -> Result<(), Self::Error> {
|
||||||
self.write(item)
|
self.write(item)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn poll_flush(
|
fn poll_flush(
|
||||||
mut self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Poll<Result<(), Self::Error>> {
|
) -> Poll<Result<(), Self::Error>> {
|
||||||
self.flush(cx)
|
self.flush(cx)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn poll_close(
|
fn poll_close(
|
||||||
mut self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Poll<Result<(), Self::Error>> {
|
) -> Poll<Result<(), Self::Error>> {
|
||||||
self.close(cx)
|
self.close(cx)
|
||||||
|
@@ -7,7 +7,6 @@
|
|||||||
//! [`AsyncRead`]: #
|
//! [`AsyncRead`]: #
|
||||||
//! [`AsyncWrite`]: #
|
//! [`AsyncWrite`]: #
|
||||||
#![deny(rust_2018_idioms, warnings)]
|
#![deny(rust_2018_idioms, warnings)]
|
||||||
#![allow(clippy::type_complexity)]
|
|
||||||
|
|
||||||
mod bcodec;
|
mod bcodec;
|
||||||
mod framed;
|
mod framed;
|
||||||
|
@@ -1,5 +1,41 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [2.0.0-alpha.3] - 2020-05-08
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
* Corrected spelling of `ConnectError::Unresolverd` to `ConnectError::Unresolved`
|
||||||
|
|
||||||
|
## [2.0.0-alpha.2] - 2020-03-08
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Update `trust-dns-proto` dependency to 0.19. [#116]
|
||||||
|
* Update `trust-dns-resolver` dependency to 0.19. [#116]
|
||||||
|
* `Address` trait is now required to have static lifetime. [#116]
|
||||||
|
* `start_resolver` and `start_default_resolver` are now `async` and may return a `ConnectError`. [#116]
|
||||||
|
|
||||||
|
[#116]: https://github.com/actix/actix-net/pull/116
|
||||||
|
|
||||||
|
## [2.0.0-alpha.1] - 2020-03-03
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Update `rustls` dependency to 0.17
|
||||||
|
* Update `tokio-rustls` dependency to 0.13
|
||||||
|
|
||||||
|
## [1.0.2] - 2020-01-15
|
||||||
|
|
||||||
|
* Fix actix-service 1.0.3 compatibility
|
||||||
|
|
||||||
|
## [1.0.1] - 2019-12-15
|
||||||
|
|
||||||
|
* Fix trust-dns-resolver compilation
|
||||||
|
|
||||||
|
## [1.0.0] - 2019-12-11
|
||||||
|
|
||||||
|
* Release
|
||||||
|
|
||||||
## [1.0.0-alpha.3] - 2019-12-07
|
## [1.0.0-alpha.3] - 2019-12-07
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-connect"
|
name = "actix-connect"
|
||||||
version = "1.0.0-alpha.3"
|
version = "2.0.0-alpha.3"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix connect - tcp connector service"
|
description = "Actix connect - tcp connector service"
|
||||||
keywords = ["network", "framework", "async", "futures"]
|
keywords = ["network", "framework", "async", "futures"]
|
||||||
@@ -9,9 +9,7 @@ repository = "https://github.com/actix/actix-net.git"
|
|||||||
documentation = "https://docs.rs/actix-connect/"
|
documentation = "https://docs.rs/actix-connect/"
|
||||||
categories = ["network-programming", "asynchronous"]
|
categories = ["network-programming", "asynchronous"]
|
||||||
license = "MIT/Apache-2.0"
|
license = "MIT/Apache-2.0"
|
||||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
workspace = ".."
|
|
||||||
|
|
||||||
[package.metadata.docs.rs]
|
[package.metadata.docs.rs]
|
||||||
features = ["openssl", "rustls", "uri"]
|
features = ["openssl", "rustls", "uri"]
|
||||||
@@ -33,26 +31,27 @@ rustls = ["rust-tls", "tokio-rustls", "webpki"]
|
|||||||
uri = ["http"]
|
uri = ["http"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-service = "1.0.0-alpha.3"
|
actix-service = "1.0.3"
|
||||||
actix-codec = "0.2.0-alpha.3"
|
actix-codec = "0.2.0"
|
||||||
actix-utils = "1.0.0-alpha.3"
|
actix-utils = "1.0.6"
|
||||||
actix-rt = "1.0.0-alpha.3"
|
actix-rt = "1.0.0"
|
||||||
derive_more = "0.99.2"
|
derive_more = "0.99.2"
|
||||||
either = "1.5.2"
|
either = "1.5.3"
|
||||||
futures = "0.3.1"
|
futures-util = { version = "0.3.4", default-features = false }
|
||||||
http = { version = "0.2.0", optional = true }
|
http = { version = "0.2.0", optional = true }
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
trust-dns-resolver = { version="0.18.0-alpha.2", default-features = false, features=["tokio"] }
|
trust-dns-proto = { version = "0.19", default-features = false, features = ["tokio-runtime"] }
|
||||||
|
trust-dns-resolver = { version = "0.19", default-features = false, features = ["tokio-runtime", "system-config"] }
|
||||||
|
|
||||||
# openssl
|
# openssl
|
||||||
open-ssl = { version="0.10", package = "openssl", optional = true }
|
open-ssl = { version="0.10", package = "openssl", optional = true }
|
||||||
tokio-openssl = { version = "0.4.0", optional = true }
|
tokio-openssl = { version = "0.4.0", optional = true }
|
||||||
|
|
||||||
# rustls
|
# rustls
|
||||||
rust-tls = { version = "0.16.0", package = "rustls", optional = true }
|
rust-tls = { version = "0.17.0", package = "rustls", optional = true }
|
||||||
tokio-rustls = { version = "0.12.0", optional = true }
|
tokio-rustls = { version = "0.13.0", optional = true }
|
||||||
webpki = { version = "0.21", optional = true }
|
webpki = { version = "0.21", optional = true }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
bytes = "0.5.2"
|
bytes = "0.5.3"
|
||||||
actix-testing = { version="1.0.0-alpha.2" }
|
actix-testing = { version="1.0.0" }
|
||||||
|
@@ -6,7 +6,7 @@ use std::net::SocketAddr;
|
|||||||
use either::Either;
|
use either::Either;
|
||||||
|
|
||||||
/// Connect request
|
/// Connect request
|
||||||
pub trait Address: Unpin {
|
pub trait Address: Unpin + 'static {
|
||||||
/// Host name of the request
|
/// Host name of the request
|
||||||
fn host(&self) -> &str;
|
fn host(&self) -> &str;
|
||||||
|
|
||||||
|
@@ -8,7 +8,7 @@ use std::task::{Context, Poll};
|
|||||||
|
|
||||||
use actix_rt::net::TcpStream;
|
use actix_rt::net::TcpStream;
|
||||||
use actix_service::{Service, ServiceFactory};
|
use actix_service::{Service, ServiceFactory};
|
||||||
use futures::future::{err, ok, BoxFuture, Either, FutureExt, Ready};
|
use futures_util::future::{err, ok, BoxFuture, Either, FutureExt, Ready};
|
||||||
|
|
||||||
use super::connect::{Address, Connect, Connection};
|
use super::connect::{Address, Connect, Connection};
|
||||||
use super::error::ConnectError;
|
use super::error::ConnectError;
|
||||||
@@ -88,7 +88,7 @@ impl<T: Address> Service for TcpConnector<T> {
|
|||||||
Either::Left(TcpConnectorResponse::new(req, port, addr))
|
Either::Left(TcpConnectorResponse::new(req, port, addr))
|
||||||
} else {
|
} else {
|
||||||
error!("TCP connector: got unresolved address");
|
error!("TCP connector: got unresolved address");
|
||||||
Either::Right(err(ConnectError::Unresolverd))
|
Either::Right(err(ConnectError::Unresolved))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -18,7 +18,7 @@ pub enum ConnectError {
|
|||||||
|
|
||||||
/// Unresolved host name
|
/// Unresolved host name
|
||||||
#[display(fmt = "Connector received `Connect` method with unresolved host")]
|
#[display(fmt = "Connector received `Connect` method with unresolved host")]
|
||||||
Unresolverd,
|
Unresolved,
|
||||||
|
|
||||||
/// Connection io error
|
/// Connection io error
|
||||||
#[display(fmt = "{}", _0)]
|
#[display(fmt = "{}", _0)]
|
||||||
|
@@ -25,7 +25,7 @@ use actix_rt::{net::TcpStream, Arbiter};
|
|||||||
use actix_service::{pipeline, pipeline_factory, Service, ServiceFactory};
|
use actix_service::{pipeline, pipeline_factory, Service, ServiceFactory};
|
||||||
use trust_dns_resolver::config::{ResolverConfig, ResolverOpts};
|
use trust_dns_resolver::config::{ResolverConfig, ResolverOpts};
|
||||||
use trust_dns_resolver::system_conf::read_system_conf;
|
use trust_dns_resolver::system_conf::read_system_conf;
|
||||||
use trust_dns_resolver::AsyncResolver;
|
use trust_dns_resolver::TokioAsyncResolver as AsyncResolver;
|
||||||
|
|
||||||
pub mod resolver {
|
pub mod resolver {
|
||||||
pub use trust_dns_resolver::config::{ResolverConfig, ResolverOpts};
|
pub use trust_dns_resolver::config::{ResolverConfig, ResolverOpts};
|
||||||
@@ -39,17 +39,18 @@ pub use self::error::ConnectError;
|
|||||||
pub use self::resolve::{Resolver, ResolverFactory};
|
pub use self::resolve::{Resolver, ResolverFactory};
|
||||||
pub use self::service::{ConnectService, ConnectServiceFactory, TcpConnectService};
|
pub use self::service::{ConnectService, ConnectServiceFactory, TcpConnectService};
|
||||||
|
|
||||||
pub fn start_resolver(cfg: ResolverConfig, opts: ResolverOpts) -> AsyncResolver {
|
pub async fn start_resolver(
|
||||||
let (resolver, bg) = AsyncResolver::new(cfg, opts);
|
cfg: ResolverConfig,
|
||||||
actix_rt::spawn(bg);
|
opts: ResolverOpts,
|
||||||
resolver
|
) -> Result<AsyncResolver, ConnectError> {
|
||||||
|
Ok(AsyncResolver::tokio(cfg, opts).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
struct DefaultResolver(AsyncResolver);
|
struct DefaultResolver(AsyncResolver);
|
||||||
|
|
||||||
pub(crate) fn get_default_resolver() -> AsyncResolver {
|
pub(crate) async fn get_default_resolver() -> Result<AsyncResolver, ConnectError> {
|
||||||
if Arbiter::contains_item::<DefaultResolver>() {
|
if Arbiter::contains_item::<DefaultResolver>() {
|
||||||
Arbiter::get_item(|item: &DefaultResolver| item.0.clone())
|
Ok(Arbiter::get_item(|item: &DefaultResolver| item.0.clone()))
|
||||||
} else {
|
} else {
|
||||||
let (cfg, opts) = match read_system_conf() {
|
let (cfg, opts) = match read_system_conf() {
|
||||||
Ok((cfg, opts)) => (cfg, opts),
|
Ok((cfg, opts)) => (cfg, opts),
|
||||||
@@ -59,20 +60,19 @@ pub(crate) fn get_default_resolver() -> AsyncResolver {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let (resolver, bg) = AsyncResolver::new(cfg, opts);
|
let resolver = AsyncResolver::tokio(cfg, opts).await?;
|
||||||
actix_rt::spawn(bg);
|
|
||||||
|
|
||||||
Arbiter::set_item(DefaultResolver(resolver.clone()));
|
Arbiter::set_item(DefaultResolver(resolver.clone()));
|
||||||
resolver
|
Ok(resolver)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn start_default_resolver() -> AsyncResolver {
|
pub async fn start_default_resolver() -> Result<AsyncResolver, ConnectError> {
|
||||||
get_default_resolver()
|
get_default_resolver().await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create tcp connector service
|
/// Create tcp connector service
|
||||||
pub fn new_connector<T: Address>(
|
pub fn new_connector<T: Address + 'static>(
|
||||||
resolver: AsyncResolver,
|
resolver: AsyncResolver,
|
||||||
) -> impl Service<Request = Connect<T>, Response = Connection<T, TcpStream>, Error = ConnectError>
|
) -> impl Service<Request = Connect<T>, Response = Connection<T, TcpStream>, Error = ConnectError>
|
||||||
+ Clone {
|
+ Clone {
|
||||||
@@ -80,7 +80,7 @@ pub fn new_connector<T: Address>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Create tcp connector service
|
/// Create tcp connector service
|
||||||
pub fn new_connector_factory<T: Address>(
|
pub fn new_connector_factory<T: Address + 'static>(
|
||||||
resolver: AsyncResolver,
|
resolver: AsyncResolver,
|
||||||
) -> impl ServiceFactory<
|
) -> impl ServiceFactory<
|
||||||
Config = (),
|
Config = (),
|
||||||
@@ -93,14 +93,14 @@ pub fn new_connector_factory<T: Address>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Create connector service with default parameters
|
/// Create connector service with default parameters
|
||||||
pub fn default_connector<T: Address>(
|
pub fn default_connector<T: Address + 'static>(
|
||||||
) -> impl Service<Request = Connect<T>, Response = Connection<T, TcpStream>, Error = ConnectError>
|
) -> impl Service<Request = Connect<T>, Response = Connection<T, TcpStream>, Error = ConnectError>
|
||||||
+ Clone {
|
+ Clone {
|
||||||
pipeline(Resolver::default()).and_then(TcpConnector::new())
|
pipeline(Resolver::default()).and_then(TcpConnector::new())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create connector service factory with default parameters
|
/// Create connector service factory with default parameters
|
||||||
pub fn default_connector_factory<T: Address>() -> impl ServiceFactory<
|
pub fn default_connector_factory<T: Address + 'static>() -> impl ServiceFactory<
|
||||||
Config = (),
|
Config = (),
|
||||||
Request = Connect<T>,
|
Request = Connect<T>,
|
||||||
Response = Connection<T, TcpStream>,
|
Response = Connection<T, TcpStream>,
|
||||||
|
@@ -5,9 +5,9 @@ use std::pin::Pin;
|
|||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
use actix_service::{Service, ServiceFactory};
|
use actix_service::{Service, ServiceFactory};
|
||||||
use futures::future::{ok, Either, Ready};
|
use futures_util::future::{ok, Either, Ready};
|
||||||
use trust_dns_resolver::lookup_ip::LookupIpFuture;
|
use trust_dns_resolver::TokioAsyncResolver as AsyncResolver;
|
||||||
use trust_dns_resolver::{AsyncResolver, Background};
|
use trust_dns_resolver::{error::ResolveError, lookup_ip::LookupIp};
|
||||||
|
|
||||||
use crate::connect::{Address, Connect};
|
use crate::connect::{Address, Connect};
|
||||||
use crate::error::ConnectError;
|
use crate::error::ConnectError;
|
||||||
@@ -106,7 +106,10 @@ impl<T: Address> Service for Resolver<T> {
|
|||||||
type Request = Connect<T>;
|
type Request = Connect<T>;
|
||||||
type Response = Connect<T>;
|
type Response = Connect<T>;
|
||||||
type Error = ConnectError;
|
type Error = ConnectError;
|
||||||
type Future = Either<ResolverFuture<T>, Ready<Result<Connect<T>, Self::Error>>>;
|
type Future = Either<
|
||||||
|
Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>,
|
||||||
|
Ready<Result<Connect<T>, Self::Error>>,
|
||||||
|
>;
|
||||||
|
|
||||||
fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||||
Poll::Ready(Ok(()))
|
Poll::Ready(Ok(()))
|
||||||
@@ -119,32 +122,48 @@ impl<T: Address> Service for Resolver<T> {
|
|||||||
req.addr = Some(either::Either::Left(SocketAddr::new(ip, req.port())));
|
req.addr = Some(either::Either::Left(SocketAddr::new(ip, req.port())));
|
||||||
Either::Right(ok(req))
|
Either::Right(ok(req))
|
||||||
} else {
|
} else {
|
||||||
trace!("DNS resolver: resolving host {:?}", req.host());
|
let resolver = self.resolver.as_ref().map(AsyncResolver::clone);
|
||||||
if self.resolver.is_none() {
|
Either::Left(Box::pin(async move {
|
||||||
self.resolver = Some(get_default_resolver());
|
trace!("DNS resolver: resolving host {:?}", req.host());
|
||||||
}
|
let resolver = if let Some(resolver) = resolver {
|
||||||
Either::Left(ResolverFuture::new(req, self.resolver.as_ref().unwrap()))
|
resolver
|
||||||
|
} else {
|
||||||
|
get_default_resolver()
|
||||||
|
.await
|
||||||
|
.expect("Failed to get default resolver")
|
||||||
|
};
|
||||||
|
ResolverFuture::new(req, &resolver).await
|
||||||
|
}))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type LookupIpFuture = Pin<Box<dyn Future<Output = Result<LookupIp, ResolveError>>>>;
|
||||||
|
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
/// Resolver future
|
/// Resolver future
|
||||||
pub struct ResolverFuture<T: Address> {
|
pub struct ResolverFuture<T: Address> {
|
||||||
req: Option<Connect<T>>,
|
req: Option<Connect<T>>,
|
||||||
lookup: Background<LookupIpFuture>,
|
lookup: LookupIpFuture,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: Address> ResolverFuture<T> {
|
impl<T: Address> ResolverFuture<T> {
|
||||||
pub fn new(req: Connect<T>, resolver: &AsyncResolver) -> Self {
|
pub fn new(req: Connect<T>, resolver: &AsyncResolver) -> Self {
|
||||||
let lookup = if let Some(host) = req.host().splitn(2, ':').next() {
|
let host = if let Some(host) = req.host().splitn(2, ':').next() {
|
||||||
resolver.lookup_ip(host)
|
host
|
||||||
} else {
|
} else {
|
||||||
resolver.lookup_ip(req.host())
|
req.host()
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Clone data to be moved to the lookup future
|
||||||
|
let host_clone = host.to_owned();
|
||||||
|
let resolver_clone = resolver.clone();
|
||||||
|
|
||||||
ResolverFuture {
|
ResolverFuture {
|
||||||
lookup,
|
lookup: Box::pin(async move {
|
||||||
|
let resolver = resolver_clone;
|
||||||
|
resolver.lookup_ip(host_clone).await
|
||||||
|
}),
|
||||||
req: Some(req),
|
req: Some(req),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -5,8 +5,8 @@ use std::task::{Context, Poll};
|
|||||||
use actix_rt::net::TcpStream;
|
use actix_rt::net::TcpStream;
|
||||||
use actix_service::{Service, ServiceFactory};
|
use actix_service::{Service, ServiceFactory};
|
||||||
use either::Either;
|
use either::Either;
|
||||||
use futures::future::{ok, Ready};
|
use futures_util::future::{ok, Ready};
|
||||||
use trust_dns_resolver::AsyncResolver;
|
use trust_dns_resolver::TokioAsyncResolver as AsyncResolver;
|
||||||
|
|
||||||
use crate::connect::{Address, Connect, Connection};
|
use crate::connect::{Address, Connect, Connection};
|
||||||
use crate::connector::{TcpConnector, TcpConnectorFactory};
|
use crate::connector::{TcpConnector, TcpConnectorFactory};
|
||||||
|
@@ -10,8 +10,8 @@ pub use tokio_openssl::{HandshakeError, SslStream};
|
|||||||
use actix_codec::{AsyncRead, AsyncWrite};
|
use actix_codec::{AsyncRead, AsyncWrite};
|
||||||
use actix_rt::net::TcpStream;
|
use actix_rt::net::TcpStream;
|
||||||
use actix_service::{Service, ServiceFactory};
|
use actix_service::{Service, ServiceFactory};
|
||||||
use futures::future::{err, ok, Either, FutureExt, LocalBoxFuture, Ready};
|
use futures_util::future::{err, ok, Either, FutureExt, LocalBoxFuture, Ready};
|
||||||
use trust_dns_resolver::AsyncResolver;
|
use trust_dns_resolver::TokioAsyncResolver as AsyncResolver;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
Address, Connect, ConnectError, ConnectService, ConnectServiceFactory, Connection,
|
Address, Connect, ConnectError, ConnectService, ConnectServiceFactory, Connection,
|
||||||
@@ -243,7 +243,7 @@ impl<T: Address> Future for OpensslConnectServiceResponse<T> {
|
|||||||
|
|
||||||
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> {
|
||||||
if let Some(ref mut fut) = self.fut1 {
|
if let Some(ref mut fut) = self.fut1 {
|
||||||
match futures::ready!(Pin::new(fut).poll(cx)) {
|
match futures_util::ready!(Pin::new(fut).poll(cx)) {
|
||||||
Ok(res) => {
|
Ok(res) => {
|
||||||
let _ = self.fut1.take();
|
let _ = self.fut1.take();
|
||||||
self.fut2 = Some(self.openssl.call(res));
|
self.fut2 = Some(self.openssl.call(res));
|
||||||
@@ -253,7 +253,7 @@ impl<T: Address> Future for OpensslConnectServiceResponse<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if let Some(ref mut fut) = self.fut2 {
|
if let Some(ref mut fut) = self.fut2 {
|
||||||
match futures::ready!(Pin::new(fut).poll(cx)) {
|
match futures_util::ready!(Pin::new(fut).poll(cx)) {
|
||||||
Ok(connect) => Poll::Ready(Ok(connect.into_parts().0)),
|
Ok(connect) => Poll::Ready(Ok(connect.into_parts().0)),
|
||||||
Err(e) => Poll::Ready(Err(ConnectError::Io(io::Error::new(
|
Err(e) => Poll::Ready(Err(ConnectError::Io(io::Error::new(
|
||||||
io::ErrorKind::Other,
|
io::ErrorKind::Other,
|
||||||
|
@@ -10,7 +10,7 @@ pub use tokio_rustls::{client::TlsStream, rustls::ClientConfig};
|
|||||||
|
|
||||||
use actix_codec::{AsyncRead, AsyncWrite};
|
use actix_codec::{AsyncRead, AsyncWrite};
|
||||||
use actix_service::{Service, ServiceFactory};
|
use actix_service::{Service, ServiceFactory};
|
||||||
use futures::future::{ok, Ready};
|
use futures_util::future::{ok, Ready};
|
||||||
use tokio_rustls::{Connect, TlsConnector};
|
use tokio_rustls::{Connect, TlsConnector};
|
||||||
use webpki::DNSNameRef;
|
use webpki::DNSNameRef;
|
||||||
|
|
||||||
@@ -38,7 +38,7 @@ where
|
|||||||
{
|
{
|
||||||
pub fn service(connector: Arc<ClientConfig>) -> RustlsConnectorService<T, U> {
|
pub fn service(connector: Arc<ClientConfig>) -> RustlsConnectorService<T, U> {
|
||||||
RustlsConnectorService {
|
RustlsConnectorService {
|
||||||
connector: connector,
|
connector,
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -126,7 +126,7 @@ where
|
|||||||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||||
let this = self.get_mut();
|
let this = self.get_mut();
|
||||||
Poll::Ready(
|
Poll::Ready(
|
||||||
futures::ready!(Pin::new(&mut this.fut).poll(cx)).map(|stream| {
|
futures_util::ready!(Pin::new(&mut this.fut).poll(cx)).map(|stream| {
|
||||||
let s = this.stream.take().unwrap();
|
let s = this.stream.take().unwrap();
|
||||||
trace!("SSL Handshake success: {:?}", s.host());
|
trace!("SSL Handshake success: {:?}", s.host());
|
||||||
s.replace(stream).1
|
s.replace(stream).1
|
||||||
|
@@ -2,10 +2,10 @@ use std::io;
|
|||||||
|
|
||||||
use actix_codec::{BytesCodec, Framed};
|
use actix_codec::{BytesCodec, Framed};
|
||||||
use actix_rt::net::TcpStream;
|
use actix_rt::net::TcpStream;
|
||||||
use actix_service::{service_fn, Service, ServiceFactory};
|
use actix_service::{fn_service, Service, ServiceFactory};
|
||||||
use actix_testing::TestServer;
|
use actix_testing::TestServer;
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use futures::SinkExt;
|
use futures_util::sink::SinkExt;
|
||||||
|
|
||||||
use actix_connect::resolver::{ResolverConfig, ResolverOpts};
|
use actix_connect::resolver::{ResolverConfig, ResolverOpts};
|
||||||
use actix_connect::Connect;
|
use actix_connect::Connect;
|
||||||
@@ -14,12 +14,10 @@ use actix_connect::Connect;
|
|||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_string() {
|
async fn test_string() {
|
||||||
let srv = TestServer::with(|| {
|
let srv = TestServer::with(|| {
|
||||||
service_fn(|io: TcpStream| {
|
fn_service(|io: TcpStream| async {
|
||||||
async {
|
let mut framed = Framed::new(io, BytesCodec);
|
||||||
let mut framed = Framed::new(io, BytesCodec);
|
framed.send(Bytes::from_static(b"test")).await?;
|
||||||
framed.send(Bytes::from_static(b"test")).await?;
|
Ok::<_, io::Error>(())
|
||||||
Ok::<_, io::Error>(())
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -33,12 +31,10 @@ async fn test_string() {
|
|||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_rustls_string() {
|
async fn test_rustls_string() {
|
||||||
let srv = TestServer::with(|| {
|
let srv = TestServer::with(|| {
|
||||||
service_fn(|io: TcpStream| {
|
fn_service(|io: TcpStream| async {
|
||||||
async {
|
let mut framed = Framed::new(io, BytesCodec);
|
||||||
let mut framed = Framed::new(io, BytesCodec);
|
framed.send(Bytes::from_static(b"test")).await?;
|
||||||
framed.send(Bytes::from_static(b"test")).await?;
|
Ok::<_, io::Error>(())
|
||||||
Ok::<_, io::Error>(())
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -51,16 +47,14 @@ async fn test_rustls_string() {
|
|||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_static_str() {
|
async fn test_static_str() {
|
||||||
let srv = TestServer::with(|| {
|
let srv = TestServer::with(|| {
|
||||||
service_fn(|io: TcpStream| {
|
fn_service(|io: TcpStream| async {
|
||||||
async {
|
let mut framed = Framed::new(io, BytesCodec);
|
||||||
let mut framed = Framed::new(io, BytesCodec);
|
framed.send(Bytes::from_static(b"test")).await?;
|
||||||
framed.send(Bytes::from_static(b"test")).await?;
|
Ok::<_, io::Error>(())
|
||||||
Ok::<_, io::Error>(())
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
let resolver = actix_connect::start_default_resolver();
|
let resolver = actix_connect::start_default_resolver().await.unwrap();
|
||||||
let mut conn = actix_connect::new_connector(resolver.clone());
|
let mut conn = actix_connect::new_connector(resolver.clone());
|
||||||
|
|
||||||
let con = conn.call(Connect::with("10", srv.addr())).await.unwrap();
|
let con = conn.call(Connect::with("10", srv.addr())).await.unwrap();
|
||||||
@@ -75,17 +69,17 @@ async fn test_static_str() {
|
|||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_new_service() {
|
async fn test_new_service() {
|
||||||
let srv = TestServer::with(|| {
|
let srv = TestServer::with(|| {
|
||||||
service_fn(|io: TcpStream| {
|
fn_service(|io: TcpStream| async {
|
||||||
async {
|
let mut framed = Framed::new(io, BytesCodec);
|
||||||
let mut framed = Framed::new(io, BytesCodec);
|
framed.send(Bytes::from_static(b"test")).await?;
|
||||||
framed.send(Bytes::from_static(b"test")).await?;
|
Ok::<_, io::Error>(())
|
||||||
Ok::<_, io::Error>(())
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
let resolver =
|
let resolver =
|
||||||
actix_connect::start_resolver(ResolverConfig::default(), ResolverOpts::default());
|
actix_connect::start_resolver(ResolverConfig::default(), ResolverOpts::default())
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
let factory = actix_connect::new_connector_factory(resolver);
|
let factory = actix_connect::new_connector_factory(resolver);
|
||||||
|
|
||||||
@@ -100,12 +94,10 @@ async fn test_uri() {
|
|||||||
use std::convert::TryFrom;
|
use std::convert::TryFrom;
|
||||||
|
|
||||||
let srv = TestServer::with(|| {
|
let srv = TestServer::with(|| {
|
||||||
service_fn(|io: TcpStream| {
|
fn_service(|io: TcpStream| async {
|
||||||
async {
|
let mut framed = Framed::new(io, BytesCodec);
|
||||||
let mut framed = Framed::new(io, BytesCodec);
|
framed.send(Bytes::from_static(b"test")).await?;
|
||||||
framed.send(Bytes::from_static(b"test")).await?;
|
Ok::<_, io::Error>(())
|
||||||
Ok::<_, io::Error>(())
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -121,12 +113,10 @@ async fn test_rustls_uri() {
|
|||||||
use std::convert::TryFrom;
|
use std::convert::TryFrom;
|
||||||
|
|
||||||
let srv = TestServer::with(|| {
|
let srv = TestServer::with(|| {
|
||||||
service_fn(|io: TcpStream| {
|
fn_service(|io: TcpStream| async {
|
||||||
async {
|
let mut framed = Framed::new(io, BytesCodec);
|
||||||
let mut framed = Framed::new(io, BytesCodec);
|
framed.send(Bytes::from_static(b"test")).await?;
|
||||||
framed.send(Bytes::from_static(b"test")).await?;
|
Ok::<_, io::Error>(())
|
||||||
Ok::<_, io::Error>(())
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@@ -1,5 +1,21 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [0.5.0] - 2019-12-29
|
||||||
|
|
||||||
|
* Simplify state management
|
||||||
|
|
||||||
|
* Allow to set custom output stream
|
||||||
|
|
||||||
|
* Removed disconnect callback
|
||||||
|
|
||||||
|
## [0.4.1] - 2019-12-11
|
||||||
|
|
||||||
|
* Disconnect callback accepts owned state
|
||||||
|
|
||||||
|
## [0.4.0] - 2019-12-11
|
||||||
|
|
||||||
|
* Remove `E` param
|
||||||
|
|
||||||
## [0.3.0-alpha.3] - 2019-12-07
|
## [0.3.0-alpha.3] - 2019-12-07
|
||||||
|
|
||||||
* Migrate to tokio 0.2
|
* Migrate to tokio 0.2
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-ioframe"
|
name = "actix-ioframe"
|
||||||
version = "0.3.0-alpha.3"
|
version = "0.5.0"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix framed service"
|
description = "Actix framed service"
|
||||||
keywords = ["network", "framework", "async", "futures"]
|
keywords = ["network", "framework", "async", "futures"]
|
||||||
@@ -9,25 +9,25 @@ repository = "https://github.com/actix/actix-net.git"
|
|||||||
documentation = "https://docs.rs/actix-ioframe/"
|
documentation = "https://docs.rs/actix-ioframe/"
|
||||||
categories = ["network-programming", "asynchronous"]
|
categories = ["network-programming", "asynchronous"]
|
||||||
license = "MIT/Apache-2.0"
|
license = "MIT/Apache-2.0"
|
||||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
workspace = ".."
|
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
name = "actix_ioframe"
|
name = "actix_ioframe"
|
||||||
path = "src/lib.rs"
|
path = "src/lib.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-service = "1.0.0-alpha.3"
|
actix-service = "1.0.1"
|
||||||
actix-codec = "0.2.0-alpha.2"
|
actix-codec = "0.2.0"
|
||||||
actix-utils = "1.0.0-alpha.2"
|
actix-utils = "1.0.4"
|
||||||
actix-rt = "1.0.0-alpha.2"
|
actix-rt = "1.0.0"
|
||||||
bytes = "0.5"
|
bytes = "0.5.3"
|
||||||
either = "1.5.2"
|
either = "1.5.3"
|
||||||
futures = "0.3.1"
|
futures-sink = { version = "0.3.4", default-features = false }
|
||||||
|
futures-core = { version = "0.3.4", default-features = false }
|
||||||
pin-project = "0.4.6"
|
pin-project = "0.4.6"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-connect = "1.0.0-alpha.2"
|
actix-connect = "2.0.0-alpha.2"
|
||||||
actix-testing = "1.0.0-alpha.2"
|
actix-testing = "1.0.0"
|
||||||
|
futures-util = { version = "0.3.4", default-features = false }
|
||||||
|
@@ -1,39 +0,0 @@
|
|||||||
//! Custom cell impl
|
|
||||||
|
|
||||||
use std::cell::UnsafeCell;
|
|
||||||
use std::fmt;
|
|
||||||
use std::rc::Rc;
|
|
||||||
|
|
||||||
pub(crate) struct Cell<T> {
|
|
||||||
inner: Rc<UnsafeCell<T>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> Clone for Cell<T> {
|
|
||||||
fn clone(&self) -> Self {
|
|
||||||
Self {
|
|
||||||
inner: self.inner.clone(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: fmt::Debug> fmt::Debug for Cell<T> {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
self.inner.fmt(f)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> Cell<T> {
|
|
||||||
pub fn new(inner: T) -> Self {
|
|
||||||
Self {
|
|
||||||
inner: Rc::new(UnsafeCell::new(inner)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) unsafe fn get_ref(&mut self) -> &T {
|
|
||||||
&*self.inner.as_ref().get()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) unsafe fn get_mut(&mut self) -> &mut T {
|
|
||||||
&mut *self.inner.as_ref().get()
|
|
||||||
}
|
|
||||||
}
|
|
@@ -3,20 +3,21 @@ use std::pin::Pin;
|
|||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
|
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
|
||||||
use actix_utils::mpsc;
|
use actix_utils::mpsc::Receiver;
|
||||||
use futures::Stream;
|
use futures_core::stream::Stream;
|
||||||
|
|
||||||
use crate::dispatcher::FramedMessage;
|
pub struct Connect<Io, Codec>
|
||||||
use crate::sink::Sink;
|
where
|
||||||
|
Codec: Encoder + Decoder,
|
||||||
pub struct Connect<Io, St = (), Codec = ()> {
|
{
|
||||||
io: Io,
|
io: Io,
|
||||||
_t: PhantomData<(St, Codec)>,
|
_t: PhantomData<Codec>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<Io> Connect<Io>
|
impl<Io, Codec> Connect<Io, Codec>
|
||||||
where
|
where
|
||||||
Io: AsyncRead + AsyncWrite,
|
Io: AsyncRead + AsyncWrite,
|
||||||
|
Codec: Encoder + Decoder,
|
||||||
{
|
{
|
||||||
pub(crate) fn new(io: Io) -> Self {
|
pub(crate) fn new(io: Io) -> Self {
|
||||||
Self {
|
Self {
|
||||||
@@ -25,36 +26,27 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn codec<Codec>(self, codec: Codec) -> ConnectResult<Io, (), Codec>
|
pub fn codec(
|
||||||
where
|
self,
|
||||||
Codec: Encoder + Decoder,
|
codec: Codec,
|
||||||
{
|
) -> ConnectResult<Io, (), Codec, Receiver<<Codec as Encoder>::Item>> {
|
||||||
let (tx, rx) = mpsc::channel();
|
|
||||||
let sink = Sink::new(tx);
|
|
||||||
|
|
||||||
ConnectResult {
|
ConnectResult {
|
||||||
state: (),
|
state: (),
|
||||||
|
out: None,
|
||||||
framed: Framed::new(self.io, codec),
|
framed: Framed::new(self.io, codec),
|
||||||
rx,
|
|
||||||
sink,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[pin_project::pin_project]
|
#[pin_project::pin_project]
|
||||||
pub struct ConnectResult<Io, St, Codec: Encoder + Decoder> {
|
pub struct ConnectResult<Io, St, Codec: Encoder + Decoder, Out> {
|
||||||
pub(crate) state: St,
|
pub(crate) state: St,
|
||||||
|
pub(crate) out: Option<Out>,
|
||||||
|
#[pin]
|
||||||
pub(crate) framed: Framed<Io, Codec>,
|
pub(crate) framed: Framed<Io, Codec>,
|
||||||
pub(crate) rx: mpsc::Receiver<FramedMessage<<Codec as Encoder>::Item>>,
|
|
||||||
pub(crate) sink: Sink<<Codec as Encoder>::Item>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<Io, St, Codec: Encoder + Decoder> ConnectResult<Io, St, Codec> {
|
impl<Io, St, Codec: Encoder + Decoder, Out: Unpin> ConnectResult<Io, St, Codec, Out> {
|
||||||
#[inline]
|
|
||||||
pub fn sink(&self) -> &Sink<<Codec as Encoder>::Item> {
|
|
||||||
&self.sink
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn get_ref(&self) -> &Io {
|
pub fn get_ref(&self) -> &Io {
|
||||||
self.framed.get_ref()
|
self.framed.get_ref()
|
||||||
@@ -65,18 +57,28 @@ impl<Io, St, Codec: Encoder + Decoder> ConnectResult<Io, St, Codec> {
|
|||||||
self.framed.get_mut()
|
self.framed.get_mut()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn out<U>(self, out: U) -> ConnectResult<Io, St, Codec, U>
|
||||||
|
where
|
||||||
|
U: Stream<Item = <Codec as Encoder>::Item> + Unpin,
|
||||||
|
{
|
||||||
|
ConnectResult {
|
||||||
|
state: self.state,
|
||||||
|
framed: self.framed,
|
||||||
|
out: Some(out),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn state<S>(self, state: S) -> ConnectResult<Io, S, Codec> {
|
pub fn state<S>(self, state: S) -> ConnectResult<Io, S, Codec, Out> {
|
||||||
ConnectResult {
|
ConnectResult {
|
||||||
state,
|
state,
|
||||||
framed: self.framed,
|
framed: self.framed,
|
||||||
rx: self.rx,
|
out: self.out,
|
||||||
sink: self.sink,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<Io, St, Codec> Stream for ConnectResult<Io, St, Codec>
|
impl<Io, St, Codec, Out> Stream for ConnectResult<Io, St, Codec, Out>
|
||||||
where
|
where
|
||||||
Io: AsyncRead + AsyncWrite,
|
Io: AsyncRead + AsyncWrite,
|
||||||
Codec: Encoder + Decoder,
|
Codec: Encoder + Decoder,
|
||||||
@@ -88,15 +90,16 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<Io, St, Codec> futures::Sink<<Codec as Encoder>::Item> for ConnectResult<Io, St, Codec>
|
impl<Io, St, Codec, Out> futures_sink::Sink<<Codec as Encoder>::Item>
|
||||||
|
for ConnectResult<Io, St, Codec, Out>
|
||||||
where
|
where
|
||||||
Io: AsyncRead + AsyncWrite,
|
Io: AsyncRead + AsyncWrite,
|
||||||
Codec: Encoder + Decoder,
|
Codec: Encoder + Decoder,
|
||||||
{
|
{
|
||||||
type Error = <Codec as Encoder>::Error;
|
type Error = <Codec as Encoder>::Error;
|
||||||
|
|
||||||
fn poll_ready(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
fn poll_ready(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||||
if self.framed.is_ready() {
|
if self.as_mut().project().framed.is_write_ready() {
|
||||||
Poll::Ready(Ok(()))
|
Poll::Ready(Ok(()))
|
||||||
} else {
|
} else {
|
||||||
Poll::Pending
|
Poll::Pending
|
||||||
@@ -110,11 +113,11 @@ where
|
|||||||
self.project().framed.write(item)
|
self.project().framed.write(item)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||||
self.get_mut().framed.flush(cx)
|
self.as_mut().project().framed.flush(cx)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||||
self.get_mut().framed.close(cx)
|
self.as_mut().project().framed.close(cx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,87 +1,59 @@
|
|||||||
//! Framed dispatcher service and related utilities
|
//! Framed dispatcher service and related utilities
|
||||||
use std::collections::VecDeque;
|
|
||||||
use std::mem;
|
|
||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
use std::rc::Rc;
|
|
||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
|
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
|
||||||
use actix_service::{IntoService, Service};
|
use actix_service::Service;
|
||||||
use actix_utils::task::LocalWaker;
|
use actix_utils::mpsc;
|
||||||
use actix_utils::{mpsc, oneshot};
|
use futures_core::stream::Stream;
|
||||||
use futures::future::ready;
|
use pin_project::pin_project;
|
||||||
use futures::{FutureExt, Sink as FutureSink, Stream};
|
|
||||||
use log::debug;
|
use log::debug;
|
||||||
|
|
||||||
use crate::cell::Cell;
|
|
||||||
use crate::error::ServiceError;
|
use crate::error::ServiceError;
|
||||||
use crate::item::Item;
|
|
||||||
use crate::sink::Sink;
|
|
||||||
|
|
||||||
type Request<S, U> = Item<S, U>;
|
type Request<U> = <U as Decoder>::Item;
|
||||||
type Response<U> = <U as Encoder>::Item;
|
type Response<U> = <U as Encoder>::Item;
|
||||||
|
|
||||||
pub(crate) enum FramedMessage<T> {
|
|
||||||
Message(T),
|
|
||||||
Close,
|
|
||||||
WaitClose(oneshot::Sender<()>),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// FramedTransport - is a future that reads frames from Framed object
|
/// FramedTransport - is a future that reads frames from Framed object
|
||||||
/// and pass then to the service.
|
/// and pass then to the service.
|
||||||
#[pin_project::pin_project]
|
#[pin_project]
|
||||||
pub(crate) struct FramedDispatcher<St, S, T, U>
|
pub(crate) struct Dispatcher<S, T, U, Out>
|
||||||
where
|
where
|
||||||
St: Clone,
|
S: Service<Request = Request<U>, Response = Option<Response<U>>>,
|
||||||
S: Service<Request = Request<St, U>, Response = Option<Response<U>>>,
|
|
||||||
S::Error: 'static,
|
S::Error: 'static,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
T: AsyncRead + AsyncWrite,
|
T: AsyncRead + AsyncWrite,
|
||||||
U: Encoder + Decoder,
|
U: Encoder + Decoder,
|
||||||
<U as Encoder>::Item: 'static,
|
<U as Encoder>::Item: 'static,
|
||||||
<U as Encoder>::Error: std::fmt::Debug,
|
<U as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <U as Encoder>::Item> + Unpin,
|
||||||
{
|
{
|
||||||
service: S,
|
service: S,
|
||||||
sink: Sink<<U as Encoder>::Item>,
|
sink: Option<Out>,
|
||||||
state: St,
|
state: FramedState<S, U>,
|
||||||
dispatch_state: FramedState<S, U>,
|
#[pin]
|
||||||
framed: Framed<T, U>,
|
framed: Framed<T, U>,
|
||||||
rx: Option<mpsc::Receiver<FramedMessage<<U as Encoder>::Item>>>,
|
rx: mpsc::Receiver<Result<<U as Encoder>::Item, S::Error>>,
|
||||||
inner: Cell<FramedDispatcherInner<<U as Encoder>::Item, S::Error>>,
|
|
||||||
disconnect: Option<Rc<dyn Fn(&mut St, bool)>>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<St, S, T, U> FramedDispatcher<St, S, T, U>
|
impl<S, T, U, Out> Dispatcher<S, T, U, Out>
|
||||||
where
|
where
|
||||||
St: Clone,
|
S: Service<Request = Request<U>, Response = Option<Response<U>>>,
|
||||||
S: Service<Request = Request<St, U>, Response = Option<Response<U>>>,
|
|
||||||
S::Error: 'static,
|
S::Error: 'static,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
T: AsyncRead + AsyncWrite,
|
T: AsyncRead + AsyncWrite,
|
||||||
U: Decoder + Encoder,
|
U: Decoder + Encoder,
|
||||||
<U as Encoder>::Item: 'static,
|
<U as Encoder>::Item: 'static,
|
||||||
<U as Encoder>::Error: std::fmt::Debug,
|
<U as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <U as Encoder>::Item> + Unpin,
|
||||||
{
|
{
|
||||||
pub(crate) fn new<F: IntoService<S>>(
|
pub(crate) fn new(framed: Framed<T, U>, service: S, sink: Option<Out>) -> Self {
|
||||||
framed: Framed<T, U>,
|
Dispatcher {
|
||||||
state: St,
|
|
||||||
service: F,
|
|
||||||
rx: mpsc::Receiver<FramedMessage<<U as Encoder>::Item>>,
|
|
||||||
sink: Sink<<U as Encoder>::Item>,
|
|
||||||
disconnect: Option<Rc<dyn Fn(&mut St, bool)>>,
|
|
||||||
) -> Self {
|
|
||||||
FramedDispatcher {
|
|
||||||
framed,
|
|
||||||
state,
|
|
||||||
sink,
|
sink,
|
||||||
disconnect,
|
service,
|
||||||
rx: Some(rx),
|
framed,
|
||||||
service: service.into_service(),
|
rx: mpsc::channel().1,
|
||||||
dispatch_state: FramedState::Processing,
|
state: FramedState::Processing,
|
||||||
inner: Cell::new(FramedDispatcherInner {
|
|
||||||
buf: VecDeque::new(),
|
|
||||||
task: LocalWaker::new(),
|
|
||||||
}),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -90,307 +62,187 @@ enum FramedState<S: Service, U: Encoder + Decoder> {
|
|||||||
Processing,
|
Processing,
|
||||||
Error(ServiceError<S::Error, U>),
|
Error(ServiceError<S::Error, U>),
|
||||||
FramedError(ServiceError<S::Error, U>),
|
FramedError(ServiceError<S::Error, U>),
|
||||||
FlushAndStop(Vec<oneshot::Sender<()>>),
|
FlushAndStop,
|
||||||
Stopping,
|
Stopping,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S: Service, U: Encoder + Decoder> FramedState<S, U> {
|
impl<S: Service, U: Encoder + Decoder> FramedState<S, U> {
|
||||||
fn stop(&mut self, tx: Option<oneshot::Sender<()>>) {
|
fn take_error(&mut self) -> ServiceError<S::Error, U> {
|
||||||
match self {
|
match std::mem::replace(self, FramedState::Processing) {
|
||||||
FramedState::FlushAndStop(ref mut vec) => {
|
FramedState::Error(err) => err,
|
||||||
if let Some(tx) = tx {
|
_ => panic!(),
|
||||||
vec.push(tx)
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
FramedState::Processing => {
|
fn take_framed_error(&mut self) -> ServiceError<S::Error, U> {
|
||||||
*self = FramedState::FlushAndStop(if let Some(tx) = tx {
|
match std::mem::replace(self, FramedState::Processing) {
|
||||||
vec![tx]
|
FramedState::FramedError(err) => err,
|
||||||
} else {
|
_ => panic!(),
|
||||||
Vec::new()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
FramedState::Error(_) | FramedState::FramedError(_) | FramedState::Stopping => {
|
|
||||||
if let Some(tx) = tx {
|
|
||||||
let _ = tx.send(());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct FramedDispatcherInner<I, E> {
|
impl<S, T, U, Out> Dispatcher<S, T, U, Out>
|
||||||
buf: VecDeque<Result<I, E>>,
|
|
||||||
task: LocalWaker,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<St, S, T, U> FramedDispatcher<St, S, T, U>
|
|
||||||
where
|
where
|
||||||
St: Clone,
|
S: Service<Request = Request<U>, Response = Option<Response<U>>>,
|
||||||
S: Service<Request = Request<St, U>, Response = Option<Response<U>>>,
|
|
||||||
S::Error: 'static,
|
S::Error: 'static,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
T: AsyncRead + AsyncWrite,
|
T: AsyncRead + AsyncWrite,
|
||||||
U: Decoder + Encoder,
|
U: Decoder + Encoder,
|
||||||
<U as Encoder>::Item: 'static,
|
<U as Encoder>::Item: 'static,
|
||||||
<U as Encoder>::Error: std::fmt::Debug,
|
<U as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <U as Encoder>::Item> + Unpin,
|
||||||
{
|
{
|
||||||
pub(crate) fn poll(
|
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> bool {
|
||||||
&mut self,
|
loop {
|
||||||
cx: &mut Context<'_>,
|
let this = self.as_mut().project();
|
||||||
) -> Poll<Result<(), ServiceError<S::Error, U>>> {
|
match this.service.poll_ready(cx) {
|
||||||
let this = self;
|
Poll::Ready(Ok(_)) => {
|
||||||
unsafe { this.inner.get_ref().task.register(cx.waker()) };
|
let item = match this.framed.next_item(cx) {
|
||||||
|
Poll::Ready(Some(Ok(el))) => el,
|
||||||
|
Poll::Ready(Some(Err(err))) => {
|
||||||
|
*this.state = FramedState::FramedError(ServiceError::Decoder(err));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
Poll::Pending => return false,
|
||||||
|
Poll::Ready(None) => {
|
||||||
|
log::trace!("Client disconnected");
|
||||||
|
*this.state = FramedState::Stopping;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
poll(
|
let tx = this.rx.sender();
|
||||||
cx,
|
let fut = this.service.call(item);
|
||||||
&mut this.service,
|
actix_rt::spawn(async move {
|
||||||
&mut this.state,
|
let item = fut.await;
|
||||||
&mut this.sink,
|
|
||||||
&mut this.framed,
|
|
||||||
&mut this.dispatch_state,
|
|
||||||
&mut this.rx,
|
|
||||||
&mut this.inner,
|
|
||||||
&mut this.disconnect,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn poll<St, S, T, U>(
|
|
||||||
cx: &mut Context<'_>,
|
|
||||||
srv: &mut S,
|
|
||||||
state: &mut St,
|
|
||||||
sink: &mut Sink<<U as Encoder>::Item>,
|
|
||||||
framed: &mut Framed<T, U>,
|
|
||||||
dispatch_state: &mut FramedState<S, U>,
|
|
||||||
rx: &mut Option<mpsc::Receiver<FramedMessage<<U as Encoder>::Item>>>,
|
|
||||||
inner: &mut Cell<FramedDispatcherInner<<U as Encoder>::Item, S::Error>>,
|
|
||||||
disconnect: &mut Option<Rc<dyn Fn(&mut St, bool)>>,
|
|
||||||
) -> Poll<Result<(), ServiceError<S::Error, U>>>
|
|
||||||
where
|
|
||||||
St: Clone,
|
|
||||||
S: Service<Request = Request<St, U>, Response = Option<Response<U>>>,
|
|
||||||
S::Error: 'static,
|
|
||||||
S::Future: 'static,
|
|
||||||
T: AsyncRead + AsyncWrite,
|
|
||||||
U: Decoder + Encoder,
|
|
||||||
<U as Encoder>::Item: 'static,
|
|
||||||
<U as Encoder>::Error: std::fmt::Debug,
|
|
||||||
{
|
|
||||||
match mem::replace(dispatch_state, FramedState::Processing) {
|
|
||||||
FramedState::Processing => {
|
|
||||||
if poll_read(cx, srv, state, sink, framed, dispatch_state, inner)
|
|
||||||
|| poll_write(cx, framed, dispatch_state, rx, inner)
|
|
||||||
{
|
|
||||||
poll(
|
|
||||||
cx,
|
|
||||||
srv,
|
|
||||||
state,
|
|
||||||
sink,
|
|
||||||
framed,
|
|
||||||
dispatch_state,
|
|
||||||
rx,
|
|
||||||
inner,
|
|
||||||
disconnect,
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
Poll::Pending
|
|
||||||
}
|
|
||||||
}
|
|
||||||
FramedState::Error(err) => {
|
|
||||||
if framed.is_write_buf_empty()
|
|
||||||
|| (poll_write(cx, framed, dispatch_state, rx, inner)
|
|
||||||
|| framed.is_write_buf_empty())
|
|
||||||
{
|
|
||||||
if let Some(ref disconnect) = disconnect {
|
|
||||||
(&*disconnect)(&mut *state, true);
|
|
||||||
}
|
|
||||||
Poll::Ready(Err(err))
|
|
||||||
} else {
|
|
||||||
*dispatch_state = FramedState::Error(err);
|
|
||||||
Poll::Pending
|
|
||||||
}
|
|
||||||
}
|
|
||||||
FramedState::FlushAndStop(mut vec) => {
|
|
||||||
if !framed.is_write_buf_empty() {
|
|
||||||
match Pin::new(framed).poll_flush(cx) {
|
|
||||||
Poll::Ready(Err(err)) => {
|
|
||||||
debug!("Error sending data: {:?}", err);
|
|
||||||
}
|
|
||||||
Poll::Pending => {
|
|
||||||
*dispatch_state = FramedState::FlushAndStop(vec);
|
|
||||||
return Poll::Pending;
|
|
||||||
}
|
|
||||||
Poll::Ready(_) => (),
|
|
||||||
}
|
|
||||||
};
|
|
||||||
for tx in vec.drain(..) {
|
|
||||||
let _ = tx.send(());
|
|
||||||
}
|
|
||||||
if let Some(ref disconnect) = disconnect {
|
|
||||||
(&*disconnect)(&mut *state, false);
|
|
||||||
}
|
|
||||||
Poll::Ready(Ok(()))
|
|
||||||
}
|
|
||||||
FramedState::FramedError(err) => {
|
|
||||||
if let Some(ref disconnect) = disconnect {
|
|
||||||
(&*disconnect)(&mut *state, true);
|
|
||||||
}
|
|
||||||
Poll::Ready(Err(err))
|
|
||||||
}
|
|
||||||
FramedState::Stopping => {
|
|
||||||
if let Some(ref disconnect) = disconnect {
|
|
||||||
(&*disconnect)(&mut *state, false);
|
|
||||||
}
|
|
||||||
Poll::Ready(Ok(()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn poll_read<St, S, T, U>(
|
|
||||||
cx: &mut Context<'_>,
|
|
||||||
srv: &mut S,
|
|
||||||
state: &mut St,
|
|
||||||
sink: &mut Sink<<U as Encoder>::Item>,
|
|
||||||
framed: &mut Framed<T, U>,
|
|
||||||
dispatch_state: &mut FramedState<S, U>,
|
|
||||||
inner: &mut Cell<FramedDispatcherInner<<U as Encoder>::Item, S::Error>>,
|
|
||||||
) -> bool
|
|
||||||
where
|
|
||||||
St: Clone,
|
|
||||||
S: Service<Request = Request<St, U>, Response = Option<Response<U>>>,
|
|
||||||
S::Error: 'static,
|
|
||||||
S::Future: 'static,
|
|
||||||
T: AsyncRead + AsyncWrite,
|
|
||||||
U: Decoder + Encoder,
|
|
||||||
<U as Encoder>::Item: 'static,
|
|
||||||
<U as Encoder>::Error: std::fmt::Debug,
|
|
||||||
{
|
|
||||||
loop {
|
|
||||||
match srv.poll_ready(cx) {
|
|
||||||
Poll::Ready(Ok(_)) => {
|
|
||||||
let item = match framed.next_item(cx) {
|
|
||||||
Poll::Ready(Some(Ok(el))) => el,
|
|
||||||
Poll::Ready(Some(Err(err))) => {
|
|
||||||
*dispatch_state = FramedState::FramedError(ServiceError::Decoder(err));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
Poll::Pending => return false,
|
|
||||||
Poll::Ready(None) => {
|
|
||||||
log::trace!("Client disconnected");
|
|
||||||
*dispatch_state = FramedState::Stopping;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut cell = inner.clone();
|
|
||||||
actix_rt::spawn(srv.call(Item::new(state.clone(), sink.clone(), item)).then(
|
|
||||||
move |item| {
|
|
||||||
let item = match item {
|
let item = match item {
|
||||||
Ok(Some(item)) => Ok(item),
|
Ok(Some(item)) => Ok(item),
|
||||||
Ok(None) => return ready(()),
|
Ok(None) => return,
|
||||||
Err(err) => Err(err),
|
Err(err) => Err(err),
|
||||||
};
|
};
|
||||||
unsafe {
|
let _ = tx.send(item);
|
||||||
let inner = cell.get_mut();
|
});
|
||||||
inner.buf.push_back(item);
|
}
|
||||||
inner.task.wake();
|
Poll::Pending => return false,
|
||||||
}
|
Poll::Ready(Err(err)) => {
|
||||||
ready(())
|
*this.state = FramedState::Error(ServiceError::Service(err));
|
||||||
},
|
return true;
|
||||||
));
|
}
|
||||||
}
|
|
||||||
Poll::Pending => return false,
|
|
||||||
Poll::Ready(Err(err)) => {
|
|
||||||
*dispatch_state = FramedState::Error(ServiceError::Service(err));
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/// write to framed object
|
/// write to framed object
|
||||||
fn poll_write<St, S, T, U>(
|
fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> bool {
|
||||||
cx: &mut Context<'_>,
|
loop {
|
||||||
framed: &mut Framed<T, U>,
|
let mut this = self.as_mut().project();
|
||||||
dispatch_state: &mut FramedState<S, U>,
|
while !this.framed.is_write_buf_full() {
|
||||||
rx: &mut Option<mpsc::Receiver<FramedMessage<<U as Encoder>::Item>>>,
|
match Pin::new(&mut this.rx).poll_next(cx) {
|
||||||
inner: &mut Cell<FramedDispatcherInner<<U as Encoder>::Item, S::Error>>,
|
Poll::Ready(Some(Ok(msg))) => {
|
||||||
) -> bool
|
if let Err(err) = this.framed.as_mut().write(msg) {
|
||||||
where
|
*this.state = FramedState::FramedError(ServiceError::Encoder(err));
|
||||||
S: Service<Request = Request<St, U>, Response = Option<Response<U>>>,
|
|
||||||
S::Error: 'static,
|
|
||||||
S::Future: 'static,
|
|
||||||
T: AsyncRead + AsyncWrite,
|
|
||||||
U: Decoder + Encoder,
|
|
||||||
<U as Encoder>::Item: 'static,
|
|
||||||
<U as Encoder>::Error: std::fmt::Debug,
|
|
||||||
{
|
|
||||||
let inner = unsafe { inner.get_mut() };
|
|
||||||
let mut rx_done = rx.is_none();
|
|
||||||
let mut buf_empty = inner.buf.is_empty();
|
|
||||||
loop {
|
|
||||||
while !framed.is_write_buf_full() {
|
|
||||||
if !buf_empty {
|
|
||||||
match inner.buf.pop_front().unwrap() {
|
|
||||||
Ok(msg) => {
|
|
||||||
if let Err(err) = framed.write(msg) {
|
|
||||||
*dispatch_state =
|
|
||||||
FramedState::FramedError(ServiceError::Encoder(err));
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
buf_empty = inner.buf.is_empty();
|
continue;
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Poll::Ready(Some(Err(err))) => {
|
||||||
*dispatch_state = FramedState::Error(ServiceError::Service(err));
|
*this.state = FramedState::Error(ServiceError::Service(err));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
Poll::Ready(None) | Poll::Pending => (),
|
||||||
|
}
|
||||||
|
|
||||||
|
if this.sink.is_some() {
|
||||||
|
match Pin::new(this.sink.as_mut().unwrap()).poll_next(cx) {
|
||||||
|
Poll::Ready(Some(msg)) => {
|
||||||
|
if let Err(err) = this.framed.as_mut().write(msg) {
|
||||||
|
*this.state =
|
||||||
|
FramedState::FramedError(ServiceError::Encoder(err));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Poll::Ready(None) => {
|
||||||
|
let _ = this.sink.take();
|
||||||
|
*this.state = FramedState::FlushAndStop;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
Poll::Pending => (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if !this.framed.is_write_buf_empty() {
|
||||||
|
match this.framed.as_mut().flush(cx) {
|
||||||
|
Poll::Pending => break,
|
||||||
|
Poll::Ready(Ok(_)) => (),
|
||||||
|
Poll::Ready(Err(err)) => {
|
||||||
|
debug!("Error sending data: {:?}", err);
|
||||||
|
*this.state = FramedState::FramedError(ServiceError::Encoder(err));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
} else {
|
||||||
|
|
||||||
if !rx_done && rx.is_some() {
|
|
||||||
match Pin::new(rx.as_mut().unwrap()).poll_next(cx) {
|
|
||||||
Poll::Ready(Some(FramedMessage::Message(msg))) => {
|
|
||||||
if let Err(err) = framed.write(msg) {
|
|
||||||
*dispatch_state =
|
|
||||||
FramedState::FramedError(ServiceError::Encoder(err));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Poll::Ready(Some(FramedMessage::Close)) => {
|
|
||||||
dispatch_state.stop(None);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
Poll::Ready(Some(FramedMessage::WaitClose(tx))) => {
|
|
||||||
dispatch_state.stop(Some(tx));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
Poll::Ready(None) => {
|
|
||||||
rx_done = true;
|
|
||||||
let _ = rx.take();
|
|
||||||
}
|
|
||||||
Poll::Pending => rx_done = true,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if rx_done && buf_empty {
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
false
|
||||||
if !framed.is_write_buf_empty() {
|
|
||||||
match framed.flush(cx) {
|
|
||||||
Poll::Pending => break,
|
|
||||||
Poll::Ready(Err(err)) => {
|
|
||||||
debug!("Error sending data: {:?}", err);
|
|
||||||
*dispatch_state = FramedState::FramedError(ServiceError::Encoder(err));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
Poll::Ready(_) => (),
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
false
|
pub(crate) fn poll(
|
||||||
|
mut self: Pin<&mut Self>,
|
||||||
|
cx: &mut Context<'_>,
|
||||||
|
) -> Poll<Result<(), ServiceError<S::Error, U>>> {
|
||||||
|
let mut this = self.as_mut().project();
|
||||||
|
match this.state {
|
||||||
|
FramedState::Processing => loop {
|
||||||
|
let read = self.as_mut().poll_read(cx);
|
||||||
|
let write = self.as_mut().poll_write(cx);
|
||||||
|
if read || write {
|
||||||
|
continue;
|
||||||
|
} else {
|
||||||
|
return Poll::Pending;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
FramedState::Error(_) => {
|
||||||
|
// flush write buffer
|
||||||
|
if !this.framed.is_write_buf_empty() {
|
||||||
|
if let Poll::Pending = this.framed.flush(cx) {
|
||||||
|
return Poll::Pending;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Poll::Ready(Err(this.state.take_error()))
|
||||||
|
}
|
||||||
|
FramedState::FlushAndStop => {
|
||||||
|
// drain service responses
|
||||||
|
match Pin::new(this.rx).poll_next(cx) {
|
||||||
|
Poll::Ready(Some(Ok(msg))) => {
|
||||||
|
if this.framed.as_mut().write(msg).is_err() {
|
||||||
|
return Poll::Ready(Ok(()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Poll::Ready(Some(Err(_))) => return Poll::Ready(Ok(())),
|
||||||
|
Poll::Ready(None) | Poll::Pending => (),
|
||||||
|
}
|
||||||
|
|
||||||
|
// flush io
|
||||||
|
if !this.framed.is_write_buf_empty() {
|
||||||
|
match this.framed.flush(cx) {
|
||||||
|
Poll::Ready(Err(err)) => {
|
||||||
|
debug!("Error sending data: {:?}", err);
|
||||||
|
}
|
||||||
|
Poll::Pending => {
|
||||||
|
return Poll::Pending;
|
||||||
|
}
|
||||||
|
Poll::Ready(_) => (),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Poll::Ready(Ok(()))
|
||||||
|
}
|
||||||
|
FramedState::FramedError(_) => Poll::Ready(Err(this.state.take_framed_error())),
|
||||||
|
FramedState::Stopping => Poll::Ready(Ok(())),
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,82 +0,0 @@
|
|||||||
use std::fmt;
|
|
||||||
use std::ops::{Deref, DerefMut};
|
|
||||||
|
|
||||||
use actix_codec::{Decoder, Encoder};
|
|
||||||
|
|
||||||
use crate::sink::Sink;
|
|
||||||
|
|
||||||
pub struct Item<St, Codec: Encoder + Decoder> {
|
|
||||||
state: St,
|
|
||||||
sink: Sink<<Codec as Encoder>::Item>,
|
|
||||||
item: <Codec as Decoder>::Item,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<St, Codec> Item<St, Codec>
|
|
||||||
where
|
|
||||||
Codec: Encoder + Decoder,
|
|
||||||
{
|
|
||||||
pub(crate) fn new(
|
|
||||||
state: St,
|
|
||||||
sink: Sink<<Codec as Encoder>::Item>,
|
|
||||||
item: <Codec as Decoder>::Item,
|
|
||||||
) -> Self {
|
|
||||||
Item { state, sink, item }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn state(&self) -> &St {
|
|
||||||
&self.state
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn state_mut(&mut self) -> &mut St {
|
|
||||||
&mut self.state
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn sink(&self) -> &Sink<<Codec as Encoder>::Item> {
|
|
||||||
&self.sink
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn into_inner(self) -> <Codec as Decoder>::Item {
|
|
||||||
self.item
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn into_parts(self) -> (St, Sink<<Codec as Encoder>::Item>, <Codec as Decoder>::Item) {
|
|
||||||
(self.state, self.sink, self.item)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<St, Codec> Deref for Item<St, Codec>
|
|
||||||
where
|
|
||||||
Codec: Encoder + Decoder,
|
|
||||||
{
|
|
||||||
type Target = <Codec as Decoder>::Item;
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn deref(&self) -> &<Codec as Decoder>::Item {
|
|
||||||
&self.item
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<St, Codec> DerefMut for Item<St, Codec>
|
|
||||||
where
|
|
||||||
Codec: Encoder + Decoder,
|
|
||||||
{
|
|
||||||
#[inline]
|
|
||||||
fn deref_mut(&mut self) -> &mut <Codec as Decoder>::Item {
|
|
||||||
&mut self.item
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<St, Codec> fmt::Debug for Item<St, Codec>
|
|
||||||
where
|
|
||||||
Codec: Encoder + Decoder,
|
|
||||||
<Codec as Decoder>::Item: fmt::Debug,
|
|
||||||
{
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
f.debug_tuple("FramedItem").field(&self.item).finish()
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,16 +1,11 @@
|
|||||||
#![deny(rust_2018_idioms, warnings)]
|
// #![deny(rust_2018_idioms, warnings)]
|
||||||
#![allow(clippy::type_complexity, clippy::too_many_arguments)]
|
#![allow(clippy::type_complexity, clippy::too_many_arguments)]
|
||||||
|
|
||||||
mod cell;
|
|
||||||
mod connect;
|
mod connect;
|
||||||
mod dispatcher;
|
mod dispatcher;
|
||||||
mod error;
|
mod error;
|
||||||
mod item;
|
|
||||||
mod service;
|
mod service;
|
||||||
mod sink;
|
|
||||||
|
|
||||||
pub use self::connect::{Connect, ConnectResult};
|
pub use self::connect::{Connect, ConnectResult};
|
||||||
pub use self::error::ServiceError;
|
pub use self::error::ServiceError;
|
||||||
pub use self::item::Item;
|
pub use self::service::{Builder, FactoryBuilder};
|
||||||
pub use self::service::{Builder, NewServiceBuilder, ServiceBuilder};
|
|
||||||
pub use self::sink::Sink;
|
|
||||||
|
@@ -4,258 +4,265 @@ use std::pin::Pin;
|
|||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder};
|
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
|
||||||
use actix_service::{IntoService, IntoServiceFactory, Service, ServiceFactory};
|
use actix_service::{IntoService, IntoServiceFactory, Service, ServiceFactory};
|
||||||
use either::Either;
|
use either::Either;
|
||||||
use futures::future::{FutureExt, LocalBoxFuture};
|
use futures_core::{ready, stream::Stream};
|
||||||
use pin_project::project;
|
use pin_project::project;
|
||||||
|
|
||||||
use crate::connect::{Connect, ConnectResult};
|
use crate::connect::{Connect, ConnectResult};
|
||||||
use crate::dispatcher::FramedDispatcher;
|
use crate::dispatcher::Dispatcher;
|
||||||
use crate::error::ServiceError;
|
use crate::error::ServiceError;
|
||||||
use crate::item::Item;
|
|
||||||
|
|
||||||
type RequestItem<S, U> = Item<S, U>;
|
type RequestItem<U> = <U as Decoder>::Item;
|
||||||
type ResponseItem<U> = Option<<U as Encoder>::Item>;
|
type ResponseItem<U> = Option<<U as Encoder>::Item>;
|
||||||
|
|
||||||
/// Service builder - structure that follows the builder pattern
|
/// Service builder - structure that follows the builder pattern
|
||||||
/// for building instances for framed services.
|
/// for building instances for framed services.
|
||||||
pub struct Builder<St, Codec>(PhantomData<(St, Codec)>);
|
pub struct Builder<St, C, Io, Codec, Out> {
|
||||||
|
connect: C,
|
||||||
impl<St: Clone, Codec> Default for Builder<St, Codec> {
|
_t: PhantomData<(St, Io, Codec, Out)>,
|
||||||
fn default() -> Builder<St, Codec> {
|
|
||||||
Builder::new()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<St: Clone, Codec> Builder<St, Codec> {
|
impl<St, C, Io, Codec, Out> Builder<St, C, Io, Codec, Out>
|
||||||
pub fn new() -> Builder<St, Codec> {
|
where
|
||||||
Builder(PhantomData)
|
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec, Out>>,
|
||||||
}
|
Io: AsyncRead + AsyncWrite,
|
||||||
|
Codec: Decoder + Encoder,
|
||||||
|
<Codec as Encoder>::Item: 'static,
|
||||||
|
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
|
||||||
|
{
|
||||||
/// Construct framed handler service with specified connect service
|
/// Construct framed handler service with specified connect service
|
||||||
pub fn service<Io, C, F>(self, connect: F) -> ServiceBuilder<St, C, Io, Codec>
|
pub fn new<F>(connect: F) -> Builder<St, C, Io, Codec, Out>
|
||||||
where
|
where
|
||||||
F: IntoService<C>,
|
F: IntoService<C>,
|
||||||
Io: AsyncRead + AsyncWrite,
|
Io: AsyncRead + AsyncWrite,
|
||||||
C: Service<Request = Connect<Io>, Response = ConnectResult<Io, St, Codec>>,
|
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec, Out>>,
|
||||||
Codec: Decoder + Encoder,
|
Codec: Decoder + Encoder,
|
||||||
|
Out: Stream<Item = <Codec as Encoder>::Item>,
|
||||||
{
|
{
|
||||||
ServiceBuilder {
|
Builder {
|
||||||
connect: connect.into_service(),
|
connect: connect.into_service(),
|
||||||
disconnect: None,
|
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Provide stream items handler service and construct service factory.
|
||||||
|
pub fn build<F, T>(self, service: F) -> FramedServiceImpl<St, C, T, Io, Codec, Out>
|
||||||
|
where
|
||||||
|
F: IntoServiceFactory<T>,
|
||||||
|
T: ServiceFactory<
|
||||||
|
Config = St,
|
||||||
|
Request = RequestItem<Codec>,
|
||||||
|
Response = ResponseItem<Codec>,
|
||||||
|
Error = C::Error,
|
||||||
|
InitError = C::Error,
|
||||||
|
>,
|
||||||
|
{
|
||||||
|
FramedServiceImpl {
|
||||||
|
connect: self.connect,
|
||||||
|
handler: Rc::new(service.into_factory()),
|
||||||
|
_t: PhantomData,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Service builder - structure that follows the builder pattern
|
||||||
|
/// for building instances for framed services.
|
||||||
|
pub struct FactoryBuilder<St, C, Io, Codec, Out> {
|
||||||
|
connect: C,
|
||||||
|
_t: PhantomData<(St, Io, Codec, Out)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<St, C, Io, Codec, Out> FactoryBuilder<St, C, Io, Codec, Out>
|
||||||
|
where
|
||||||
|
Io: AsyncRead + AsyncWrite,
|
||||||
|
C: ServiceFactory<
|
||||||
|
Config = (),
|
||||||
|
Request = Connect<Io, Codec>,
|
||||||
|
Response = ConnectResult<Io, St, Codec, Out>,
|
||||||
|
>,
|
||||||
|
Codec: Decoder + Encoder,
|
||||||
|
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
|
||||||
|
{
|
||||||
/// Construct framed handler new service with specified connect service
|
/// Construct framed handler new service with specified connect service
|
||||||
pub fn factory<Io, C, F>(self, connect: F) -> NewServiceBuilder<St, C, Io, Codec>
|
pub fn new<F>(connect: F) -> FactoryBuilder<St, C, Io, Codec, Out>
|
||||||
where
|
where
|
||||||
F: IntoServiceFactory<C>,
|
F: IntoServiceFactory<C>,
|
||||||
Io: AsyncRead + AsyncWrite,
|
Io: AsyncRead + AsyncWrite,
|
||||||
C: ServiceFactory<
|
C: ServiceFactory<
|
||||||
Config = (),
|
Config = (),
|
||||||
Request = Connect<Io>,
|
Request = Connect<Io, Codec>,
|
||||||
Response = ConnectResult<Io, St, Codec>,
|
Response = ConnectResult<Io, St, Codec, Out>,
|
||||||
>,
|
>,
|
||||||
C::Error: 'static,
|
|
||||||
C::Future: 'static,
|
|
||||||
Codec: Decoder + Encoder,
|
Codec: Decoder + Encoder,
|
||||||
|
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
|
||||||
{
|
{
|
||||||
NewServiceBuilder {
|
FactoryBuilder {
|
||||||
connect: connect.into_factory(),
|
connect: connect.into_factory(),
|
||||||
disconnect: None,
|
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
pub struct ServiceBuilder<St, C, Io, Codec> {
|
pub fn build<F, T, Cfg>(self, service: F) -> FramedService<St, C, T, Io, Codec, Out, Cfg>
|
||||||
connect: C,
|
|
||||||
disconnect: Option<Rc<dyn Fn(&mut St, bool)>>,
|
|
||||||
_t: PhantomData<(St, Io, Codec)>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<St, C, Io, Codec> ServiceBuilder<St, C, Io, Codec>
|
|
||||||
where
|
|
||||||
St: Clone,
|
|
||||||
C: Service<Request = Connect<Io>, Response = ConnectResult<Io, St, Codec>>,
|
|
||||||
C::Error: 'static,
|
|
||||||
Io: AsyncRead + AsyncWrite,
|
|
||||||
Codec: Decoder + Encoder,
|
|
||||||
<Codec as Encoder>::Item: 'static,
|
|
||||||
<Codec as Encoder>::Error: std::fmt::Debug,
|
|
||||||
{
|
|
||||||
/// Callback to execute on disconnect
|
|
||||||
///
|
|
||||||
/// Second parameter indicates error occured during disconnect.
|
|
||||||
pub fn disconnect<F, Out>(mut self, disconnect: F) -> Self
|
|
||||||
where
|
|
||||||
F: Fn(&mut St, bool) + 'static,
|
|
||||||
{
|
|
||||||
self.disconnect = Some(Rc::new(disconnect));
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Provide stream items handler service and construct service factory.
|
|
||||||
pub fn finish<F, T>(self, service: F) -> FramedServiceImpl<St, C, T, Io, Codec>
|
|
||||||
where
|
where
|
||||||
F: IntoServiceFactory<T>,
|
F: IntoServiceFactory<T>,
|
||||||
T: ServiceFactory<
|
T: ServiceFactory<
|
||||||
Config = St,
|
Config = St,
|
||||||
Request = RequestItem<St, Codec>,
|
Request = RequestItem<Codec>,
|
||||||
Response = ResponseItem<Codec>,
|
Response = ResponseItem<Codec>,
|
||||||
Error = C::Error,
|
Error = C::Error,
|
||||||
InitError = C::Error,
|
InitError = C::Error,
|
||||||
> + 'static,
|
>,
|
||||||
{
|
|
||||||
FramedServiceImpl {
|
|
||||||
connect: self.connect,
|
|
||||||
handler: Rc::new(service.into_factory()),
|
|
||||||
disconnect: self.disconnect.clone(),
|
|
||||||
_t: PhantomData,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct NewServiceBuilder<St, C, Io, Codec> {
|
|
||||||
connect: C,
|
|
||||||
disconnect: Option<Rc<dyn Fn(&mut St, bool)>>,
|
|
||||||
_t: PhantomData<(St, Io, Codec)>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<St, C, Io, Codec> NewServiceBuilder<St, C, Io, Codec>
|
|
||||||
where
|
|
||||||
St: Clone,
|
|
||||||
Io: AsyncRead + AsyncWrite,
|
|
||||||
C: ServiceFactory<
|
|
||||||
Config = (),
|
|
||||||
Request = Connect<Io>,
|
|
||||||
Response = ConnectResult<Io, St, Codec>,
|
|
||||||
>,
|
|
||||||
C::Error: 'static,
|
|
||||||
C::Future: 'static,
|
|
||||||
Codec: Decoder + Encoder,
|
|
||||||
<Codec as Encoder>::Item: 'static,
|
|
||||||
<Codec as Encoder>::Error: std::fmt::Debug,
|
|
||||||
{
|
|
||||||
/// Callback to execute on disconnect
|
|
||||||
///
|
|
||||||
/// Second parameter indicates error occured during disconnect.
|
|
||||||
pub fn disconnect<F>(mut self, disconnect: F) -> Self
|
|
||||||
where
|
|
||||||
F: Fn(&mut St, bool) + 'static,
|
|
||||||
{
|
|
||||||
self.disconnect = Some(Rc::new(disconnect));
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn finish<F, T, Cfg>(self, service: F) -> FramedService<St, C, T, Io, Codec, Cfg>
|
|
||||||
where
|
|
||||||
F: IntoServiceFactory<T>,
|
|
||||||
T: ServiceFactory<
|
|
||||||
Config = St,
|
|
||||||
Request = RequestItem<St, Codec>,
|
|
||||||
Response = ResponseItem<Codec>,
|
|
||||||
Error = C::Error,
|
|
||||||
InitError = C::Error,
|
|
||||||
> + 'static,
|
|
||||||
{
|
{
|
||||||
FramedService {
|
FramedService {
|
||||||
connect: self.connect,
|
connect: self.connect,
|
||||||
handler: Rc::new(service.into_factory()),
|
handler: Rc::new(service.into_factory()),
|
||||||
disconnect: self.disconnect,
|
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct FramedService<St, C, T, Io, Codec, Cfg> {
|
pub struct FramedService<St, C, T, Io, Codec, Out, Cfg> {
|
||||||
connect: C,
|
connect: C,
|
||||||
handler: Rc<T>,
|
handler: Rc<T>,
|
||||||
disconnect: Option<Rc<dyn Fn(&mut St, bool)>>,
|
_t: PhantomData<(St, Io, Codec, Out, Cfg)>,
|
||||||
_t: PhantomData<(St, Io, Codec, Cfg)>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<St, C, T, Io, Codec, Cfg> ServiceFactory for FramedService<St, C, T, Io, Codec, Cfg>
|
impl<St, C, T, Io, Codec, Out, Cfg> ServiceFactory
|
||||||
|
for FramedService<St, C, T, Io, Codec, Out, Cfg>
|
||||||
where
|
where
|
||||||
St: Clone + 'static,
|
|
||||||
Io: AsyncRead + AsyncWrite,
|
Io: AsyncRead + AsyncWrite,
|
||||||
C: ServiceFactory<
|
C: ServiceFactory<
|
||||||
Config = (),
|
Config = (),
|
||||||
Request = Connect<Io>,
|
Request = Connect<Io, Codec>,
|
||||||
Response = ConnectResult<Io, St, Codec>,
|
Response = ConnectResult<Io, St, Codec, Out>,
|
||||||
>,
|
>,
|
||||||
C::Error: 'static,
|
|
||||||
C::Future: 'static,
|
|
||||||
T: ServiceFactory<
|
T: ServiceFactory<
|
||||||
Config = St,
|
Config = St,
|
||||||
Request = RequestItem<St, Codec>,
|
Request = RequestItem<Codec>,
|
||||||
Response = ResponseItem<Codec>,
|
Response = ResponseItem<Codec>,
|
||||||
Error = C::Error,
|
Error = C::Error,
|
||||||
InitError = C::Error,
|
InitError = C::Error,
|
||||||
> + 'static,
|
>,
|
||||||
|
<T::Service as Service>::Error: 'static,
|
||||||
<T::Service as Service>::Future: 'static,
|
<T::Service as Service>::Future: 'static,
|
||||||
Codec: Decoder + Encoder,
|
Codec: Decoder + Encoder,
|
||||||
<Codec as Encoder>::Item: 'static,
|
<Codec as Encoder>::Item: 'static,
|
||||||
<Codec as Encoder>::Error: std::fmt::Debug,
|
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
|
||||||
{
|
{
|
||||||
type Config = Cfg;
|
type Config = Cfg;
|
||||||
type Request = Io;
|
type Request = Io;
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = ServiceError<C::Error, Codec>;
|
type Error = ServiceError<C::Error, Codec>;
|
||||||
type InitError = C::InitError;
|
type InitError = C::InitError;
|
||||||
type Service = FramedServiceImpl<St, C::Service, T, Io, Codec>;
|
type Service = FramedServiceImpl<St, C::Service, T, Io, Codec, Out>;
|
||||||
type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>;
|
type Future = FramedServiceResponse<St, C, T, Io, Codec, Out>;
|
||||||
|
|
||||||
fn new_service(&self, _: Cfg) -> Self::Future {
|
fn new_service(&self, _: Cfg) -> Self::Future {
|
||||||
let handler = self.handler.clone();
|
|
||||||
let disconnect = self.disconnect.clone();
|
|
||||||
|
|
||||||
// create connect service and then create service impl
|
// create connect service and then create service impl
|
||||||
self.connect
|
FramedServiceResponse {
|
||||||
.new_service(())
|
fut: self.connect.new_service(()),
|
||||||
.map(move |result| {
|
handler: self.handler.clone(),
|
||||||
result.map(move |connect| FramedServiceImpl {
|
}
|
||||||
connect,
|
|
||||||
handler,
|
|
||||||
disconnect,
|
|
||||||
_t: PhantomData,
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.boxed_local()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct FramedServiceImpl<St, C, T, Io, Codec> {
|
#[pin_project::pin_project]
|
||||||
connect: C,
|
pub struct FramedServiceResponse<St, C, T, Io, Codec, Out>
|
||||||
handler: Rc<T>,
|
|
||||||
disconnect: Option<Rc<dyn Fn(&mut St, bool)>>,
|
|
||||||
_t: PhantomData<(St, Io, Codec)>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<St, C, T, Io, Codec> Service for FramedServiceImpl<St, C, T, Io, Codec>
|
|
||||||
where
|
where
|
||||||
St: Clone,
|
|
||||||
Io: AsyncRead + AsyncWrite,
|
Io: AsyncRead + AsyncWrite,
|
||||||
C: Service<Request = Connect<Io>, Response = ConnectResult<Io, St, Codec>>,
|
C: ServiceFactory<
|
||||||
C::Error: 'static,
|
Config = (),
|
||||||
|
Request = Connect<Io, Codec>,
|
||||||
|
Response = ConnectResult<Io, St, Codec, Out>,
|
||||||
|
>,
|
||||||
T: ServiceFactory<
|
T: ServiceFactory<
|
||||||
Config = St,
|
Config = St,
|
||||||
Request = RequestItem<St, Codec>,
|
Request = RequestItem<Codec>,
|
||||||
Response = ResponseItem<Codec>,
|
Response = ResponseItem<Codec>,
|
||||||
Error = C::Error,
|
Error = C::Error,
|
||||||
InitError = C::Error,
|
InitError = C::Error,
|
||||||
>,
|
>,
|
||||||
|
<T::Service as Service>::Error: 'static,
|
||||||
<T::Service as Service>::Future: 'static,
|
<T::Service as Service>::Future: 'static,
|
||||||
Codec: Decoder + Encoder,
|
Codec: Decoder + Encoder,
|
||||||
<Codec as Encoder>::Item: 'static,
|
<Codec as Encoder>::Item: 'static,
|
||||||
<Codec as Encoder>::Error: std::fmt::Debug,
|
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
|
||||||
|
{
|
||||||
|
#[pin]
|
||||||
|
fut: C::Future,
|
||||||
|
handler: Rc<T>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<St, C, T, Io, Codec, Out> Future for FramedServiceResponse<St, C, T, Io, Codec, Out>
|
||||||
|
where
|
||||||
|
Io: AsyncRead + AsyncWrite,
|
||||||
|
C: ServiceFactory<
|
||||||
|
Config = (),
|
||||||
|
Request = Connect<Io, Codec>,
|
||||||
|
Response = ConnectResult<Io, St, Codec, Out>,
|
||||||
|
>,
|
||||||
|
T: ServiceFactory<
|
||||||
|
Config = St,
|
||||||
|
Request = RequestItem<Codec>,
|
||||||
|
Response = ResponseItem<Codec>,
|
||||||
|
Error = C::Error,
|
||||||
|
InitError = C::Error,
|
||||||
|
>,
|
||||||
|
<T::Service as Service>::Error: 'static,
|
||||||
|
<T::Service as Service>::Future: 'static,
|
||||||
|
Codec: Decoder + Encoder,
|
||||||
|
<Codec as Encoder>::Item: 'static,
|
||||||
|
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
|
||||||
|
{
|
||||||
|
type Output = Result<FramedServiceImpl<St, C::Service, T, Io, Codec, Out>, C::InitError>;
|
||||||
|
|
||||||
|
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||||
|
let this = self.project();
|
||||||
|
let connect = ready!(this.fut.poll(cx))?;
|
||||||
|
|
||||||
|
Poll::Ready(Ok(FramedServiceImpl {
|
||||||
|
connect,
|
||||||
|
handler: this.handler.clone(),
|
||||||
|
_t: PhantomData,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct FramedServiceImpl<St, C, T, Io, Codec, Out> {
|
||||||
|
connect: C,
|
||||||
|
handler: Rc<T>,
|
||||||
|
_t: PhantomData<(St, Io, Codec, Out)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<St, C, T, Io, Codec, Out> Service for FramedServiceImpl<St, C, T, Io, Codec, Out>
|
||||||
|
where
|
||||||
|
Io: AsyncRead + AsyncWrite,
|
||||||
|
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec, Out>>,
|
||||||
|
T: ServiceFactory<
|
||||||
|
Config = St,
|
||||||
|
Request = RequestItem<Codec>,
|
||||||
|
Response = ResponseItem<Codec>,
|
||||||
|
Error = C::Error,
|
||||||
|
InitError = C::Error,
|
||||||
|
>,
|
||||||
|
<T::Service as Service>::Error: 'static,
|
||||||
|
<T::Service as Service>::Future: 'static,
|
||||||
|
Codec: Decoder + Encoder,
|
||||||
|
<Codec as Encoder>::Item: 'static,
|
||||||
|
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
|
||||||
{
|
{
|
||||||
type Request = Io;
|
type Request = Io;
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = ServiceError<C::Error, Codec>;
|
type Error = ServiceError<C::Error, Codec>;
|
||||||
type Future = FramedServiceImplResponse<St, Io, Codec, C, T>;
|
type Future = FramedServiceImplResponse<St, Io, Codec, Out, C, T>;
|
||||||
|
|
||||||
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||||
self.connect.poll_ready(cx).map_err(|e| e.into())
|
self.connect.poll_ready(cx).map_err(|e| e.into())
|
||||||
@@ -266,52 +273,51 @@ where
|
|||||||
inner: FramedServiceImplResponseInner::Connect(
|
inner: FramedServiceImplResponseInner::Connect(
|
||||||
self.connect.call(Connect::new(req)),
|
self.connect.call(Connect::new(req)),
|
||||||
self.handler.clone(),
|
self.handler.clone(),
|
||||||
self.disconnect.clone(),
|
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[pin_project::pin_project]
|
#[pin_project::pin_project]
|
||||||
pub struct FramedServiceImplResponse<St, Io, Codec, C, T>
|
pub struct FramedServiceImplResponse<St, Io, Codec, Out, C, T>
|
||||||
where
|
where
|
||||||
St: Clone,
|
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec, Out>>,
|
||||||
C: Service<Request = Connect<Io>, Response = ConnectResult<Io, St, Codec>>,
|
|
||||||
C::Error: 'static,
|
|
||||||
T: ServiceFactory<
|
T: ServiceFactory<
|
||||||
Config = St,
|
Config = St,
|
||||||
Request = RequestItem<St, Codec>,
|
Request = RequestItem<Codec>,
|
||||||
Response = ResponseItem<Codec>,
|
Response = ResponseItem<Codec>,
|
||||||
Error = C::Error,
|
Error = C::Error,
|
||||||
InitError = C::Error,
|
InitError = C::Error,
|
||||||
>,
|
>,
|
||||||
|
<T::Service as Service>::Error: 'static,
|
||||||
<T::Service as Service>::Future: 'static,
|
<T::Service as Service>::Future: 'static,
|
||||||
Io: AsyncRead + AsyncWrite,
|
Io: AsyncRead + AsyncWrite,
|
||||||
Codec: Encoder + Decoder,
|
Codec: Encoder + Decoder,
|
||||||
<Codec as Encoder>::Item: 'static,
|
<Codec as Encoder>::Item: 'static,
|
||||||
<Codec as Encoder>::Error: std::fmt::Debug,
|
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
|
||||||
{
|
{
|
||||||
#[pin]
|
#[pin]
|
||||||
inner: FramedServiceImplResponseInner<St, Io, Codec, C, T>,
|
inner: FramedServiceImplResponseInner<St, Io, Codec, Out, C, T>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<St, Io, Codec, C, T> Future for FramedServiceImplResponse<St, Io, Codec, C, T>
|
impl<St, Io, Codec, Out, C, T> Future for FramedServiceImplResponse<St, Io, Codec, Out, C, T>
|
||||||
where
|
where
|
||||||
St: Clone,
|
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec, Out>>,
|
||||||
C: Service<Request = Connect<Io>, Response = ConnectResult<Io, St, Codec>>,
|
|
||||||
C::Error: 'static,
|
|
||||||
T: ServiceFactory<
|
T: ServiceFactory<
|
||||||
Config = St,
|
Config = St,
|
||||||
Request = RequestItem<St, Codec>,
|
Request = RequestItem<Codec>,
|
||||||
Response = ResponseItem<Codec>,
|
Response = ResponseItem<Codec>,
|
||||||
Error = C::Error,
|
Error = C::Error,
|
||||||
InitError = C::Error,
|
InitError = C::Error,
|
||||||
>,
|
>,
|
||||||
|
<T::Service as Service>::Error: 'static,
|
||||||
<T::Service as Service>::Future: 'static,
|
<T::Service as Service>::Future: 'static,
|
||||||
Io: AsyncRead + AsyncWrite,
|
Io: AsyncRead + AsyncWrite,
|
||||||
Codec: Encoder + Decoder,
|
Codec: Encoder + Decoder,
|
||||||
<Codec as Encoder>::Item: 'static,
|
<Codec as Encoder>::Item: 'static,
|
||||||
<Codec as Encoder>::Error: std::fmt::Debug,
|
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
|
||||||
{
|
{
|
||||||
type Output = Result<(), ServiceError<C::Error, Codec>>;
|
type Output = Result<(), ServiceError<C::Error, Codec>>;
|
||||||
|
|
||||||
@@ -331,93 +337,78 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[pin_project::pin_project]
|
#[pin_project::pin_project]
|
||||||
enum FramedServiceImplResponseInner<St, Io, Codec, C, T>
|
enum FramedServiceImplResponseInner<St, Io, Codec, Out, C, T>
|
||||||
where
|
where
|
||||||
St: Clone,
|
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec, Out>>,
|
||||||
C: Service<Request = Connect<Io>, Response = ConnectResult<Io, St, Codec>>,
|
|
||||||
C::Error: 'static,
|
|
||||||
T: ServiceFactory<
|
T: ServiceFactory<
|
||||||
Config = St,
|
Config = St,
|
||||||
Request = RequestItem<St, Codec>,
|
Request = RequestItem<Codec>,
|
||||||
Response = ResponseItem<Codec>,
|
Response = ResponseItem<Codec>,
|
||||||
Error = C::Error,
|
Error = C::Error,
|
||||||
InitError = C::Error,
|
InitError = C::Error,
|
||||||
>,
|
>,
|
||||||
|
<T::Service as Service>::Error: 'static,
|
||||||
<T::Service as Service>::Future: 'static,
|
<T::Service as Service>::Future: 'static,
|
||||||
Io: AsyncRead + AsyncWrite,
|
Io: AsyncRead + AsyncWrite,
|
||||||
Codec: Encoder + Decoder,
|
Codec: Encoder + Decoder,
|
||||||
<Codec as Encoder>::Item: 'static,
|
<Codec as Encoder>::Item: 'static,
|
||||||
<Codec as Encoder>::Error: std::fmt::Debug,
|
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
|
||||||
{
|
{
|
||||||
Connect(#[pin] C::Future, Rc<T>, Option<Rc<dyn Fn(&mut St, bool)>>),
|
Connect(#[pin] C::Future, Rc<T>),
|
||||||
Handler(
|
Handler(#[pin] T::Future, Option<Framed<Io, Codec>>, Option<Out>),
|
||||||
#[pin] T::Future,
|
Dispatcher(#[pin] Dispatcher<T::Service, Io, Codec, Out>),
|
||||||
Option<ConnectResult<Io, St, Codec>>,
|
|
||||||
Option<Rc<dyn Fn(&mut St, bool)>>,
|
|
||||||
),
|
|
||||||
Dispatcher(#[pin] FramedDispatcher<St, T::Service, Io, Codec>),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<St, Io, Codec, C, T> FramedServiceImplResponseInner<St, Io, Codec, C, T>
|
impl<St, Io, Codec, Out, C, T> FramedServiceImplResponseInner<St, Io, Codec, Out, C, T>
|
||||||
where
|
where
|
||||||
St: Clone,
|
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec, Out>>,
|
||||||
C: Service<Request = Connect<Io>, Response = ConnectResult<Io, St, Codec>>,
|
|
||||||
C::Error: 'static,
|
|
||||||
T: ServiceFactory<
|
T: ServiceFactory<
|
||||||
Config = St,
|
Config = St,
|
||||||
Request = RequestItem<St, Codec>,
|
Request = RequestItem<Codec>,
|
||||||
Response = ResponseItem<Codec>,
|
Response = ResponseItem<Codec>,
|
||||||
Error = C::Error,
|
Error = C::Error,
|
||||||
InitError = C::Error,
|
InitError = C::Error,
|
||||||
>,
|
>,
|
||||||
|
<T::Service as Service>::Error: 'static,
|
||||||
<T::Service as Service>::Future: 'static,
|
<T::Service as Service>::Future: 'static,
|
||||||
Io: AsyncRead + AsyncWrite,
|
Io: AsyncRead + AsyncWrite,
|
||||||
Codec: Encoder + Decoder,
|
Codec: Encoder + Decoder,
|
||||||
<Codec as Encoder>::Item: 'static,
|
<Codec as Encoder>::Item: 'static,
|
||||||
<Codec as Encoder>::Error: std::fmt::Debug,
|
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
|
||||||
{
|
{
|
||||||
#[project]
|
#[project]
|
||||||
fn poll(
|
fn poll(
|
||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Either<
|
) -> Either<
|
||||||
FramedServiceImplResponseInner<St, Io, Codec, C, T>,
|
FramedServiceImplResponseInner<St, Io, Codec, Out, C, T>,
|
||||||
Poll<Result<(), ServiceError<C::Error, Codec>>>,
|
Poll<Result<(), ServiceError<C::Error, Codec>>>,
|
||||||
> {
|
> {
|
||||||
#[project]
|
#[project]
|
||||||
match self.project() {
|
match self.project() {
|
||||||
FramedServiceImplResponseInner::Connect(fut, handler, disconnect) => {
|
FramedServiceImplResponseInner::Connect(fut, handler) => match fut.poll(cx) {
|
||||||
|
Poll::Ready(Ok(res)) => Either::Left(FramedServiceImplResponseInner::Handler(
|
||||||
|
handler.new_service(res.state),
|
||||||
|
Some(res.framed),
|
||||||
|
res.out,
|
||||||
|
)),
|
||||||
|
Poll::Pending => Either::Right(Poll::Pending),
|
||||||
|
Poll::Ready(Err(e)) => Either::Right(Poll::Ready(Err(e.into()))),
|
||||||
|
},
|
||||||
|
FramedServiceImplResponseInner::Handler(fut, framed, out) => {
|
||||||
match fut.poll(cx) {
|
match fut.poll(cx) {
|
||||||
Poll::Ready(Ok(res)) => {
|
Poll::Ready(Ok(handler)) => {
|
||||||
Either::Left(FramedServiceImplResponseInner::Handler(
|
Either::Left(FramedServiceImplResponseInner::Dispatcher(
|
||||||
handler.new_service(res.state.clone()),
|
Dispatcher::new(framed.take().unwrap(), handler, out.take()),
|
||||||
Some(res),
|
|
||||||
disconnect.take(),
|
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
Poll::Pending => Either::Right(Poll::Pending),
|
Poll::Pending => Either::Right(Poll::Pending),
|
||||||
Poll::Ready(Err(e)) => Either::Right(Poll::Ready(Err(e.into()))),
|
Poll::Ready(Err(e)) => Either::Right(Poll::Ready(Err(e.into()))),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
FramedServiceImplResponseInner::Handler(fut, res, disconnect) => match fut.poll(cx)
|
FramedServiceImplResponseInner::Dispatcher(fut) => {
|
||||||
{
|
|
||||||
Poll::Ready(Ok(handler)) => {
|
|
||||||
let res = res.take().unwrap();
|
|
||||||
Either::Left(FramedServiceImplResponseInner::Dispatcher(
|
|
||||||
FramedDispatcher::new(
|
|
||||||
res.framed,
|
|
||||||
res.state,
|
|
||||||
handler,
|
|
||||||
res.rx,
|
|
||||||
res.sink,
|
|
||||||
disconnect.take(),
|
|
||||||
),
|
|
||||||
))
|
|
||||||
}
|
|
||||||
Poll::Pending => Either::Right(Poll::Pending),
|
|
||||||
Poll::Ready(Err(e)) => Either::Right(Poll::Ready(Err(e.into()))),
|
|
||||||
},
|
|
||||||
FramedServiceImplResponseInner::Dispatcher(ref mut fut) => {
|
|
||||||
Either::Right(fut.poll(cx))
|
Either::Right(fut.poll(cx))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,44 +0,0 @@
|
|||||||
use std::fmt;
|
|
||||||
|
|
||||||
use actix_utils::{mpsc, oneshot};
|
|
||||||
use futures::future::{Future, FutureExt};
|
|
||||||
|
|
||||||
use crate::dispatcher::FramedMessage;
|
|
||||||
|
|
||||||
pub struct Sink<T>(mpsc::Sender<FramedMessage<T>>);
|
|
||||||
|
|
||||||
impl<T> Clone for Sink<T> {
|
|
||||||
fn clone(&self) -> Self {
|
|
||||||
Sink(self.0.clone())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> Sink<T> {
|
|
||||||
pub(crate) fn new(tx: mpsc::Sender<FramedMessage<T>>) -> Self {
|
|
||||||
Sink(tx)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Close connection
|
|
||||||
pub fn close(&self) {
|
|
||||||
let _ = self.0.send(FramedMessage::Close);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Close connection
|
|
||||||
pub fn wait_close(&self) -> impl Future<Output = ()> {
|
|
||||||
let (tx, rx) = oneshot::channel();
|
|
||||||
let _ = self.0.send(FramedMessage::WaitClose(tx));
|
|
||||||
|
|
||||||
rx.map(|_| ())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Send item
|
|
||||||
pub fn send(&self, item: T) {
|
|
||||||
let _ = self.0.send(FramedMessage::Message(item));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> fmt::Debug for Sink<T> {
|
|
||||||
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
fmt.debug_struct("Sink").finish()
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,43 +1,49 @@
|
|||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::cell::Cell;
|
||||||
use std::sync::Arc;
|
use std::rc::Rc;
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
use actix_codec::BytesCodec;
|
use actix_codec::BytesCodec;
|
||||||
use actix_rt::time::delay_for;
|
use actix_service::{fn_factory_with_config, fn_service, IntoService, Service};
|
||||||
use actix_service::{service_fn, Service};
|
|
||||||
use actix_testing::TestServer;
|
use actix_testing::TestServer;
|
||||||
use futures::future::ok;
|
use actix_utils::mpsc;
|
||||||
|
use bytes::{Bytes, BytesMut};
|
||||||
|
use futures_util::future::ok;
|
||||||
|
|
||||||
use actix_ioframe::{Builder, Connect};
|
use actix_ioframe::{Builder, Connect, FactoryBuilder};
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
struct State;
|
struct State(Option<mpsc::Sender<Bytes>>);
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_disconnect() -> std::io::Result<()> {
|
async fn test_basic() {
|
||||||
let disconnect = Arc::new(AtomicBool::new(false));
|
let client_item = Rc::new(Cell::new(false));
|
||||||
let disconnect1 = disconnect.clone();
|
|
||||||
|
|
||||||
let srv = TestServer::with(move || {
|
let srv = TestServer::with(move || {
|
||||||
let disconnect1 = disconnect1.clone();
|
FactoryBuilder::new(fn_service(|conn: Connect<_, _>| {
|
||||||
|
ok(conn.codec(BytesCodec).state(State(None)))
|
||||||
Builder::new()
|
}))
|
||||||
.factory(service_fn(|conn: Connect<_>| {
|
// echo
|
||||||
ok(conn.codec(BytesCodec).state(State))
|
.build(fn_service(|t: BytesMut| ok(Some(t.freeze()))))
|
||||||
}))
|
|
||||||
.disconnect(move |_, _| {
|
|
||||||
disconnect1.store(true, Ordering::Relaxed);
|
|
||||||
})
|
|
||||||
.finish(service_fn(|_t| ok(None)))
|
|
||||||
});
|
});
|
||||||
|
|
||||||
let mut client = Builder::new()
|
let item = client_item.clone();
|
||||||
.service(|conn: Connect<_>| {
|
let mut client = Builder::new(fn_service(move |conn: Connect<_, _>| {
|
||||||
let conn = conn.codec(BytesCodec).state(State);
|
async move {
|
||||||
conn.sink().close();
|
let (tx, rx) = mpsc::channel();
|
||||||
ok(conn)
|
let _ = tx.send(Bytes::from_static(b"Hello"));
|
||||||
|
Ok(conn.codec(BytesCodec).out(rx).state(State(Some(tx))))
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
.build(fn_factory_with_config(move |mut cfg: State| {
|
||||||
|
let item = item.clone();
|
||||||
|
ok((move |t: BytesMut| {
|
||||||
|
assert_eq!(t.freeze(), Bytes::from_static(b"Hello"));
|
||||||
|
item.set(true);
|
||||||
|
// drop Sender, which will close connection
|
||||||
|
cfg.0.take();
|
||||||
|
ok::<_, ()>(None)
|
||||||
})
|
})
|
||||||
.finish(service_fn(|_t| ok(None)));
|
.into_service())
|
||||||
|
}));
|
||||||
|
|
||||||
let conn = actix_connect::default_connector()
|
let conn = actix_connect::default_connector()
|
||||||
.call(actix_connect::Connect::with(String::new(), srv.addr()))
|
.call(actix_connect::Connect::with(String::new(), srv.addr()))
|
||||||
@@ -45,8 +51,5 @@ async fn test_disconnect() -> std::io::Result<()> {
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
client.call(conn.into_parts().0).await.unwrap();
|
client.call(conn.into_parts().0).await.unwrap();
|
||||||
let _ = delay_for(Duration::from_millis(100)).await;
|
assert!(client_item.get());
|
||||||
assert!(disconnect.load(Ordering::Relaxed));
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
1
actix-macros/.gitignore
vendored
Normal file
1
actix-macros/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
|||||||
|
/wip
|
9
actix-macros/CHANGES.md
Normal file
9
actix-macros/CHANGES.md
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
# CHANGES
|
||||||
|
|
||||||
|
## 0.1.2 - 2020-05-18
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Forward actix_rt::test arguments to test function [#127]
|
||||||
|
|
||||||
|
[#127]: https://github.com/actix/actix-net/pull/127
|
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-macros"
|
name = "actix-macros"
|
||||||
version = "0.1.0-alpha.1"
|
version = "0.1.2"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix runtime macros"
|
description = "Actix runtime macros"
|
||||||
repository = "https://github.com/actix/actix-net"
|
repository = "https://github.com/actix/actix-net"
|
||||||
@@ -8,14 +8,16 @@ documentation = "https://docs.rs/actix-macros/"
|
|||||||
categories = ["network-programming", "asynchronous"]
|
categories = ["network-programming", "asynchronous"]
|
||||||
license = "MIT/Apache-2.0"
|
license = "MIT/Apache-2.0"
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
workspace = ".."
|
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
proc-macro = true
|
proc-macro = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
quote = "^1"
|
quote = "1.0.3"
|
||||||
syn = { version = "^1", features = ["full"] }
|
syn = { version = "^1", features = ["full"] }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-rt = { version = "1.0.0-alpha.1" }
|
actix-rt = "1.0"
|
||||||
|
|
||||||
|
futures-util = { version = "0.3", default-features = false }
|
||||||
|
trybuild = "1"
|
||||||
|
1
actix-macros/LICENSE-APACHE
Symbolic link
1
actix-macros/LICENSE-APACHE
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../LICENSE-APACHE
|
1
actix-macros/LICENSE-MIT
Symbolic link
1
actix-macros/LICENSE-MIT
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../LICENSE-MIT
|
@@ -14,28 +14,30 @@ use quote::quote;
|
|||||||
/// println!("Hello world");
|
/// println!("Hello world");
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
|
#[allow(clippy::needless_doctest_main)]
|
||||||
#[proc_macro_attribute]
|
#[proc_macro_attribute]
|
||||||
#[cfg(not(test))] // Work around for rust-lang/rust#62127
|
#[cfg(not(test))] // Work around for rust-lang/rust#62127
|
||||||
pub fn main(_: TokenStream, item: TokenStream) -> TokenStream {
|
pub fn main(_: TokenStream, item: TokenStream) -> TokenStream {
|
||||||
let input = syn::parse_macro_input!(item as syn::ItemFn);
|
let mut input = syn::parse_macro_input!(item as syn::ItemFn);
|
||||||
|
|
||||||
let ret = &input.sig.output;
|
|
||||||
let name = &input.sig.ident;
|
|
||||||
let inputs = &input.sig.inputs;
|
|
||||||
let body = &input.block;
|
|
||||||
let attrs = &input.attrs;
|
let attrs = &input.attrs;
|
||||||
|
let vis = &input.vis;
|
||||||
|
let sig = &mut input.sig;
|
||||||
|
let body = &input.block;
|
||||||
|
let name = &sig.ident;
|
||||||
|
|
||||||
if input.sig.asyncness.is_none() {
|
if sig.asyncness.is_none() {
|
||||||
return syn::Error::new_spanned(input.sig.fn_token, "only async fn is supported")
|
return syn::Error::new_spanned(sig.fn_token, "only async fn is supported")
|
||||||
.to_compile_error()
|
.to_compile_error()
|
||||||
.into();
|
.into();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
sig.asyncness = None;
|
||||||
|
|
||||||
(quote! {
|
(quote! {
|
||||||
#(#attrs)*
|
#(#attrs)*
|
||||||
fn #name(#inputs) #ret {
|
#vis #sig {
|
||||||
actix_rt::System::new("main")
|
actix_rt::System::new(stringify!(#name))
|
||||||
.block_on(async { #body })
|
.block_on(async move { #body })
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.into()
|
.into()
|
||||||
@@ -53,12 +55,11 @@ pub fn main(_: TokenStream, item: TokenStream) -> TokenStream {
|
|||||||
/// ```
|
/// ```
|
||||||
#[proc_macro_attribute]
|
#[proc_macro_attribute]
|
||||||
pub fn test(_: TokenStream, item: TokenStream) -> TokenStream {
|
pub fn test(_: TokenStream, item: TokenStream) -> TokenStream {
|
||||||
let input = syn::parse_macro_input!(item as syn::ItemFn);
|
let mut input = syn::parse_macro_input!(item as syn::ItemFn);
|
||||||
|
|
||||||
let ret = &input.sig.output;
|
|
||||||
let name = &input.sig.ident;
|
|
||||||
let body = &input.block;
|
|
||||||
let attrs = &input.attrs;
|
let attrs = &input.attrs;
|
||||||
|
let vis = &input.vis;
|
||||||
|
let sig = &mut input.sig;
|
||||||
|
let body = &input.block;
|
||||||
let mut has_test_attr = false;
|
let mut has_test_attr = false;
|
||||||
|
|
||||||
for attr in attrs {
|
for attr in attrs {
|
||||||
@@ -67,19 +68,21 @@ pub fn test(_: TokenStream, item: TokenStream) -> TokenStream {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if input.sig.asyncness.is_none() {
|
if sig.asyncness.is_none() {
|
||||||
return syn::Error::new_spanned(
|
return syn::Error::new_spanned(
|
||||||
input.sig.fn_token,
|
input.sig.fn_token,
|
||||||
format!("only async fn is supported, {:?}", input.sig.ident),
|
format!("only async fn is supported, {}", input.sig.ident),
|
||||||
)
|
)
|
||||||
.to_compile_error()
|
.to_compile_error()
|
||||||
.into();
|
.into();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
sig.asyncness = None;
|
||||||
|
|
||||||
let result = if has_test_attr {
|
let result = if has_test_attr {
|
||||||
quote! {
|
quote! {
|
||||||
#(#attrs)*
|
#(#attrs)*
|
||||||
fn #name() #ret {
|
#vis #sig {
|
||||||
actix_rt::System::new("test")
|
actix_rt::System::new("test")
|
||||||
.block_on(async { #body })
|
.block_on(async { #body })
|
||||||
}
|
}
|
||||||
@@ -88,7 +91,7 @@ pub fn test(_: TokenStream, item: TokenStream) -> TokenStream {
|
|||||||
quote! {
|
quote! {
|
||||||
#[test]
|
#[test]
|
||||||
#(#attrs)*
|
#(#attrs)*
|
||||||
fn #name() #ret {
|
#vis #sig {
|
||||||
actix_rt::System::new("test")
|
actix_rt::System::new("test")
|
||||||
.block_on(async { #body })
|
.block_on(async { #body })
|
||||||
}
|
}
|
||||||
|
9
actix-macros/tests/trybuild.rs
Normal file
9
actix-macros/tests/trybuild.rs
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
#[test]
|
||||||
|
fn compile_macros() {
|
||||||
|
let t = trybuild::TestCases::new();
|
||||||
|
t.pass("tests/trybuild/main-01-basic.rs");
|
||||||
|
t.compile_fail("tests/trybuild/main-02-only-async.rs");
|
||||||
|
|
||||||
|
t.pass("tests/trybuild/test-01-basic.rs");
|
||||||
|
t.pass("tests/trybuild/test-02-keep-attrs.rs");
|
||||||
|
}
|
4
actix-macros/tests/trybuild/main-01-basic.rs
Normal file
4
actix-macros/tests/trybuild/main-01-basic.rs
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
#[actix_rt::main]
|
||||||
|
async fn main() {
|
||||||
|
println!("Hello world");
|
||||||
|
}
|
4
actix-macros/tests/trybuild/main-02-only-async.rs
Normal file
4
actix-macros/tests/trybuild/main-02-only-async.rs
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
#[actix_rt::main]
|
||||||
|
fn main() {
|
||||||
|
futures_util::future::ready(()).await
|
||||||
|
}
|
14
actix-macros/tests/trybuild/main-02-only-async.stderr
Normal file
14
actix-macros/tests/trybuild/main-02-only-async.stderr
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
error: only async fn is supported
|
||||||
|
--> $DIR/main-02-only-async.rs:2:1
|
||||||
|
|
|
||||||
|
2 | fn main() {
|
||||||
|
| ^^
|
||||||
|
|
||||||
|
error[E0601]: `main` function not found in crate `$CRATE`
|
||||||
|
--> $DIR/main-02-only-async.rs:1:1
|
||||||
|
|
|
||||||
|
1 | / #[actix_rt::main]
|
||||||
|
2 | | fn main() {
|
||||||
|
3 | | futures_util::future::ready(()).await
|
||||||
|
4 | | }
|
||||||
|
| |_^ consider adding a `main` function to `$DIR/tests/trybuild/main-02-only-async.rs`
|
6
actix-macros/tests/trybuild/test-01-basic.rs
Normal file
6
actix-macros/tests/trybuild/test-01-basic.rs
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
#[actix_rt::test]
|
||||||
|
async fn my_test() {
|
||||||
|
assert!(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {}
|
7
actix-macros/tests/trybuild/test-02-keep-attrs.rs
Normal file
7
actix-macros/tests/trybuild/test-02-keep-attrs.rs
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
#[actix_rt::test]
|
||||||
|
#[should_panic]
|
||||||
|
async fn my_test() {
|
||||||
|
todo!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {}
|
@@ -1,5 +1,32 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [1.1.1] - 2020-04-30
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
* Fix memory leak due to [#94] (see [#129] for more detail)
|
||||||
|
|
||||||
|
[#129]: https://github.com/actix/actix-net/issues/129
|
||||||
|
|
||||||
|
## [1.1.0] - 2020-04-08
|
||||||
|
|
||||||
|
**This version has been yanked.**
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
* 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::local_join` associated function
|
||||||
|
to get be able to `await` for spawned futures [#94]
|
||||||
|
|
||||||
|
[#94]: https://github.com/actix/actix-net/pull/94
|
||||||
|
[#99]: https://github.com/actix/actix-net/pull/99
|
||||||
|
[#124]: https://github.com/actix/actix-net/pull/124
|
||||||
|
|
||||||
|
## [1.0.0] - 2019-12-11
|
||||||
|
|
||||||
|
* Update dependencies
|
||||||
|
|
||||||
## [1.0.0-alpha.3] - 2019-12-07
|
## [1.0.0-alpha.3] - 2019-12-07
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-rt"
|
name = "actix-rt"
|
||||||
version = "1.0.0-alpha.3"
|
version = "1.1.1"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix runtime"
|
description = "Actix runtime"
|
||||||
keywords = ["network", "framework", "async", "futures"]
|
keywords = ["network", "framework", "async", "futures"]
|
||||||
@@ -9,17 +9,17 @@ repository = "https://github.com/actix/actix-net.git"
|
|||||||
documentation = "https://docs.rs/actix-rt/"
|
documentation = "https://docs.rs/actix-rt/"
|
||||||
categories = ["network-programming", "asynchronous"]
|
categories = ["network-programming", "asynchronous"]
|
||||||
license = "MIT/Apache-2.0"
|
license = "MIT/Apache-2.0"
|
||||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
workspace = ".."
|
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
name = "actix_rt"
|
name = "actix_rt"
|
||||||
path = "src/lib.rs"
|
path = "src/lib.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-macros = "0.1.0-alpha.1"
|
actix-macros = "0.1.0"
|
||||||
actix-threadpool = "0.3"
|
actix-threadpool = "0.3"
|
||||||
futures = "0.3.1"
|
futures-channel = { version = "0.3.4", default-features = false }
|
||||||
|
futures-util = { version = "0.3.4", default-features = false, features = ["alloc"] }
|
||||||
copyless = "0.1.4"
|
copyless = "0.1.4"
|
||||||
tokio = { version = "0.2.4", default-features=false, features = ["rt-core", "rt-util", "io-driver", "tcp", "uds", "udp", "time", "signal", "stream"] }
|
smallvec = "1"
|
||||||
|
tokio = { version = "0.2.6", default-features = false, features = ["rt-core", "rt-util", "io-driver", "tcp", "uds", "udp", "time", "signal", "stream"] }
|
||||||
|
@@ -6,19 +6,26 @@ use std::sync::atomic::{AtomicUsize, Ordering};
|
|||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
use std::{fmt, thread};
|
use std::{fmt, thread};
|
||||||
|
|
||||||
use futures::channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender};
|
use futures_channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender};
|
||||||
use futures::channel::oneshot::{channel, Canceled, Sender};
|
use futures_channel::oneshot::{channel, Canceled, Sender};
|
||||||
use futures::{future, Future, FutureExt, Stream};
|
use futures_util::{
|
||||||
|
future::{self, Future, FutureExt},
|
||||||
|
stream::Stream,
|
||||||
|
};
|
||||||
|
|
||||||
use crate::runtime::Runtime;
|
use crate::runtime::Runtime;
|
||||||
use crate::system::System;
|
use crate::system::System;
|
||||||
|
|
||||||
use copyless::BoxHelper;
|
use copyless::BoxHelper;
|
||||||
|
|
||||||
|
use smallvec::SmallVec;
|
||||||
|
pub use tokio::task::JoinHandle;
|
||||||
|
|
||||||
thread_local!(
|
thread_local!(
|
||||||
static ADDR: RefCell<Option<Arbiter>> = RefCell::new(None);
|
static ADDR: RefCell<Option<Arbiter>> = RefCell::new(None);
|
||||||
static RUNNING: Cell<bool> = Cell::new(false);
|
static RUNNING: Cell<bool> = Cell::new(false);
|
||||||
static Q: RefCell<Vec<Pin<Box<dyn Future<Output = ()>>>>> = RefCell::new(Vec::new());
|
static Q: RefCell<Vec<Pin<Box<dyn Future<Output = ()>>>>> = RefCell::new(Vec::new());
|
||||||
|
static PENDING: RefCell<SmallVec<[JoinHandle<()>; 8]>> = RefCell::new(SmallVec::new());
|
||||||
static STORAGE: RefCell<HashMap<TypeId, Box<dyn Any>>> = RefCell::new(HashMap::new());
|
static STORAGE: RefCell<HashMap<TypeId, Box<dyn Any>>> = RefCell::new(HashMap::new());
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -42,8 +49,8 @@ impl fmt::Debug for ArbiterCommand {
|
|||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
/// Arbiters provide an asynchronous execution environment for actors, functions
|
/// Arbiters provide an asynchronous execution environment for actors, functions
|
||||||
/// and futures. When an Arbiter is created, they spawn a new OS thread, and
|
/// and futures. When an Arbiter is created, it spawns a new OS thread, and
|
||||||
/// host an event loop. Some Arbiter functions execute on the current thread.
|
/// hosts an event loop. Some Arbiter functions execute on the current thread.
|
||||||
pub struct Arbiter {
|
pub struct Arbiter {
|
||||||
sender: UnboundedSender<ArbiterCommand>,
|
sender: UnboundedSender<ArbiterCommand>,
|
||||||
thread_handle: Option<thread::JoinHandle<()>>,
|
thread_handle: Option<thread::JoinHandle<()>>,
|
||||||
@@ -83,6 +90,11 @@ impl Arbiter {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Check if current arbiter is running.
|
||||||
|
pub fn is_running() -> bool {
|
||||||
|
RUNNING.with(|cell| cell.get())
|
||||||
|
}
|
||||||
|
|
||||||
/// Stop arbiter from continuing it's event loop.
|
/// Stop arbiter from continuing it's event loop.
|
||||||
pub fn stop(&self) {
|
pub fn stop(&self) {
|
||||||
let _ = self.sender.unbounded_send(ArbiterCommand::Stop);
|
let _ = self.sender.unbounded_send(ArbiterCommand::Stop);
|
||||||
@@ -170,13 +182,20 @@ impl Arbiter {
|
|||||||
RUNNING.with(move |cell| {
|
RUNNING.with(move |cell| {
|
||||||
if cell.get() {
|
if cell.get() {
|
||||||
// Spawn the future on running executor
|
// Spawn the future on running executor
|
||||||
tokio::task::spawn_local(future);
|
let len = PENDING.with(move |cell| {
|
||||||
|
let mut p = cell.borrow_mut();
|
||||||
|
p.push(tokio::task::spawn_local(future));
|
||||||
|
p.len()
|
||||||
|
});
|
||||||
|
if len > 7 {
|
||||||
|
// Before reaching the inline size
|
||||||
|
tokio::task::spawn_local(CleanupPending);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
// Box the future and push it to the queue, this results in double boxing
|
// Box the future and push it to the queue, this results in double boxing
|
||||||
// because the executor boxes the future again, but works for now
|
// because the executor boxes the future again, but works for now
|
||||||
Q.with(move |cell| {
|
Q.with(move |cell| {
|
||||||
cell.borrow_mut()
|
cell.borrow_mut().push(Pin::from(Box::alloc().init(future)))
|
||||||
.push(unsafe { Pin::new_unchecked(Box::alloc().init(future)) })
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -294,6 +313,39 @@ impl Arbiter {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns a future that will be completed once all currently spawned futures
|
||||||
|
/// have completed.
|
||||||
|
pub fn local_join() -> impl Future<Output = ()> {
|
||||||
|
PENDING.with(move |cell| {
|
||||||
|
let current = cell.replace(SmallVec::new());
|
||||||
|
future::join_all(current).map(|_| ())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Future used for cleaning-up already finished `JoinHandle`s
|
||||||
|
/// from the `PENDING` list so the vector doesn't grow indefinitely
|
||||||
|
struct CleanupPending;
|
||||||
|
|
||||||
|
impl Future for CleanupPending {
|
||||||
|
type Output = ();
|
||||||
|
|
||||||
|
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||||
|
PENDING.with(move |cell| {
|
||||||
|
let mut pending = cell.borrow_mut();
|
||||||
|
let mut i = 0;
|
||||||
|
while i != pending.len() {
|
||||||
|
if let Poll::Ready(_) = Pin::new(&mut pending[i]).poll(cx) {
|
||||||
|
pending.remove(i);
|
||||||
|
} else {
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Poll::Ready(())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct ArbiterController {
|
struct ArbiterController {
|
||||||
@@ -329,7 +381,15 @@ impl Future for ArbiterController {
|
|||||||
return Poll::Ready(());
|
return Poll::Ready(());
|
||||||
}
|
}
|
||||||
ArbiterCommand::Execute(fut) => {
|
ArbiterCommand::Execute(fut) => {
|
||||||
tokio::task::spawn_local(fut);
|
let len = PENDING.with(move |cell| {
|
||||||
|
let mut p = cell.borrow_mut();
|
||||||
|
p.push(tokio::task::spawn_local(fut));
|
||||||
|
p.len()
|
||||||
|
});
|
||||||
|
if len > 7 {
|
||||||
|
// Before reaching the inline size
|
||||||
|
tokio::task::spawn_local(CleanupPending);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
ArbiterCommand::ExecuteFn(f) => {
|
ArbiterCommand::ExecuteFn(f) => {
|
||||||
f.call_box();
|
f.call_box();
|
||||||
|
@@ -1,9 +1,9 @@
|
|||||||
use std::borrow::Cow;
|
use std::borrow::Cow;
|
||||||
use std::io;
|
use std::io;
|
||||||
|
|
||||||
use futures::channel::mpsc::unbounded;
|
use futures_channel::mpsc::unbounded;
|
||||||
use futures::channel::oneshot::{channel, Receiver};
|
use futures_channel::oneshot::{channel, Receiver};
|
||||||
use futures::future::{lazy, Future, FutureExt};
|
use futures_util::future::{lazy, Future, FutureExt};
|
||||||
use tokio::task::LocalSet;
|
use tokio::task::LocalSet;
|
||||||
|
|
||||||
use crate::arbiter::{Arbiter, SystemArbiter};
|
use crate::arbiter::{Arbiter, SystemArbiter};
|
||||||
|
@@ -25,7 +25,7 @@ pub use actix_threadpool as blocking;
|
|||||||
/// This function panics if actix system is not running.
|
/// This function panics if actix system is not running.
|
||||||
pub fn spawn<F>(f: F)
|
pub fn spawn<F>(f: F)
|
||||||
where
|
where
|
||||||
F: futures::Future<Output = ()> + 'static,
|
F: futures_util::future::Future<Output = ()> + 'static,
|
||||||
{
|
{
|
||||||
if !System::is_set() {
|
if !System::is_set() {
|
||||||
panic!("System is not running");
|
panic!("System is not running");
|
||||||
|
@@ -86,7 +86,6 @@ impl Runtime {
|
|||||||
where
|
where
|
||||||
F: Future + 'static,
|
F: Future + 'static,
|
||||||
{
|
{
|
||||||
let res = self.local.block_on(&mut self.rt, f);
|
self.local.block_on(&mut self.rt, f)
|
||||||
res
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -3,7 +3,7 @@ use std::future::Future;
|
|||||||
use std::io;
|
use std::io;
|
||||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
|
|
||||||
use futures::channel::mpsc::UnboundedSender;
|
use futures_channel::mpsc::UnboundedSender;
|
||||||
use tokio::task::LocalSet;
|
use tokio::task::LocalSet;
|
||||||
|
|
||||||
use crate::arbiter::{Arbiter, SystemCommand};
|
use crate::arbiter::{Arbiter, SystemCommand};
|
||||||
@@ -79,8 +79,8 @@ impl System {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set current running system.
|
/// Check if current system is set, i.e., as already been started.
|
||||||
pub(crate) fn is_set() -> bool {
|
pub fn is_set() -> bool {
|
||||||
CURRENT.with(|cell| cell.borrow().is_some())
|
CURRENT.with(|cell| cell.borrow().is_some())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
114
actix-rt/tests/integration_tests.rs
Normal file
114
actix-rt/tests/integration_tests.rs
Normal file
@@ -0,0 +1,114 @@
|
|||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn start_and_stop() {
|
||||||
|
actix_rt::System::new("start_and_stop").block_on(async move {
|
||||||
|
assert!(
|
||||||
|
actix_rt::Arbiter::is_running(),
|
||||||
|
"System doesn't seem to have started"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
assert!(
|
||||||
|
!actix_rt::Arbiter::is_running(),
|
||||||
|
"System doesn't seem to have stopped"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn await_for_timer() {
|
||||||
|
let time = Duration::from_secs(2);
|
||||||
|
let instant = Instant::now();
|
||||||
|
actix_rt::System::new("test_wait_timer").block_on(async move {
|
||||||
|
tokio::time::delay_for(time).await;
|
||||||
|
});
|
||||||
|
assert!(
|
||||||
|
instant.elapsed() >= time,
|
||||||
|
"Block on should poll awaited future to completion"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn join_another_arbiter() {
|
||||||
|
let time = Duration::from_secs(2);
|
||||||
|
let instant = Instant::now();
|
||||||
|
actix_rt::System::new("test_join_another_arbiter").block_on(async move {
|
||||||
|
let mut arbiter = actix_rt::Arbiter::new();
|
||||||
|
arbiter.send(Box::pin(async move {
|
||||||
|
tokio::time::delay_for(time).await;
|
||||||
|
actix_rt::Arbiter::current().stop();
|
||||||
|
}));
|
||||||
|
arbiter.join().unwrap();
|
||||||
|
});
|
||||||
|
assert!(
|
||||||
|
instant.elapsed() >= time,
|
||||||
|
"Join on another arbiter should complete only when it calls stop"
|
||||||
|
);
|
||||||
|
|
||||||
|
let instant = Instant::now();
|
||||||
|
actix_rt::System::new("test_join_another_arbiter").block_on(async move {
|
||||||
|
let mut arbiter = actix_rt::Arbiter::new();
|
||||||
|
arbiter.exec_fn(move || {
|
||||||
|
actix_rt::spawn(async move {
|
||||||
|
tokio::time::delay_for(time).await;
|
||||||
|
actix_rt::Arbiter::current().stop();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
arbiter.join().unwrap();
|
||||||
|
});
|
||||||
|
assert!(
|
||||||
|
instant.elapsed() >= time,
|
||||||
|
"Join on a arbiter that has used actix_rt::spawn should wait for said future"
|
||||||
|
);
|
||||||
|
|
||||||
|
let instant = Instant::now();
|
||||||
|
actix_rt::System::new("test_join_another_arbiter").block_on(async move {
|
||||||
|
let mut arbiter = actix_rt::Arbiter::new();
|
||||||
|
arbiter.send(Box::pin(async move {
|
||||||
|
tokio::time::delay_for(time).await;
|
||||||
|
actix_rt::Arbiter::current().stop();
|
||||||
|
}));
|
||||||
|
arbiter.stop();
|
||||||
|
arbiter.join().unwrap();
|
||||||
|
});
|
||||||
|
assert!(
|
||||||
|
instant.elapsed() < time,
|
||||||
|
"Premature stop of arbiter should conclude regardless of it's current state"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn join_current_arbiter() {
|
||||||
|
let time = Duration::from_secs(2);
|
||||||
|
|
||||||
|
let instant = Instant::now();
|
||||||
|
actix_rt::System::new("test_join_current_arbiter").block_on(async move {
|
||||||
|
actix_rt::spawn(async move {
|
||||||
|
tokio::time::delay_for(time).await;
|
||||||
|
actix_rt::Arbiter::current().stop();
|
||||||
|
});
|
||||||
|
actix_rt::Arbiter::local_join().await;
|
||||||
|
});
|
||||||
|
assert!(
|
||||||
|
instant.elapsed() >= time,
|
||||||
|
"Join on current arbiter should wait for all spawned futures"
|
||||||
|
);
|
||||||
|
|
||||||
|
let large_timer = Duration::from_secs(20);
|
||||||
|
let instant = Instant::now();
|
||||||
|
actix_rt::System::new("test_join_current_arbiter").block_on(async move {
|
||||||
|
actix_rt::spawn(async move {
|
||||||
|
tokio::time::delay_for(time).await;
|
||||||
|
actix_rt::Arbiter::current().stop();
|
||||||
|
});
|
||||||
|
let f = actix_rt::Arbiter::local_join();
|
||||||
|
actix_rt::spawn(async move {
|
||||||
|
tokio::time::delay_for(large_timer).await;
|
||||||
|
actix_rt::Arbiter::current().stop();
|
||||||
|
});
|
||||||
|
f.await;
|
||||||
|
});
|
||||||
|
assert!(
|
||||||
|
instant.elapsed() < large_timer,
|
||||||
|
"local_join should await only for the already spawned futures"
|
||||||
|
);
|
||||||
|
}
|
@@ -1,5 +1,40 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [1.0.3] - 2020-05-19
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Replace deprecated `net2` crate with `socket2` [#140]
|
||||||
|
|
||||||
|
[#140]: https://github.com/actix/actix-net/pull/140
|
||||||
|
|
||||||
|
## [1.0.2] - 2020-02-26
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
* Avoid error by calling `reregister()` on Windows [#103]
|
||||||
|
|
||||||
|
[#103]: https://github.com/actix/actix-net/pull/103
|
||||||
|
|
||||||
|
## [1.0.1] - 2019-12-29
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Rename `.start()` method to `.run()`
|
||||||
|
|
||||||
|
## [1.0.0] - 2019-12-11
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Use actix-net releases
|
||||||
|
|
||||||
|
|
||||||
|
## [1.0.0-alpha.4] - 2019-12-08
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Use actix-service 1.0.0-alpha.4
|
||||||
|
|
||||||
## [1.0.0-alpha.3] - 2019-12-07
|
## [1.0.0-alpha.3] - 2019-12-07
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-server"
|
name = "actix-server"
|
||||||
version = "1.0.0-alpha.3"
|
version = "1.0.3"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix server - General purpose tcp server"
|
description = "Actix server - General purpose tcp server"
|
||||||
keywords = ["network", "framework", "async", "futures"]
|
keywords = ["network", "framework", "async", "futures"]
|
||||||
@@ -9,7 +9,7 @@ repository = "https://github.com/actix/actix-net.git"
|
|||||||
documentation = "https://docs.rs/actix-server/"
|
documentation = "https://docs.rs/actix-server/"
|
||||||
categories = ["network-programming", "asynchronous"]
|
categories = ["network-programming", "asynchronous"]
|
||||||
license = "MIT/Apache-2.0"
|
license = "MIT/Apache-2.0"
|
||||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
exclude = [".gitignore", ".cargo/config"]
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
workspace = ".."
|
workspace = ".."
|
||||||
|
|
||||||
@@ -21,22 +21,24 @@ path = "src/lib.rs"
|
|||||||
default = []
|
default = []
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-service = "1.0.0-alpha.3"
|
actix-service = "1.0.1"
|
||||||
actix-rt = "1.0.0-alpha.3"
|
actix-rt = "1.0.0"
|
||||||
actix-codec = "0.2.0-alpha.3"
|
actix-codec = "0.2.0"
|
||||||
actix-utils = "1.0.0-alpha.3"
|
actix-utils = "1.0.4"
|
||||||
|
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
num_cpus = "1.0"
|
num_cpus = "1.11"
|
||||||
mio = "0.6.19"
|
mio = "0.6.19"
|
||||||
net2 = "0.2"
|
socket2 = "0.3"
|
||||||
futures = "0.3.1"
|
futures-channel = { version = "0.3.4", default-features = false }
|
||||||
|
futures-util = { version = "0.3.4", default-features = false, features = ["sink"] }
|
||||||
slab = "0.4"
|
slab = "0.4"
|
||||||
|
|
||||||
# unix domain sockets
|
# unix domain sockets
|
||||||
|
# FIXME: Remove it and use mio own uds feature once mio 0.7 is released
|
||||||
mio-uds = { version = "0.6.7" }
|
mio-uds = { version = "0.6.7" }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
bytes = "0.5"
|
bytes = "0.5"
|
||||||
env_logger = "0.6"
|
env_logger = "0.7"
|
||||||
actix-testing = "1.0.0-alpha.3"
|
actix-testing = "1.0.0"
|
||||||
|
@@ -298,12 +298,7 @@ impl Accept {
|
|||||||
}
|
}
|
||||||
Command::Resume => {
|
Command::Resume => {
|
||||||
for (token, info) in self.sockets.iter() {
|
for (token, info) in self.sockets.iter() {
|
||||||
if let Err(err) = self.poll.register(
|
if let Err(err) = self.register(token, info) {
|
||||||
&info.sock,
|
|
||||||
mio::Token(token + DELTA),
|
|
||||||
mio::Ready::readable(),
|
|
||||||
mio::PollOpt::edge(),
|
|
||||||
) {
|
|
||||||
error!("Can not resume socket accept process: {}", err);
|
error!("Can not resume socket accept process: {}", err);
|
||||||
} else {
|
} else {
|
||||||
info!(
|
info!(
|
||||||
@@ -338,17 +333,44 @@ impl Accept {
|
|||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(not(target_os = "windows"))]
|
||||||
|
fn register(&self, token: usize, info: &ServerSocketInfo) -> io::Result<()> {
|
||||||
|
self.poll.register(
|
||||||
|
&info.sock,
|
||||||
|
mio::Token(token + DELTA),
|
||||||
|
mio::Ready::readable(),
|
||||||
|
mio::PollOpt::edge(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
fn register(&self, token: usize, info: &ServerSocketInfo) -> io::Result<()> {
|
||||||
|
// On windows, calling register without deregister cause an error.
|
||||||
|
// See https://github.com/actix/actix-web/issues/905
|
||||||
|
// Calling reregister seems to fix the issue.
|
||||||
|
self.poll
|
||||||
|
.register(
|
||||||
|
&info.sock,
|
||||||
|
mio::Token(token + DELTA),
|
||||||
|
mio::Ready::readable(),
|
||||||
|
mio::PollOpt::edge(),
|
||||||
|
)
|
||||||
|
.or_else(|_| {
|
||||||
|
self.poll.reregister(
|
||||||
|
&info.sock,
|
||||||
|
mio::Token(token + DELTA),
|
||||||
|
mio::Ready::readable(),
|
||||||
|
mio::PollOpt::edge(),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
fn backpressure(&mut self, on: bool) {
|
fn backpressure(&mut self, on: bool) {
|
||||||
if self.backpressure {
|
if self.backpressure {
|
||||||
if !on {
|
if !on {
|
||||||
self.backpressure = false;
|
self.backpressure = false;
|
||||||
for (token, info) in self.sockets.iter() {
|
for (token, info) in self.sockets.iter() {
|
||||||
if let Err(err) = self.poll.register(
|
if let Err(err) = self.register(token, info) {
|
||||||
&info.sock,
|
|
||||||
mio::Token(token + DELTA),
|
|
||||||
mio::Ready::readable(),
|
|
||||||
mio::PollOpt::edge(),
|
|
||||||
) {
|
|
||||||
error!("Can not resume socket accept process: {}", err);
|
error!("Can not resume socket accept process: {}", err);
|
||||||
} else {
|
} else {
|
||||||
info!("Accepting connections on {} has been resumed", info.addr);
|
info!("Accepting connections on {} has been resumed", info.addr);
|
||||||
|
@@ -6,14 +6,13 @@ use std::{io, mem, net};
|
|||||||
use actix_rt::net::TcpStream;
|
use actix_rt::net::TcpStream;
|
||||||
use actix_rt::time::{delay_until, Instant};
|
use actix_rt::time::{delay_until, Instant};
|
||||||
use actix_rt::{spawn, System};
|
use actix_rt::{spawn, System};
|
||||||
use futures::channel::mpsc::{unbounded, UnboundedReceiver};
|
use futures_channel::mpsc::{unbounded, UnboundedReceiver};
|
||||||
use futures::channel::oneshot;
|
use futures_channel::oneshot;
|
||||||
use futures::future::ready;
|
use futures_util::future::ready;
|
||||||
use futures::stream::FuturesUnordered;
|
use futures_util::stream::FuturesUnordered;
|
||||||
use futures::{ready, Future, FutureExt, Stream, StreamExt};
|
use futures_util::{future::Future, ready, stream::Stream, FutureExt, StreamExt};
|
||||||
use log::{error, info};
|
use log::{error, info};
|
||||||
use net2::TcpBuilder;
|
use socket2::{Domain, Protocol, Socket, Type};
|
||||||
use num_cpus;
|
|
||||||
|
|
||||||
use crate::accept::{AcceptLoop, AcceptNotify, Command};
|
use crate::accept::{AcceptLoop, AcceptNotify, Command};
|
||||||
use crate::config::{ConfiguredService, ServiceConfig};
|
use crate::config::{ConfiguredService, ServiceConfig};
|
||||||
@@ -31,7 +30,7 @@ pub struct ServerBuilder {
|
|||||||
backlog: i32,
|
backlog: i32,
|
||||||
workers: Vec<(usize, WorkerClient)>,
|
workers: Vec<(usize, WorkerClient)>,
|
||||||
services: Vec<Box<dyn InternalServiceFactory>>,
|
services: Vec<Box<dyn InternalServiceFactory>>,
|
||||||
sockets: Vec<(Token, StdListener)>,
|
sockets: Vec<(Token, String, StdListener)>,
|
||||||
accept: AcceptLoop,
|
accept: AcceptLoop,
|
||||||
exit: bool,
|
exit: bool,
|
||||||
shutdown_timeout: Duration,
|
shutdown_timeout: Duration,
|
||||||
@@ -146,8 +145,8 @@ impl ServerBuilder {
|
|||||||
let mut srv = ConfiguredService::new(apply);
|
let mut srv = ConfiguredService::new(apply);
|
||||||
for (name, lst) in cfg.services {
|
for (name, lst) in cfg.services {
|
||||||
let token = self.token.next();
|
let token = self.token.next();
|
||||||
srv.stream(token, name, lst.local_addr()?);
|
srv.stream(token, name.clone(), lst.local_addr()?);
|
||||||
self.sockets.push((token, StdListener::Tcp(lst)));
|
self.sockets.push((token, name, StdListener::Tcp(lst)));
|
||||||
}
|
}
|
||||||
self.services.push(Box::new(srv));
|
self.services.push(Box::new(srv));
|
||||||
}
|
}
|
||||||
@@ -172,7 +171,8 @@ impl ServerBuilder {
|
|||||||
factory.clone(),
|
factory.clone(),
|
||||||
lst.local_addr()?,
|
lst.local_addr()?,
|
||||||
));
|
));
|
||||||
self.sockets.push((token, StdListener::Tcp(lst)));
|
self.sockets
|
||||||
|
.push((token, name.as_ref().to_string(), StdListener::Tcp(lst)));
|
||||||
}
|
}
|
||||||
Ok(self)
|
Ok(self)
|
||||||
}
|
}
|
||||||
@@ -219,10 +219,11 @@ impl ServerBuilder {
|
|||||||
self.services.push(StreamNewService::create(
|
self.services.push(StreamNewService::create(
|
||||||
name.as_ref().to_string(),
|
name.as_ref().to_string(),
|
||||||
token,
|
token,
|
||||||
factory.clone(),
|
factory,
|
||||||
addr,
|
addr,
|
||||||
));
|
));
|
||||||
self.sockets.push((token, StdListener::Uds(lst)));
|
self.sockets
|
||||||
|
.push((token, name.as_ref().to_string(), StdListener::Uds(lst)));
|
||||||
Ok(self)
|
Ok(self)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -243,55 +244,44 @@ impl ServerBuilder {
|
|||||||
factory,
|
factory,
|
||||||
lst.local_addr()?,
|
lst.local_addr()?,
|
||||||
));
|
));
|
||||||
self.sockets.push((token, StdListener::Tcp(lst)));
|
self.sockets
|
||||||
|
.push((token, name.as_ref().to_string(), StdListener::Tcp(lst)));
|
||||||
Ok(self)
|
Ok(self)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Spawn new thread and start listening for incoming connections.
|
#[doc(hidden)]
|
||||||
///
|
pub fn start(self) -> Server {
|
||||||
/// This method spawns new thread and starts new actix system. Other than
|
self.run()
|
||||||
/// that it is similar to `start()` method. This method blocks.
|
|
||||||
///
|
|
||||||
/// This methods panics if no socket addresses get bound.
|
|
||||||
///
|
|
||||||
/// ```rust,ignore
|
|
||||||
/// use actix_web::*;
|
|
||||||
///
|
|
||||||
/// fn main() -> std::io::Result<()> {
|
|
||||||
/// Server::new().
|
|
||||||
/// .service(
|
|
||||||
/// HttpServer::new(|| App::new().service(web::service("/").to(|| HttpResponse::Ok())))
|
|
||||||
/// .bind("127.0.0.1:0")
|
|
||||||
/// .run()
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
pub fn run(self) -> io::Result<()> {
|
|
||||||
let sys = System::new("http-server");
|
|
||||||
self.start();
|
|
||||||
sys.run()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Starts processing incoming connections and return server controller.
|
/// Starts processing incoming connections and return server controller.
|
||||||
pub fn start(mut self) -> Server {
|
pub fn run(mut self) -> Server {
|
||||||
if self.sockets.is_empty() {
|
if self.sockets.is_empty() {
|
||||||
panic!("Server should have at least one bound socket");
|
panic!("Server should have at least one bound socket");
|
||||||
} else {
|
} else {
|
||||||
info!("Starting {} workers", self.threads);
|
info!("Starting {} workers", self.threads);
|
||||||
|
|
||||||
// start workers
|
// start workers
|
||||||
let mut workers = Vec::new();
|
let workers = (0..self.threads)
|
||||||
for idx in 0..self.threads {
|
.map(|idx| {
|
||||||
let worker = self.start_worker(idx, self.accept.get_notify());
|
let worker = self.start_worker(idx, self.accept.get_notify());
|
||||||
workers.push(worker.clone());
|
self.workers.push((idx, worker.clone()));
|
||||||
self.workers.push((idx, worker));
|
|
||||||
}
|
worker
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
// start accept thread
|
// start accept thread
|
||||||
for sock in &self.sockets {
|
for sock in &self.sockets {
|
||||||
info!("Starting server on {}", sock.1);
|
info!("Starting \"{}\" service on {}", sock.1, sock.2);
|
||||||
}
|
}
|
||||||
self.accept
|
self.accept.start(
|
||||||
.start(mem::replace(&mut self.sockets, Vec::new()), workers);
|
mem::replace(&mut self.sockets, Vec::new())
|
||||||
|
.into_iter()
|
||||||
|
.map(|t| (t.0, t.2))
|
||||||
|
.collect(),
|
||||||
|
workers,
|
||||||
|
);
|
||||||
|
|
||||||
// handle signals
|
// handle signals
|
||||||
if !self.no_signals {
|
if !self.no_signals {
|
||||||
@@ -391,7 +381,7 @@ impl ServerBuilder {
|
|||||||
.await;
|
.await;
|
||||||
System::current().stop();
|
System::current().stop();
|
||||||
}
|
}
|
||||||
.boxed(),
|
.boxed(),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
ready(())
|
ready(())
|
||||||
@@ -497,11 +487,13 @@ pub(super) fn bind_addr<S: net::ToSocketAddrs>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn create_tcp_listener(addr: net::SocketAddr, backlog: i32) -> io::Result<net::TcpListener> {
|
fn create_tcp_listener(addr: net::SocketAddr, backlog: i32) -> io::Result<net::TcpListener> {
|
||||||
let builder = match addr {
|
let domain = match addr {
|
||||||
net::SocketAddr::V4(_) => TcpBuilder::new_v4()?,
|
net::SocketAddr::V4(_) => Domain::ipv4(),
|
||||||
net::SocketAddr::V6(_) => TcpBuilder::new_v6()?,
|
net::SocketAddr::V6(_) => Domain::ipv6(),
|
||||||
};
|
};
|
||||||
builder.reuse_address(true)?;
|
let socket = Socket::new(domain, Type::stream(), Some(Protocol::tcp()))?;
|
||||||
builder.bind(addr)?;
|
socket.set_reuse_address(true)?;
|
||||||
Ok(builder.listen(backlog)?)
|
socket.bind(&addr.into())?;
|
||||||
|
socket.listen(backlog)?;
|
||||||
|
Ok(socket.into_tcp_listener())
|
||||||
}
|
}
|
||||||
|
@@ -4,7 +4,7 @@ use std::{fmt, io, net};
|
|||||||
use actix_rt::net::TcpStream;
|
use actix_rt::net::TcpStream;
|
||||||
use actix_service as actix;
|
use actix_service as actix;
|
||||||
use actix_utils::counter::CounterGuard;
|
use actix_utils::counter::CounterGuard;
|
||||||
use futures::future::{ok, Future, FutureExt, LocalBoxFuture};
|
use futures_util::future::{ok, Future, FutureExt, LocalBoxFuture};
|
||||||
use log::error;
|
use log::error;
|
||||||
|
|
||||||
use super::builder::bind_addr;
|
use super::builder::bind_addr;
|
||||||
@@ -91,7 +91,7 @@ impl ConfiguredService {
|
|||||||
|
|
||||||
pub(super) fn stream(&mut self, token: Token, name: String, addr: net::SocketAddr) {
|
pub(super) fn stream(&mut self, token: Token, name: String, addr: net::SocketAddr) {
|
||||||
self.names.insert(token, (name.clone(), addr));
|
self.names.insert(token, (name.clone(), addr));
|
||||||
self.topics.insert(name.clone(), token);
|
self.topics.insert(name, token);
|
||||||
self.services.push(token);
|
self.services.push(token);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -142,7 +142,7 @@ impl InternalServiceFactory for ConfiguredService {
|
|||||||
let name = names.remove(&token).unwrap().0;
|
let name = names.remove(&token).unwrap().0;
|
||||||
res.push((
|
res.push((
|
||||||
token,
|
token,
|
||||||
Box::new(StreamService::new(actix::service_fn2(
|
Box::new(StreamService::new(actix::fn_service(
|
||||||
move |_: TcpStream| {
|
move |_: TcpStream| {
|
||||||
error!("Service {:?} is not configured", name);
|
error!("Service {:?} is not configured", name);
|
||||||
ok::<_, ()>(())
|
ok::<_, ()>(())
|
||||||
@@ -153,7 +153,7 @@ impl InternalServiceFactory for ConfiguredService {
|
|||||||
}
|
}
|
||||||
return Ok(res);
|
return Ok(res);
|
||||||
}
|
}
|
||||||
.boxed_local()
|
.boxed_local()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -218,7 +218,7 @@ impl ServiceRuntime {
|
|||||||
// let name = name.to_owned();
|
// let name = name.to_owned();
|
||||||
if let Some(token) = self.names.get(name) {
|
if let Some(token) = self.names.get(name) {
|
||||||
self.services.insert(
|
self.services.insert(
|
||||||
token.clone(),
|
*token,
|
||||||
Box::new(ServiceFactory {
|
Box::new(ServiceFactory {
|
||||||
inner: service.into_factory(),
|
inner: service.into_factory(),
|
||||||
}),
|
}),
|
||||||
@@ -280,6 +280,6 @@ where
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
.boxed_local()
|
.boxed_local()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -3,9 +3,9 @@ use std::io;
|
|||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
use futures::channel::mpsc::UnboundedSender;
|
use futures_channel::mpsc::UnboundedSender;
|
||||||
use futures::channel::oneshot;
|
use futures_channel::oneshot;
|
||||||
use futures::FutureExt;
|
use futures_util::FutureExt;
|
||||||
|
|
||||||
use crate::builder::ServerBuilder;
|
use crate::builder::ServerBuilder;
|
||||||
use crate::signals::Signal;
|
use crate::signals::Signal;
|
||||||
|
@@ -6,8 +6,8 @@ use std::time::Duration;
|
|||||||
use actix_rt::spawn;
|
use actix_rt::spawn;
|
||||||
use actix_service::{self as actix, Service, ServiceFactory as ActixServiceFactory};
|
use actix_service::{self as actix, Service, ServiceFactory as ActixServiceFactory};
|
||||||
use actix_utils::counter::CounterGuard;
|
use actix_utils::counter::CounterGuard;
|
||||||
use futures::future::{err, ok, LocalBoxFuture, Ready};
|
use futures_util::future::{err, ok, LocalBoxFuture, Ready};
|
||||||
use futures::{FutureExt, TryFutureExt};
|
use futures_util::{FutureExt, TryFutureExt};
|
||||||
use log::error;
|
use log::error;
|
||||||
|
|
||||||
use super::Token;
|
use super::Token;
|
||||||
|
@@ -3,7 +3,7 @@ use std::io;
|
|||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
use futures::future::lazy;
|
use futures_util::future::lazy;
|
||||||
|
|
||||||
use crate::server::Server;
|
use crate::server::Server;
|
||||||
|
|
||||||
|
@@ -7,10 +7,10 @@ use std::time;
|
|||||||
use actix_rt::time::{delay_until, Delay, Instant};
|
use actix_rt::time::{delay_until, Delay, Instant};
|
||||||
use actix_rt::{spawn, Arbiter};
|
use actix_rt::{spawn, Arbiter};
|
||||||
use actix_utils::counter::Counter;
|
use actix_utils::counter::Counter;
|
||||||
use futures::channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender};
|
use futures_channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender};
|
||||||
use futures::channel::oneshot;
|
use futures_channel::oneshot;
|
||||||
use futures::future::{join_all, LocalBoxFuture, MapOk};
|
use futures_util::future::{join_all, LocalBoxFuture, MapOk};
|
||||||
use futures::{Future, FutureExt, Stream, TryFutureExt};
|
use futures_util::{future::Future, stream::Stream, FutureExt, TryFutureExt};
|
||||||
use log::{error, info, trace};
|
use log::{error, info, trace};
|
||||||
|
|
||||||
use crate::accept::AcceptNotify;
|
use crate::accept::AcceptNotify;
|
||||||
@@ -217,7 +217,7 @@ impl Worker {
|
|||||||
wrk.await
|
wrk.await
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
.boxed(),
|
.boxed(),
|
||||||
);
|
);
|
||||||
|
|
||||||
WorkerClient::new(idx, tx1, tx2, avail)
|
WorkerClient::new(idx, tx1, tx2, avail)
|
||||||
@@ -315,6 +315,8 @@ enum WorkerState {
|
|||||||
impl Future for Worker {
|
impl Future for Worker {
|
||||||
type Output = ();
|
type Output = ();
|
||||||
|
|
||||||
|
// FIXME: remove this attribute
|
||||||
|
#[allow(clippy::never_loop)]
|
||||||
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> {
|
||||||
// `StopWorker` message handler
|
// `StopWorker` message handler
|
||||||
if let Poll::Ready(Some(StopCommand { graceful, result })) =
|
if let Poll::Ready(Some(StopCommand { graceful, result })) =
|
||||||
@@ -368,11 +370,8 @@ impl Future for Worker {
|
|||||||
Ok(false) => {
|
Ok(false) => {
|
||||||
// push connection back to queue
|
// push connection back to queue
|
||||||
if let Some(conn) = conn {
|
if let Some(conn) = conn {
|
||||||
match self.state {
|
if let WorkerState::Unavailable(ref mut conns) = self.state {
|
||||||
WorkerState::Unavailable(ref mut conns) => {
|
conns.push(conn);
|
||||||
conns.push(conn);
|
|
||||||
}
|
|
||||||
_ => (),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Poll::Pending
|
Poll::Pending
|
||||||
|
@@ -1,23 +1,18 @@
|
|||||||
use std::io::Read;
|
|
||||||
use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
|
use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
|
||||||
use std::sync::{mpsc, Arc};
|
use std::sync::{mpsc, Arc};
|
||||||
use std::{net, thread, time};
|
use std::{net, thread, time};
|
||||||
|
|
||||||
use actix_codec::{BytesCodec, Framed};
|
|
||||||
use actix_rt::net::TcpStream;
|
|
||||||
use actix_server::Server;
|
use actix_server::Server;
|
||||||
use actix_service::service_fn;
|
use actix_service::fn_service;
|
||||||
use bytes::Bytes;
|
use futures_util::future::{lazy, ok};
|
||||||
use futures::future::{lazy, ok};
|
use socket2::{Domain, Protocol, Socket, Type};
|
||||||
use futures::SinkExt;
|
|
||||||
use net2::TcpBuilder;
|
|
||||||
|
|
||||||
fn unused_addr() -> net::SocketAddr {
|
fn unused_addr() -> net::SocketAddr {
|
||||||
let addr: net::SocketAddr = "127.0.0.1:0".parse().unwrap();
|
let addr: net::SocketAddr = "127.0.0.1:0".parse().unwrap();
|
||||||
let socket = TcpBuilder::new_v4().unwrap();
|
let socket = Socket::new(Domain::ipv4(), Type::stream(), Some(Protocol::tcp())).unwrap();
|
||||||
socket.bind(&addr).unwrap();
|
socket.bind(&addr.into()).unwrap();
|
||||||
socket.reuse_address(true).unwrap();
|
socket.set_reuse_address(true).unwrap();
|
||||||
let tcp = socket.to_tcp_listener().unwrap();
|
let tcp = socket.into_tcp_listener();
|
||||||
tcp.local_addr().unwrap()
|
tcp.local_addr().unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -31,7 +26,7 @@ fn test_bind() {
|
|||||||
let srv = Server::build()
|
let srv = Server::build()
|
||||||
.workers(1)
|
.workers(1)
|
||||||
.disable_signals()
|
.disable_signals()
|
||||||
.bind("test", addr, move || service_fn(|_| ok::<_, ()>(())))
|
.bind("test", addr, move || fn_service(|_| ok::<_, ()>(())))
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.start();
|
.start();
|
||||||
let _ = tx.send((srv, actix_rt::System::current()));
|
let _ = tx.send((srv, actix_rt::System::current()));
|
||||||
@@ -41,7 +36,7 @@ fn test_bind() {
|
|||||||
|
|
||||||
thread::sleep(time::Duration::from_millis(500));
|
thread::sleep(time::Duration::from_millis(500));
|
||||||
assert!(net::TcpStream::connect(addr).is_ok());
|
assert!(net::TcpStream::connect(addr).is_ok());
|
||||||
let _ = sys.stop();
|
sys.stop();
|
||||||
let _ = h.join();
|
let _ = h.join();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -56,7 +51,7 @@ fn test_listen() {
|
|||||||
Server::build()
|
Server::build()
|
||||||
.disable_signals()
|
.disable_signals()
|
||||||
.workers(1)
|
.workers(1)
|
||||||
.listen("test", lst, move || service_fn(|_| ok::<_, ()>(())))
|
.listen("test", lst, move || fn_service(|_| ok::<_, ()>(())))
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.start();
|
.start();
|
||||||
let _ = tx.send(actix_rt::System::current());
|
let _ = tx.send(actix_rt::System::current());
|
||||||
@@ -66,13 +61,19 @@ fn test_listen() {
|
|||||||
|
|
||||||
thread::sleep(time::Duration::from_millis(500));
|
thread::sleep(time::Duration::from_millis(500));
|
||||||
assert!(net::TcpStream::connect(addr).is_ok());
|
assert!(net::TcpStream::connect(addr).is_ok());
|
||||||
let _ = sys.stop();
|
sys.stop();
|
||||||
let _ = h.join();
|
let _ = h.join();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
fn test_start() {
|
fn test_start() {
|
||||||
|
use actix_codec::{BytesCodec, Framed};
|
||||||
|
use actix_rt::net::TcpStream;
|
||||||
|
use bytes::Bytes;
|
||||||
|
use futures_util::sink::SinkExt;
|
||||||
|
use std::io::Read;
|
||||||
|
|
||||||
let addr = unused_addr();
|
let addr = unused_addr();
|
||||||
let (tx, rx) = mpsc::channel();
|
let (tx, rx) = mpsc::channel();
|
||||||
|
|
||||||
@@ -82,12 +83,10 @@ fn test_start() {
|
|||||||
.backlog(100)
|
.backlog(100)
|
||||||
.disable_signals()
|
.disable_signals()
|
||||||
.bind("test", addr, move || {
|
.bind("test", addr, move || {
|
||||||
service_fn(|io: TcpStream| {
|
fn_service(|io: TcpStream| async move {
|
||||||
async move {
|
let mut f = Framed::new(io, BytesCodec);
|
||||||
let mut f = Framed::new(io, BytesCodec);
|
f.send(Bytes::from_static(b"test")).await.unwrap();
|
||||||
f.send(Bytes::from_static(b"test")).await.unwrap();
|
Ok::<_, ()>(())
|
||||||
Ok::<_, ()>(())
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.unwrap()
|
.unwrap()
|
||||||
@@ -130,7 +129,7 @@ fn test_start() {
|
|||||||
assert!(net::TcpStream::connect(addr).is_err());
|
assert!(net::TcpStream::connect(addr).is_err());
|
||||||
|
|
||||||
thread::sleep(time::Duration::from_millis(100));
|
thread::sleep(time::Duration::from_millis(100));
|
||||||
let _ = sys.stop();
|
sys.stop();
|
||||||
let _ = h.join();
|
let _ = h.join();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -158,8 +157,8 @@ fn test_configure() {
|
|||||||
.listen("addr3", lst)
|
.listen("addr3", lst)
|
||||||
.apply(move |rt| {
|
.apply(move |rt| {
|
||||||
let num = num.clone();
|
let num = num.clone();
|
||||||
rt.service("addr1", service_fn(|_| ok::<_, ()>(())));
|
rt.service("addr1", fn_service(|_| ok::<_, ()>(())));
|
||||||
rt.service("addr3", service_fn(|_| ok::<_, ()>(())));
|
rt.service("addr3", fn_service(|_| ok::<_, ()>(())));
|
||||||
rt.on_start(lazy(move |_| {
|
rt.on_start(lazy(move |_| {
|
||||||
let _ = num.fetch_add(1, Relaxed);
|
let _ = num.fetch_add(1, Relaxed);
|
||||||
}))
|
}))
|
||||||
@@ -178,6 +177,6 @@ fn test_configure() {
|
|||||||
assert!(net::TcpStream::connect(addr2).is_ok());
|
assert!(net::TcpStream::connect(addr2).is_ok());
|
||||||
assert!(net::TcpStream::connect(addr3).is_ok());
|
assert!(net::TcpStream::connect(addr3).is_ok());
|
||||||
assert_eq!(num.load(Relaxed), 1);
|
assert_eq!(num.load(Relaxed), 1);
|
||||||
let _ = sys.stop();
|
sys.stop();
|
||||||
let _ = h.join();
|
let _ = h.join();
|
||||||
}
|
}
|
||||||
|
@@ -1,5 +1,55 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [1.0.5] - 2020-01-16
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
* Fixed unsoundness in .and_then()/.then() service combinators
|
||||||
|
|
||||||
|
## [1.0.4] - 2020-01-15
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
* Revert 1.0.3 change
|
||||||
|
|
||||||
|
## [1.0.3] - 2020-01-15
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
* Fixed unsoundness in `AndThenService` impl
|
||||||
|
|
||||||
|
## [1.0.2] - 2020-01-08
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
* Add `into_service` helper function
|
||||||
|
|
||||||
|
|
||||||
|
## [1.0.1] - 2019-12-22
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* `map_config()` and `unit_config()` accepts `IntoServiceFactory` type
|
||||||
|
|
||||||
|
|
||||||
|
## [1.0.0] - 2019-12-11
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
* Add Clone impl for Apply service
|
||||||
|
|
||||||
|
|
||||||
|
## [1.0.0-alpha.4] - 2019-12-08
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Renamed `service_fn` to `fn_service`
|
||||||
|
|
||||||
|
* Renamed `factory_fn` to `fn_factory`
|
||||||
|
|
||||||
|
* Renamed `factory_fn_cfg` to `fn_factory_with_config`
|
||||||
|
|
||||||
|
|
||||||
## [1.0.0-alpha.3] - 2019-12-06
|
## [1.0.0-alpha.3] - 2019-12-06
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
@@ -1,22 +1,15 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-service"
|
name = "actix-service"
|
||||||
version = "1.0.0-alpha.3"
|
version = "1.0.5"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix Service"
|
description = "Actix service"
|
||||||
keywords = ["network", "framework", "async", "futures"]
|
keywords = ["network", "framework", "async", "futures"]
|
||||||
homepage = "https://actix.rs"
|
homepage = "https://actix.rs"
|
||||||
repository = "https://github.com/actix/actix-net.git"
|
repository = "https://github.com/actix/actix-net.git"
|
||||||
documentation = "https://docs.rs/actix-service/"
|
documentation = "https://docs.rs/actix-service/"
|
||||||
categories = ["network-programming", "asynchronous"]
|
categories = ["network-programming", "asynchronous"]
|
||||||
license = "MIT/Apache-2.0"
|
license = "MIT/Apache-2.0"
|
||||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
workspace = ".."
|
|
||||||
|
|
||||||
[badges]
|
|
||||||
travis-ci = { repository = "actix/actix-service", branch = "master" }
|
|
||||||
appveyor = { repository = "actix/actix-net" }
|
|
||||||
codecov = { repository = "actix/actix-service", branch = "master", service = "github" }
|
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
name = "actix_service"
|
name = "actix_service"
|
||||||
@@ -27,4 +20,13 @@ futures-util = "0.3.1"
|
|||||||
pin-project = "0.4.6"
|
pin-project = "0.4.6"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-rt = "1.0.0-alpha.2"
|
actix-rt = "1.0.0"
|
||||||
|
criterion = "0.3"
|
||||||
|
|
||||||
|
[[bench]]
|
||||||
|
name = "unsafecell_vs_refcell"
|
||||||
|
harness = false
|
||||||
|
|
||||||
|
[[bench]]
|
||||||
|
name = "and_then"
|
||||||
|
harness = false
|
||||||
|
324
actix-service/benches/and_then.rs
Normal file
324
actix-service/benches/and_then.rs
Normal file
@@ -0,0 +1,324 @@
|
|||||||
|
/// Benchmark various implementations of and_then
|
||||||
|
|
||||||
|
use criterion::{criterion_main, Criterion};
|
||||||
|
use futures_util::future::join_all;
|
||||||
|
use std::cell::{RefCell, UnsafeCell};
|
||||||
|
use std::task::{Context, Poll};
|
||||||
|
use std::rc::Rc;
|
||||||
|
use actix_service::{Service};
|
||||||
|
use actix_service::IntoService;
|
||||||
|
use std::future::Future;
|
||||||
|
use std::pin::Pin;
|
||||||
|
use futures_util::future::TryFutureExt;
|
||||||
|
use actix_service::boxed::BoxFuture;
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Test services A,B for AndThen service implementations
|
||||||
|
*/
|
||||||
|
|
||||||
|
async fn svc1(_: ()) -> Result<usize, ()> {
|
||||||
|
Ok(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn svc2(req: usize) -> Result<usize, ()> {
|
||||||
|
Ok(req + 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* AndThenUC - original AndThen service based on UnsafeCell
|
||||||
|
* Cut down version of actix_service::AndThenService based on actix-service::Cell
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
struct AndThenUC<A,B>(Rc<UnsafeCell<(A, B)>>);
|
||||||
|
|
||||||
|
impl<A,B> AndThenUC<A,B> {
|
||||||
|
fn new(a: A, b: B) -> Self
|
||||||
|
where
|
||||||
|
A: Service,
|
||||||
|
B: Service<Request = A::Response, Error = A::Error>,
|
||||||
|
{
|
||||||
|
Self(Rc::new(UnsafeCell::new((a,b))))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<A,B> Clone for AndThenUC<A,B> {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
Self(self.0.clone())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<A,B> Service for AndThenUC<A,B>
|
||||||
|
where
|
||||||
|
A: Service,
|
||||||
|
B: Service<Request = A::Response, Error = A::Error>
|
||||||
|
{
|
||||||
|
type Request = A::Request;
|
||||||
|
type Response = B::Response;
|
||||||
|
type Error = A::Error;
|
||||||
|
type Future = AndThenServiceResponse<A,B>;
|
||||||
|
|
||||||
|
fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||||
|
Poll::Ready(Ok(()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn call(&mut self, req: A::Request) -> Self::Future {
|
||||||
|
let fut = unsafe { &mut *(*self.0).get() }.0.call(req);
|
||||||
|
AndThenServiceResponse {
|
||||||
|
state: State::A(fut, Some(self.0.clone()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pin_project::pin_project]
|
||||||
|
pub(crate) struct AndThenServiceResponse<A, B>
|
||||||
|
where
|
||||||
|
A: Service,
|
||||||
|
B: Service<Request = A::Response, Error = A::Error>,
|
||||||
|
{
|
||||||
|
#[pin]
|
||||||
|
state: State<A, B>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pin_project::pin_project]
|
||||||
|
enum State<A, B>
|
||||||
|
where
|
||||||
|
A: Service,
|
||||||
|
B: Service<Request = A::Response, Error = A::Error>,
|
||||||
|
{
|
||||||
|
A(#[pin] A::Future, Option<Rc<UnsafeCell<(A, B)>>>),
|
||||||
|
B(#[pin] B::Future),
|
||||||
|
Empty,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<A, B> Future for AndThenServiceResponse<A, B>
|
||||||
|
where
|
||||||
|
A: Service,
|
||||||
|
B: Service<Request = A::Response, Error = A::Error>,
|
||||||
|
{
|
||||||
|
type Output = Result<B::Response, A::Error>;
|
||||||
|
|
||||||
|
#[pin_project::project]
|
||||||
|
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||||
|
let mut this = self.as_mut().project();
|
||||||
|
|
||||||
|
#[project]
|
||||||
|
match this.state.as_mut().project() {
|
||||||
|
State::A(fut, b) => match fut.poll(cx)? {
|
||||||
|
Poll::Ready(res) => {
|
||||||
|
let b = b.take().unwrap();
|
||||||
|
this.state.set(State::Empty); // drop fut A
|
||||||
|
let fut = unsafe { &mut (*b.get()).1 }.call(res);
|
||||||
|
this.state.set(State::B(fut));
|
||||||
|
self.poll(cx)
|
||||||
|
}
|
||||||
|
Poll::Pending => Poll::Pending,
|
||||||
|
},
|
||||||
|
State::B(fut) => fut.poll(cx).map(|r| {
|
||||||
|
this.state.set(State::Empty);
|
||||||
|
r
|
||||||
|
}),
|
||||||
|
State::Empty => panic!("future must not be polled after it returned `Poll::Ready`"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
* AndThenRC - AndThen service based on RefCell
|
||||||
|
*/
|
||||||
|
|
||||||
|
struct AndThenRC<A,B>(Rc<RefCell<(A, B)>>);
|
||||||
|
|
||||||
|
impl<A,B> AndThenRC<A,B> {
|
||||||
|
fn new(a: A, b: B) -> Self
|
||||||
|
where
|
||||||
|
A: Service,
|
||||||
|
B: Service<Request = A::Response, Error = A::Error>,
|
||||||
|
{
|
||||||
|
Self(Rc::new(RefCell::new((a,b))))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<A,B> Clone for AndThenRC<A,B> {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
Self(self.0.clone())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<A,B> Service for AndThenRC<A,B>
|
||||||
|
where
|
||||||
|
A: Service,
|
||||||
|
B: Service<Request = A::Response, Error = A::Error>
|
||||||
|
{
|
||||||
|
type Request = A::Request;
|
||||||
|
type Response = B::Response;
|
||||||
|
type Error = A::Error;
|
||||||
|
type Future = AndThenServiceResponseRC<A,B>;
|
||||||
|
|
||||||
|
fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||||
|
Poll::Ready(Ok(()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn call(&mut self, req: A::Request) -> Self::Future {
|
||||||
|
let fut = self.0.borrow_mut().0.call(req);
|
||||||
|
AndThenServiceResponseRC {
|
||||||
|
state: StateRC::A(fut, Some(self.0.clone()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pin_project::pin_project]
|
||||||
|
pub(crate) struct AndThenServiceResponseRC<A, B>
|
||||||
|
where
|
||||||
|
A: Service,
|
||||||
|
B: Service<Request = A::Response, Error = A::Error>,
|
||||||
|
{
|
||||||
|
#[pin]
|
||||||
|
state: StateRC<A, B>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pin_project::pin_project]
|
||||||
|
enum StateRC<A, B>
|
||||||
|
where
|
||||||
|
A: Service,
|
||||||
|
B: Service<Request = A::Response, Error = A::Error>,
|
||||||
|
{
|
||||||
|
A(#[pin] A::Future, Option<Rc<RefCell<(A, B)>>>),
|
||||||
|
B(#[pin] B::Future),
|
||||||
|
Empty,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<A, B> Future for AndThenServiceResponseRC<A, B>
|
||||||
|
where
|
||||||
|
A: Service,
|
||||||
|
B: Service<Request = A::Response, Error = A::Error>,
|
||||||
|
{
|
||||||
|
type Output = Result<B::Response, A::Error>;
|
||||||
|
|
||||||
|
#[pin_project::project]
|
||||||
|
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||||
|
let mut this = self.as_mut().project();
|
||||||
|
|
||||||
|
#[project]
|
||||||
|
match this.state.as_mut().project() {
|
||||||
|
StateRC::A(fut, b) => match fut.poll(cx)? {
|
||||||
|
Poll::Ready(res) => {
|
||||||
|
let b = b.take().unwrap();
|
||||||
|
this.state.set(StateRC::Empty); // drop fut A
|
||||||
|
let fut = b.borrow_mut().1.call(res);
|
||||||
|
this.state.set(StateRC::B(fut));
|
||||||
|
self.poll(cx)
|
||||||
|
}
|
||||||
|
Poll::Pending => Poll::Pending,
|
||||||
|
},
|
||||||
|
StateRC::B(fut) => fut.poll(cx).map(|r| {
|
||||||
|
this.state.set(StateRC::Empty);
|
||||||
|
r
|
||||||
|
}),
|
||||||
|
StateRC::Empty => panic!("future must not be polled after it returned `Poll::Ready`"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
* AndThenRCFuture - AndThen service based on RefCell
|
||||||
|
* and standard futures::future::and_then combinator in a Box
|
||||||
|
*/
|
||||||
|
|
||||||
|
struct AndThenRCFuture<A,B>(Rc<RefCell<(A, B)>>);
|
||||||
|
|
||||||
|
impl<A,B> AndThenRCFuture<A,B> {
|
||||||
|
fn new(a: A, b: B) -> Self
|
||||||
|
where
|
||||||
|
A: Service,
|
||||||
|
B: Service<Request = A::Response, Error = A::Error>,
|
||||||
|
{
|
||||||
|
Self(Rc::new(RefCell::new((a,b))))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<A,B> Clone for AndThenRCFuture<A,B> {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
Self(self.0.clone())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<A,B> Service for AndThenRCFuture<A,B>
|
||||||
|
where
|
||||||
|
A: Service + 'static,
|
||||||
|
A::Future: 'static,
|
||||||
|
B: Service<Request = A::Response, Error = A::Error> + 'static,
|
||||||
|
B::Future: 'static
|
||||||
|
{
|
||||||
|
type Request = A::Request;
|
||||||
|
type Response = B::Response;
|
||||||
|
type Error = A::Error;
|
||||||
|
type Future = BoxFuture<Self::Response, Self::Error>;
|
||||||
|
|
||||||
|
fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||||
|
Poll::Ready(Ok(()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn call(&mut self, req: A::Request) -> Self::Future {
|
||||||
|
let fut = self.0.borrow_mut().0.call(req);
|
||||||
|
let core = self.0.clone();
|
||||||
|
let fut2 = move |res| (*core).borrow_mut().1.call(res);
|
||||||
|
Box::pin(
|
||||||
|
fut.and_then(fut2)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// Criterion Benchmark for async Service
|
||||||
|
/// Should be used from within criterion group:
|
||||||
|
/// ```rust,ignore
|
||||||
|
/// let mut criterion: ::criterion::Criterion<_> =
|
||||||
|
/// ::criterion::Criterion::default().configure_from_args();
|
||||||
|
/// bench_async_service(&mut criterion, ok_service(), "async_service_direct");
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// Usable for benching Service wrappers:
|
||||||
|
/// Using minimum service code implementation we first measure
|
||||||
|
/// time to run minimum service, then measure time with wrapper.
|
||||||
|
///
|
||||||
|
/// Sample output
|
||||||
|
/// async_service_direct time: [1.0908 us 1.1656 us 1.2613 us]
|
||||||
|
pub fn bench_async_service<S>(c: &mut Criterion, srv: S, name: &str)
|
||||||
|
where
|
||||||
|
S: Service<Request = (), Response = usize, Error = ()> + Clone + 'static,
|
||||||
|
{
|
||||||
|
let mut rt = actix_rt::System::new("test");
|
||||||
|
|
||||||
|
// start benchmark loops
|
||||||
|
c.bench_function(name, move |b| {
|
||||||
|
b.iter_custom(|iters| {
|
||||||
|
let mut srvs: Vec<_> = (1..iters).map(|_| srv.clone()).collect();
|
||||||
|
// exclude request generation, it appears it takes significant time vs call (3us vs 1us)
|
||||||
|
let start = std::time::Instant::now();
|
||||||
|
// benchmark body
|
||||||
|
rt.block_on(async move {
|
||||||
|
join_all(srvs.iter_mut().map(|srv| srv.call(()))).await
|
||||||
|
});
|
||||||
|
let elapsed = start.elapsed();
|
||||||
|
// check that at least first request succeeded
|
||||||
|
elapsed
|
||||||
|
})
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
pub fn service_benches() {
|
||||||
|
let mut criterion: ::criterion::Criterion<_> =
|
||||||
|
::criterion::Criterion::default().configure_from_args();
|
||||||
|
bench_async_service(&mut criterion, AndThenUC::new(svc1.into_service(), svc2.into_service()), "AndThen with UnsafeCell");
|
||||||
|
bench_async_service(&mut criterion, AndThenRC::new(svc1.into_service(), svc2.into_service()), "AndThen with RefCell");
|
||||||
|
bench_async_service(&mut criterion, AndThenUC::new(svc1.into_service(), svc2.into_service()), "AndThen with UnsafeCell");
|
||||||
|
bench_async_service(&mut criterion, AndThenRC::new(svc1.into_service(), svc2.into_service()), "AndThen with RefCell");
|
||||||
|
bench_async_service(&mut criterion, AndThenRCFuture::new(svc1.into_service(), svc2.into_service()), "AndThen with RefCell via future::and_then");
|
||||||
|
}
|
||||||
|
|
||||||
|
criterion_main!(service_benches);
|
117
actix-service/benches/unsafecell_vs_refcell.rs
Normal file
117
actix-service/benches/unsafecell_vs_refcell.rs
Normal file
@@ -0,0 +1,117 @@
|
|||||||
|
use criterion::{criterion_main, Criterion};
|
||||||
|
use futures_util::future::join_all;
|
||||||
|
use std::cell::{RefCell, UnsafeCell};
|
||||||
|
use std::task::{Context, Poll};
|
||||||
|
use std::rc::Rc;
|
||||||
|
use actix_service::{Service};
|
||||||
|
use futures_util::future::{ok, Ready};
|
||||||
|
|
||||||
|
struct SrvUC(Rc<UnsafeCell<usize>>);
|
||||||
|
|
||||||
|
impl Default for SrvUC {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self(Rc::new(UnsafeCell::new(0)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Clone for SrvUC {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
Self(self.0.clone())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Service for SrvUC {
|
||||||
|
type Request = ();
|
||||||
|
type Response = usize;
|
||||||
|
type Error = ();
|
||||||
|
type Future = Ready<Result<Self::Response, ()>>;
|
||||||
|
|
||||||
|
fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||||
|
Poll::Ready(Ok(()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn call(&mut self, _: ()) -> Self::Future {
|
||||||
|
unsafe { *(*self.0).get() = *(*self.0).get() + 1 };
|
||||||
|
ok(unsafe { *self.0.get() })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct SrvRC(Rc<RefCell<usize>>);
|
||||||
|
|
||||||
|
impl Default for SrvRC {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self(Rc::new(RefCell::new(0)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Clone for SrvRC {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
Self(self.0.clone())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Service for SrvRC {
|
||||||
|
type Request = ();
|
||||||
|
type Response = usize;
|
||||||
|
type Error = ();
|
||||||
|
type Future = Ready<Result<Self::Response, ()>>;
|
||||||
|
|
||||||
|
fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||||
|
Poll::Ready(Ok(()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn call(&mut self, _: ()) -> Self::Future {
|
||||||
|
let prev = *self.0.borrow();
|
||||||
|
*(*self.0).borrow_mut() = prev + 1;
|
||||||
|
ok(*self.0.borrow())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// Criterion Benchmark for async Service
|
||||||
|
/// Should be used from within criterion group:
|
||||||
|
/// ```rust,ignore
|
||||||
|
/// let mut criterion: ::criterion::Criterion<_> =
|
||||||
|
/// ::criterion::Criterion::default().configure_from_args();
|
||||||
|
/// bench_async_service(&mut criterion, ok_service(), "async_service_direct");
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// Usable for benching Service wrappers:
|
||||||
|
/// Using minimum service code implementation we first measure
|
||||||
|
/// time to run minimum service, then measure time with wrapper.
|
||||||
|
///
|
||||||
|
/// Sample output
|
||||||
|
/// async_service_direct time: [1.0908 us 1.1656 us 1.2613 us]
|
||||||
|
pub fn bench_async_service<S>(c: &mut Criterion, srv: S, name: &str)
|
||||||
|
where
|
||||||
|
S: Service<Request = (), Response = usize, Error = ()> + Clone + 'static,
|
||||||
|
{
|
||||||
|
let mut rt = actix_rt::System::new("test");
|
||||||
|
|
||||||
|
// start benchmark loops
|
||||||
|
c.bench_function(name, move |b| {
|
||||||
|
b.iter_custom(|iters| {
|
||||||
|
let mut srvs: Vec<_> = (1..iters).map(|_| srv.clone()).collect();
|
||||||
|
// exclude request generation, it appears it takes significant time vs call (3us vs 1us)
|
||||||
|
let start = std::time::Instant::now();
|
||||||
|
// benchmark body
|
||||||
|
rt.block_on(async move {
|
||||||
|
join_all(srvs.iter_mut().map(|srv| srv.call(()))).await
|
||||||
|
});
|
||||||
|
let elapsed = start.elapsed();
|
||||||
|
// check that at least first request succeeded
|
||||||
|
elapsed
|
||||||
|
})
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
pub fn service_benches() {
|
||||||
|
let mut criterion: ::criterion::Criterion<_> =
|
||||||
|
::criterion::Criterion::default().configure_from_args();
|
||||||
|
bench_async_service(&mut criterion, SrvUC::default(), "Service with UnsafeCell");
|
||||||
|
bench_async_service(&mut criterion, SrvRC::default(), "Service with RefCell");
|
||||||
|
bench_async_service(&mut criterion, SrvUC::default(), "Service with UnsafeCell");
|
||||||
|
bench_async_service(&mut criterion, SrvRC::default(), "Service with RefCell");
|
||||||
|
}
|
||||||
|
criterion_main!(service_benches);
|
@@ -1,5 +1,6 @@
|
|||||||
use std::future::Future;
|
use std::future::Future;
|
||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
|
use std::rc::Rc;
|
||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
use super::{Service, ServiceFactory};
|
use super::{Service, ServiceFactory};
|
||||||
@@ -9,7 +10,7 @@ use crate::cell::Cell;
|
|||||||
/// of another service which completes successfully.
|
/// of another service which completes successfully.
|
||||||
///
|
///
|
||||||
/// This is created by the `ServiceExt::and_then` method.
|
/// This is created by the `ServiceExt::and_then` method.
|
||||||
pub struct AndThenService<A, B>(Cell<(A, B)>);
|
pub(crate) struct AndThenService<A, B>(Cell<(A, B)>);
|
||||||
|
|
||||||
impl<A, B> AndThenService<A, B> {
|
impl<A, B> AndThenService<A, B> {
|
||||||
/// Create new `AndThen` combinator
|
/// Create new `AndThen` combinator
|
||||||
@@ -40,7 +41,6 @@ where
|
|||||||
|
|
||||||
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||||
let srv = self.0.get_mut();
|
let srv = self.0.get_mut();
|
||||||
|
|
||||||
let not_ready = !srv.0.poll_ready(cx)?.is_ready();
|
let not_ready = !srv.0.poll_ready(cx)?.is_ready();
|
||||||
if !srv.1.poll_ready(cx)?.is_ready() || not_ready {
|
if !srv.1.poll_ready(cx)?.is_ready() || not_ready {
|
||||||
Poll::Pending
|
Poll::Pending
|
||||||
@@ -57,7 +57,7 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[pin_project::pin_project]
|
#[pin_project::pin_project]
|
||||||
pub struct AndThenServiceResponse<A, B>
|
pub(crate) struct AndThenServiceResponse<A, B>
|
||||||
where
|
where
|
||||||
A: Service,
|
A: Service,
|
||||||
B: Service<Request = A::Response, Error = A::Error>,
|
B: Service<Request = A::Response, Error = A::Error>,
|
||||||
@@ -110,7 +110,7 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// `.and_then()` service factory combinator
|
/// `.and_then()` service factory combinator
|
||||||
pub struct AndThenServiceFactory<A, B>
|
pub(crate) struct AndThenServiceFactory<A, B>
|
||||||
where
|
where
|
||||||
A: ServiceFactory,
|
A: ServiceFactory,
|
||||||
A::Config: Clone,
|
A::Config: Clone,
|
||||||
@@ -121,8 +121,7 @@ where
|
|||||||
InitError = A::InitError,
|
InitError = A::InitError,
|
||||||
>,
|
>,
|
||||||
{
|
{
|
||||||
a: A,
|
inner: Rc<(A, B)>,
|
||||||
b: B,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, B> AndThenServiceFactory<A, B>
|
impl<A, B> AndThenServiceFactory<A, B>
|
||||||
@@ -138,7 +137,9 @@ where
|
|||||||
{
|
{
|
||||||
/// Create new `AndThenFactory` combinator
|
/// Create new `AndThenFactory` combinator
|
||||||
pub(crate) fn new(a: A, b: B) -> Self {
|
pub(crate) fn new(a: A, b: B) -> Self {
|
||||||
Self { a, b }
|
Self {
|
||||||
|
inner: Rc::new((a, b)),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -163,34 +164,34 @@ where
|
|||||||
type Future = AndThenServiceFactoryResponse<A, B>;
|
type Future = AndThenServiceFactoryResponse<A, B>;
|
||||||
|
|
||||||
fn new_service(&self, cfg: A::Config) -> Self::Future {
|
fn new_service(&self, cfg: A::Config) -> Self::Future {
|
||||||
|
let inner = &*self.inner;
|
||||||
AndThenServiceFactoryResponse::new(
|
AndThenServiceFactoryResponse::new(
|
||||||
self.a.new_service(cfg.clone()),
|
inner.0.new_service(cfg.clone()),
|
||||||
self.b.new_service(cfg),
|
inner.1.new_service(cfg),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, B> Clone for AndThenServiceFactory<A, B>
|
impl<A, B> Clone for AndThenServiceFactory<A, B>
|
||||||
where
|
where
|
||||||
A: ServiceFactory + Clone,
|
A: ServiceFactory,
|
||||||
A::Config: Clone,
|
A::Config: Clone,
|
||||||
B: ServiceFactory<
|
B: ServiceFactory<
|
||||||
Config = A::Config,
|
Config = A::Config,
|
||||||
Request = A::Response,
|
Request = A::Response,
|
||||||
Error = A::Error,
|
Error = A::Error,
|
||||||
InitError = A::InitError,
|
InitError = A::InitError,
|
||||||
> + Clone,
|
>,
|
||||||
{
|
{
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
Self {
|
Self {
|
||||||
a: self.a.clone(),
|
inner: self.inner.clone(),
|
||||||
b: self.b.clone(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[pin_project::pin_project]
|
#[pin_project::pin_project]
|
||||||
pub struct AndThenServiceFactoryResponse<A, B>
|
pub(crate) struct AndThenServiceFactoryResponse<A, B>
|
||||||
where
|
where
|
||||||
A: ServiceFactory,
|
A: ServiceFactory,
|
||||||
B: ServiceFactory<Request = A::Response>,
|
B: ServiceFactory<Request = A::Response>,
|
||||||
@@ -258,7 +259,7 @@ mod tests {
|
|||||||
|
|
||||||
use futures_util::future::{lazy, ok, ready, Ready};
|
use futures_util::future::{lazy, ok, ready, Ready};
|
||||||
|
|
||||||
use crate::{factory_fn, pipeline, pipeline_factory, Service, ServiceFactory};
|
use crate::{fn_factory, pipeline, pipeline_factory, Service, ServiceFactory};
|
||||||
|
|
||||||
struct Srv1(Rc<Cell<usize>>);
|
struct Srv1(Rc<Cell<usize>>);
|
||||||
|
|
||||||
@@ -312,7 +313,7 @@ mod tests {
|
|||||||
let mut srv = pipeline(Srv1(cnt.clone())).and_then(Srv2(cnt));
|
let mut srv = pipeline(Srv1(cnt.clone())).and_then(Srv2(cnt));
|
||||||
let res = srv.call("srv1").await;
|
let res = srv.call("srv1").await;
|
||||||
assert!(res.is_ok());
|
assert!(res.is_ok());
|
||||||
assert_eq!(res.unwrap(), (("srv1", "srv2")));
|
assert_eq!(res.unwrap(), ("srv1", "srv2"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
@@ -320,7 +321,7 @@ mod tests {
|
|||||||
let cnt = Rc::new(Cell::new(0));
|
let cnt = Rc::new(Cell::new(0));
|
||||||
let cnt2 = cnt.clone();
|
let cnt2 = cnt.clone();
|
||||||
let new_srv =
|
let new_srv =
|
||||||
pipeline_factory(factory_fn(move || ready(Ok::<_, ()>(Srv1(cnt2.clone())))))
|
pipeline_factory(fn_factory(move || ready(Ok::<_, ()>(Srv1(cnt2.clone())))))
|
||||||
.and_then(move || ready(Ok(Srv2(cnt.clone()))));
|
.and_then(move || ready(Ok(Srv2(cnt.clone()))));
|
||||||
|
|
||||||
let mut srv = new_srv.new_service(()).await.unwrap();
|
let mut srv = new_srv.new_service(()).await.unwrap();
|
||||||
|
@@ -1,13 +1,14 @@
|
|||||||
use std::future::Future;
|
use std::future::Future;
|
||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
|
use std::rc::Rc;
|
||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
use crate::cell::Cell;
|
use crate::cell::Cell;
|
||||||
use crate::{Service, ServiceFactory};
|
use crate::{Service, ServiceFactory};
|
||||||
|
|
||||||
/// `Apply` service combinator
|
/// `Apply` service combinator
|
||||||
pub struct AndThenApplyFn<A, B, F, Fut, Res, Err>
|
pub(crate) struct AndThenApplyFn<A, B, F, Fut, Res, Err>
|
||||||
where
|
where
|
||||||
A: Service,
|
A: Service,
|
||||||
B: Service,
|
B: Service,
|
||||||
@@ -15,8 +16,7 @@ where
|
|||||||
Fut: Future<Output = Result<Res, Err>>,
|
Fut: Future<Output = Result<Res, Err>>,
|
||||||
Err: From<A::Error> + From<B::Error>,
|
Err: From<A::Error> + From<B::Error>,
|
||||||
{
|
{
|
||||||
a: A,
|
srv: Cell<(A, B, F)>,
|
||||||
b: Cell<(B, F)>,
|
|
||||||
r: PhantomData<(Fut, Res, Err)>,
|
r: PhantomData<(Fut, Res, Err)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -31,8 +31,7 @@ where
|
|||||||
/// Create new `Apply` combinator
|
/// Create new `Apply` combinator
|
||||||
pub(crate) fn new(a: A, b: B, f: F) -> Self {
|
pub(crate) fn new(a: A, b: B, f: F) -> Self {
|
||||||
Self {
|
Self {
|
||||||
a,
|
srv: Cell::new((a, b, f)),
|
||||||
b: Cell::new((b, f)),
|
|
||||||
r: PhantomData,
|
r: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -40,7 +39,7 @@ where
|
|||||||
|
|
||||||
impl<A, B, F, Fut, Res, Err> Clone for AndThenApplyFn<A, B, F, Fut, Res, Err>
|
impl<A, B, F, Fut, Res, Err> Clone for AndThenApplyFn<A, B, F, Fut, Res, Err>
|
||||||
where
|
where
|
||||||
A: Service + Clone,
|
A: Service,
|
||||||
B: Service,
|
B: Service,
|
||||||
F: FnMut(A::Response, &mut B) -> Fut,
|
F: FnMut(A::Response, &mut B) -> Fut,
|
||||||
Fut: Future<Output = Result<Res, Err>>,
|
Fut: Future<Output = Result<Res, Err>>,
|
||||||
@@ -48,8 +47,7 @@ where
|
|||||||
{
|
{
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
AndThenApplyFn {
|
AndThenApplyFn {
|
||||||
a: self.a.clone(),
|
srv: self.srv.clone(),
|
||||||
b: self.b.clone(),
|
|
||||||
r: PhantomData,
|
r: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -69,8 +67,9 @@ where
|
|||||||
type Future = AndThenApplyFnFuture<A, B, F, Fut, Res, Err>;
|
type Future = AndThenApplyFnFuture<A, B, F, Fut, Res, Err>;
|
||||||
|
|
||||||
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||||
let not_ready = self.a.poll_ready(cx)?.is_pending();
|
let inner = self.srv.get_mut();
|
||||||
if self.b.get_mut().0.poll_ready(cx)?.is_pending() || not_ready {
|
let not_ready = inner.0.poll_ready(cx)?.is_pending();
|
||||||
|
if inner.1.poll_ready(cx)?.is_pending() || not_ready {
|
||||||
Poll::Pending
|
Poll::Pending
|
||||||
} else {
|
} else {
|
||||||
Poll::Ready(Ok(()))
|
Poll::Ready(Ok(()))
|
||||||
@@ -78,14 +77,15 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: A::Request) -> Self::Future {
|
fn call(&mut self, req: A::Request) -> Self::Future {
|
||||||
|
let fut = self.srv.get_mut().0.call(req);
|
||||||
AndThenApplyFnFuture {
|
AndThenApplyFnFuture {
|
||||||
state: State::A(self.a.call(req), Some(self.b.clone())),
|
state: State::A(fut, Some(self.srv.clone())),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[pin_project::pin_project]
|
#[pin_project::pin_project]
|
||||||
pub struct AndThenApplyFnFuture<A, B, F, Fut, Res, Err>
|
pub(crate) struct AndThenApplyFnFuture<A, B, F, Fut, Res, Err>
|
||||||
where
|
where
|
||||||
A: Service,
|
A: Service,
|
||||||
B: Service,
|
B: Service,
|
||||||
@@ -108,7 +108,7 @@ where
|
|||||||
Err: From<A::Error>,
|
Err: From<A::Error>,
|
||||||
Err: From<B::Error>,
|
Err: From<B::Error>,
|
||||||
{
|
{
|
||||||
A(#[pin] A::Future, Option<Cell<(B, F)>>),
|
A(#[pin] A::Future, Option<Cell<(A, B, F)>>),
|
||||||
B(#[pin] Fut),
|
B(#[pin] Fut),
|
||||||
Empty,
|
Empty,
|
||||||
}
|
}
|
||||||
@@ -134,7 +134,7 @@ where
|
|||||||
let mut b = b.take().unwrap();
|
let mut b = b.take().unwrap();
|
||||||
this.state.set(State::Empty);
|
this.state.set(State::Empty);
|
||||||
let b = b.get_mut();
|
let b = b.get_mut();
|
||||||
let fut = (&mut b.1)(res, &mut b.0);
|
let fut = (&mut b.2)(res, &mut b.1);
|
||||||
this.state.set(State::B(fut));
|
this.state.set(State::B(fut));
|
||||||
self.poll(cx)
|
self.poll(cx)
|
||||||
}
|
}
|
||||||
@@ -150,10 +150,8 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// `AndThenApplyFn` service factory
|
/// `AndThenApplyFn` service factory
|
||||||
pub struct AndThenApplyFnFactory<A, B, F, Fut, Res, Err> {
|
pub(crate) struct AndThenApplyFnFactory<A, B, F, Fut, Res, Err> {
|
||||||
a: A,
|
srv: Rc<(A, B, F)>,
|
||||||
b: B,
|
|
||||||
f: F,
|
|
||||||
r: PhantomData<(Fut, Res, Err)>,
|
r: PhantomData<(Fut, Res, Err)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -168,25 +166,16 @@ where
|
|||||||
/// Create new `ApplyNewService` new service instance
|
/// Create new `ApplyNewService` new service instance
|
||||||
pub(crate) fn new(a: A, b: B, f: F) -> Self {
|
pub(crate) fn new(a: A, b: B, f: F) -> Self {
|
||||||
Self {
|
Self {
|
||||||
a: a,
|
srv: Rc::new((a, b, f)),
|
||||||
b: b,
|
|
||||||
f: f,
|
|
||||||
r: PhantomData,
|
r: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, B, F, Fut, Res, Err> Clone for AndThenApplyFnFactory<A, B, F, Fut, Res, Err>
|
impl<A, B, F, Fut, Res, Err> Clone for AndThenApplyFnFactory<A, B, F, Fut, Res, Err> {
|
||||||
where
|
|
||||||
A: Clone,
|
|
||||||
B: Clone,
|
|
||||||
F: Clone,
|
|
||||||
{
|
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
Self {
|
Self {
|
||||||
a: self.a.clone(),
|
srv: self.srv.clone(),
|
||||||
b: self.b.clone(),
|
|
||||||
f: self.f.clone(),
|
|
||||||
r: PhantomData,
|
r: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -210,18 +199,19 @@ where
|
|||||||
type Future = AndThenApplyFnFactoryResponse<A, B, F, Fut, Res, Err>;
|
type Future = AndThenApplyFnFactoryResponse<A, B, F, Fut, Res, Err>;
|
||||||
|
|
||||||
fn new_service(&self, cfg: A::Config) -> Self::Future {
|
fn new_service(&self, cfg: A::Config) -> Self::Future {
|
||||||
|
let srv = &*self.srv;
|
||||||
AndThenApplyFnFactoryResponse {
|
AndThenApplyFnFactoryResponse {
|
||||||
a: None,
|
a: None,
|
||||||
b: None,
|
b: None,
|
||||||
f: self.f.clone(),
|
f: srv.2.clone(),
|
||||||
fut_a: self.a.new_service(cfg.clone()),
|
fut_a: srv.0.new_service(cfg.clone()),
|
||||||
fut_b: self.b.new_service(cfg),
|
fut_b: srv.1.new_service(cfg),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[pin_project::pin_project]
|
#[pin_project::pin_project]
|
||||||
pub struct AndThenApplyFnFactoryResponse<A, B, F, Fut, Res, Err>
|
pub(crate) struct AndThenApplyFnFactoryResponse<A, B, F, Fut, Res, Err>
|
||||||
where
|
where
|
||||||
A: ServiceFactory,
|
A: ServiceFactory,
|
||||||
B: ServiceFactory<Config = A::Config, InitError = A::InitError>,
|
B: ServiceFactory<Config = A::Config, InitError = A::InitError>,
|
||||||
@@ -267,8 +257,11 @@ where
|
|||||||
|
|
||||||
if this.a.is_some() && this.b.is_some() {
|
if this.a.is_some() && this.b.is_some() {
|
||||||
Poll::Ready(Ok(AndThenApplyFn {
|
Poll::Ready(Ok(AndThenApplyFn {
|
||||||
a: this.a.take().unwrap(),
|
srv: Cell::new((
|
||||||
b: Cell::new((this.b.take().unwrap(), this.f.clone())),
|
this.a.take().unwrap(),
|
||||||
|
this.b.take().unwrap(),
|
||||||
|
this.f.clone(),
|
||||||
|
)),
|
||||||
r: PhantomData,
|
r: PhantomData,
|
||||||
}))
|
}))
|
||||||
} else {
|
} else {
|
||||||
@@ -283,7 +276,7 @@ mod tests {
|
|||||||
|
|
||||||
use futures_util::future::{lazy, ok, Ready, TryFutureExt};
|
use futures_util::future::{lazy, ok, Ready, TryFutureExt};
|
||||||
|
|
||||||
use crate::{pipeline, pipeline_factory, service_fn2, Service, ServiceFactory};
|
use crate::{fn_service, pipeline, pipeline_factory, Service, ServiceFactory};
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
struct Srv;
|
struct Srv;
|
||||||
@@ -297,6 +290,7 @@ mod tests {
|
|||||||
Poll::Ready(Ok(()))
|
Poll::Ready(Ok(()))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::unit_arg)]
|
||||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
fn call(&mut self, req: Self::Request) -> Self::Future {
|
||||||
ok(req)
|
ok(req)
|
||||||
}
|
}
|
||||||
@@ -304,7 +298,7 @@ mod tests {
|
|||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_service() {
|
async fn test_service() {
|
||||||
let mut srv = pipeline(|r: &'static str| ok(r))
|
let mut srv = pipeline(ok)
|
||||||
.and_then_apply_fn(Srv, |req: &'static str, s| {
|
.and_then_apply_fn(Srv, |req: &'static str, s| {
|
||||||
s.call(()).map_ok(move |res| (req, res))
|
s.call(()).map_ok(move |res| (req, res))
|
||||||
});
|
});
|
||||||
@@ -318,7 +312,7 @@ mod tests {
|
|||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_service_factory() {
|
async fn test_service_factory() {
|
||||||
let new_srv = pipeline_factory(|| ok::<_, ()>(service_fn2(|r: &'static str| ok(r))))
|
let new_srv = pipeline_factory(|| ok::<_, ()>(fn_service(ok)))
|
||||||
.and_then_apply_fn(
|
.and_then_apply_fn(
|
||||||
|| ok(Srv),
|
|| ok(Srv),
|
||||||
|req: &'static str, s| s.call(()).map_ok(move |res| (req, res)),
|
|req: &'static str, s| s.call(()).map_ok(move |res| (req, res)),
|
||||||
|
@@ -5,7 +5,7 @@ use std::task::{Context, Poll};
|
|||||||
|
|
||||||
use super::{IntoService, IntoServiceFactory, Service, ServiceFactory};
|
use super::{IntoService, IntoServiceFactory, Service, ServiceFactory};
|
||||||
|
|
||||||
/// Apply tranform function to a service
|
/// Apply tranform function to a service.
|
||||||
pub fn apply_fn<T, F, R, In, Out, Err, U>(service: U, f: F) -> Apply<T, F, R, In, Out, Err>
|
pub fn apply_fn<T, F, R, In, Out, Err, U>(service: U, f: F) -> Apply<T, F, R, In, Out, Err>
|
||||||
where
|
where
|
||||||
T: Service<Error = Err>,
|
T: Service<Error = Err>,
|
||||||
@@ -16,7 +16,7 @@ where
|
|||||||
Apply::new(service.into_service(), f)
|
Apply::new(service.into_service(), f)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create factory for `apply` service.
|
/// Service factory that prodices `apply_fn` service.
|
||||||
pub fn apply_fn_factory<T, F, R, In, Out, Err, U>(
|
pub fn apply_fn_factory<T, F, R, In, Out, Err, U>(
|
||||||
service: U,
|
service: U,
|
||||||
f: F,
|
f: F,
|
||||||
@@ -56,6 +56,21 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<T, F, R, In, Out, Err> Clone for Apply<T, F, R, In, Out, Err>
|
||||||
|
where
|
||||||
|
T: Service<Error = Err> + Clone,
|
||||||
|
F: FnMut(In, &mut T) -> R + Clone,
|
||||||
|
R: Future<Output = Result<Out, Err>>,
|
||||||
|
{
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
Apply {
|
||||||
|
service: self.service.clone(),
|
||||||
|
f: self.f.clone(),
|
||||||
|
r: PhantomData,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl<T, F, R, In, Out, Err> Service for Apply<T, F, R, In, Out, Err>
|
impl<T, F, R, In, Out, Err> Service for Apply<T, F, R, In, Out, Err>
|
||||||
where
|
where
|
||||||
T: Service<Error = Err>,
|
T: Service<Error = Err>,
|
||||||
@@ -218,8 +233,8 @@ mod tests {
|
|||||||
let mut srv = pipeline(apply_fn(Srv, |req: &'static str, srv| {
|
let mut srv = pipeline(apply_fn(Srv, |req: &'static str, srv| {
|
||||||
let fut = srv.call(());
|
let fut = srv.call(());
|
||||||
async move {
|
async move {
|
||||||
let res = fut.await.unwrap();
|
fut.await.unwrap();
|
||||||
Ok((req, res))
|
Ok((req, ()))
|
||||||
}
|
}
|
||||||
}));
|
}));
|
||||||
|
|
||||||
@@ -227,7 +242,7 @@ mod tests {
|
|||||||
|
|
||||||
let res = srv.call("srv").await;
|
let res = srv.call("srv").await;
|
||||||
assert!(res.is_ok());
|
assert!(res.is_ok());
|
||||||
assert_eq!(res.unwrap(), (("srv", ())));
|
assert_eq!(res.unwrap(), ("srv", ()));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
@@ -237,8 +252,8 @@ mod tests {
|
|||||||
|req: &'static str, srv| {
|
|req: &'static str, srv| {
|
||||||
let fut = srv.call(());
|
let fut = srv.call(());
|
||||||
async move {
|
async move {
|
||||||
let res = fut.await.unwrap();
|
fut.await.unwrap();
|
||||||
Ok((req, res))
|
Ok((req, ()))
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
));
|
));
|
||||||
@@ -249,6 +264,6 @@ mod tests {
|
|||||||
|
|
||||||
let res = srv.call("srv").await;
|
let res = srv.call("srv").await;
|
||||||
assert!(res.is_ok());
|
assert!(res.is_ok());
|
||||||
assert_eq!(res.unwrap(), (("srv", ())));
|
assert_eq!(res.unwrap(), ("srv", ()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -6,8 +6,19 @@ use std::task::{Context, Poll};
|
|||||||
use crate::cell::Cell;
|
use crate::cell::Cell;
|
||||||
use crate::{Service, ServiceFactory};
|
use crate::{Service, ServiceFactory};
|
||||||
|
|
||||||
/// Convert `Fn(&Config, &mut Service) -> Future<Service>` fn to a NewService
|
/// Convert `Fn(Config, &mut Service1) -> Future<Service2>` fn to a service factory
|
||||||
pub fn apply_cfg<F, C, T, R, S, E>(srv: T, f: F) -> ApplyConfigService<F, C, T, R, S, E>
|
pub fn apply_cfg<F, C, T, R, S, E>(
|
||||||
|
srv: T,
|
||||||
|
f: F,
|
||||||
|
) -> impl ServiceFactory<
|
||||||
|
Config = C,
|
||||||
|
Request = S::Request,
|
||||||
|
Response = S::Response,
|
||||||
|
Error = S::Error,
|
||||||
|
Service = S,
|
||||||
|
InitError = E,
|
||||||
|
Future = R,
|
||||||
|
> + Clone
|
||||||
where
|
where
|
||||||
F: FnMut(C, &mut T) -> R,
|
F: FnMut(C, &mut T) -> R,
|
||||||
T: Service,
|
T: Service,
|
||||||
@@ -20,12 +31,20 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Convert `Fn(&Config, &mut Service) -> Future<Service>` fn to a NewService
|
/// Convert `Fn(Config, &mut Service1) -> Future<Service2>` fn to a service factory
|
||||||
/// Service get constructor from NewService.
|
///
|
||||||
|
/// Service1 get constructed from `T` factory.
|
||||||
pub fn apply_cfg_factory<F, C, T, R, S>(
|
pub fn apply_cfg_factory<F, C, T, R, S>(
|
||||||
srv: T,
|
factory: T,
|
||||||
f: F,
|
f: F,
|
||||||
) -> ApplyConfigServiceFactory<F, C, T, R, S>
|
) -> impl ServiceFactory<
|
||||||
|
Config = C,
|
||||||
|
Request = S::Request,
|
||||||
|
Response = S::Response,
|
||||||
|
Error = S::Error,
|
||||||
|
Service = S,
|
||||||
|
InitError = T::InitError,
|
||||||
|
> + Clone
|
||||||
where
|
where
|
||||||
F: FnMut(C, &mut T::Service) -> R,
|
F: FnMut(C, &mut T::Service) -> R,
|
||||||
T: ServiceFactory<Config = ()>,
|
T: ServiceFactory<Config = ()>,
|
||||||
@@ -34,13 +53,13 @@ where
|
|||||||
S: Service,
|
S: Service,
|
||||||
{
|
{
|
||||||
ApplyConfigServiceFactory {
|
ApplyConfigServiceFactory {
|
||||||
srv: Cell::new((srv, f)),
|
srv: Cell::new((factory, f)),
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Convert `Fn(&Config) -> Future<Service>` fn to NewService\
|
/// Convert `Fn(Config, &mut Server) -> Future<Service>` fn to NewService\
|
||||||
pub struct ApplyConfigService<F, C, T, R, S, E>
|
struct ApplyConfigService<F, C, T, R, S, E>
|
||||||
where
|
where
|
||||||
F: FnMut(C, &mut T) -> R,
|
F: FnMut(C, &mut T) -> R,
|
||||||
T: Service,
|
T: Service,
|
||||||
@@ -91,7 +110,7 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Convert `Fn(&Config) -> Future<Service>` fn to NewService
|
/// Convert `Fn(&Config) -> Future<Service>` fn to NewService
|
||||||
pub struct ApplyConfigServiceFactory<F, C, T, R, S>
|
struct ApplyConfigServiceFactory<F, C, T, R, S>
|
||||||
where
|
where
|
||||||
F: FnMut(C, &mut T::Service) -> R,
|
F: FnMut(C, &mut T::Service) -> R,
|
||||||
T: ServiceFactory<Config = ()>,
|
T: ServiceFactory<Config = ()>,
|
||||||
@@ -144,7 +163,7 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[pin_project::pin_project]
|
#[pin_project::pin_project]
|
||||||
pub struct ApplyConfigServiceFactoryResponse<F, C, T, R, S>
|
struct ApplyConfigServiceFactoryResponse<F, C, T, R, S>
|
||||||
where
|
where
|
||||||
F: FnMut(C, &mut T::Service) -> R,
|
F: FnMut(C, &mut T::Service) -> R,
|
||||||
T: ServiceFactory<Config = ()>,
|
T: ServiceFactory<Config = ()>,
|
||||||
|
@@ -13,7 +13,7 @@ pub type BoxService<Req, Res, Err> =
|
|||||||
|
|
||||||
pub struct BoxServiceFactory<C, Req, Res, Err, InitErr>(Inner<C, Req, Res, Err, InitErr>);
|
pub struct BoxServiceFactory<C, Req, Res, Err, InitErr>(Inner<C, Req, Res, Err, InitErr>);
|
||||||
|
|
||||||
/// Create boxed new service
|
/// Create boxed service factory
|
||||||
pub fn factory<T>(
|
pub fn factory<T>(
|
||||||
factory: T,
|
factory: T,
|
||||||
) -> BoxServiceFactory<T::Config, T::Request, T::Response, T::Error, T::InitError>
|
) -> BoxServiceFactory<T::Config, T::Request, T::Response, T::Error, T::InitError>
|
||||||
|
@@ -7,7 +7,7 @@ use futures_util::future::{ok, Ready};
|
|||||||
use crate::{IntoService, IntoServiceFactory, Service, ServiceFactory};
|
use crate::{IntoService, IntoServiceFactory, Service, ServiceFactory};
|
||||||
|
|
||||||
/// Create `ServiceFactory` for function that can act as a `Service`
|
/// Create `ServiceFactory` for function that can act as a `Service`
|
||||||
pub fn service_fn<F, Fut, Req, Res, Err, Cfg>(
|
pub fn fn_service<F, Fut, Req, Res, Err, Cfg>(
|
||||||
f: F,
|
f: F,
|
||||||
) -> FnServiceFactory<F, Fut, Req, Res, Err, Cfg>
|
) -> FnServiceFactory<F, Fut, Req, Res, Err, Cfg>
|
||||||
where
|
where
|
||||||
@@ -17,16 +17,43 @@ where
|
|||||||
FnServiceFactory::new(f)
|
FnServiceFactory::new(f)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn service_fn2<F, Fut, Req, Res, Err>(f: F) -> FnService<F, Fut, Req, Res, Err>
|
|
||||||
where
|
|
||||||
F: FnMut(Req) -> Fut,
|
|
||||||
Fut: Future<Output = Result<Res, Err>>,
|
|
||||||
{
|
|
||||||
FnService::new(f)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Create `ServiceFactory` for function that can produce services
|
/// Create `ServiceFactory` for function that can produce services
|
||||||
pub fn factory_fn<F, Cfg, Srv, Fut, Err>(f: F) -> FnServiceNoConfig<F, Cfg, Srv, Fut, Err>
|
///
|
||||||
|
/// # Example
|
||||||
|
///
|
||||||
|
/// ```rust
|
||||||
|
/// use std::io;
|
||||||
|
/// use actix_service::{fn_factory, fn_service, Service, ServiceFactory};
|
||||||
|
/// use futures_util::future::ok;
|
||||||
|
///
|
||||||
|
/// /// Service that divides two usize values.
|
||||||
|
/// async fn div((x, y): (usize, usize)) -> Result<usize, io::Error> {
|
||||||
|
/// if y == 0 {
|
||||||
|
/// Err(io::Error::new(io::ErrorKind::Other, "divide by zdro"))
|
||||||
|
/// } else {
|
||||||
|
/// Ok(x / y)
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// #[actix_rt::main]
|
||||||
|
/// async fn main() -> io::Result<()> {
|
||||||
|
/// // Create service factory that produces `div` services
|
||||||
|
/// let factory = fn_factory(|| {
|
||||||
|
/// ok::<_, io::Error>(fn_service(div))
|
||||||
|
/// });
|
||||||
|
///
|
||||||
|
/// // construct new service
|
||||||
|
/// let mut srv = factory.new_service(()).await?;
|
||||||
|
///
|
||||||
|
/// // now we can use `div` service
|
||||||
|
/// let result = srv.call((10, 20)).await?;
|
||||||
|
///
|
||||||
|
/// println!("10 / 20 = {}", result);
|
||||||
|
///
|
||||||
|
/// Ok(())
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
pub fn fn_factory<F, Cfg, Srv, Fut, Err>(f: F) -> FnServiceNoConfig<F, Cfg, Srv, Fut, Err>
|
||||||
where
|
where
|
||||||
Srv: Service,
|
Srv: Service,
|
||||||
F: Fn() -> Fut,
|
F: Fn() -> Fut,
|
||||||
@@ -35,8 +62,39 @@ where
|
|||||||
FnServiceNoConfig::new(f)
|
FnServiceNoConfig::new(f)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create `ServiceFactory` for function that can produce services with configuration
|
/// Create `ServiceFactory` for function that accepts config argument and can produce services
|
||||||
pub fn factory_fn_cfg<F, Fut, Cfg, Srv, Err>(f: F) -> FnServiceConfig<F, Fut, Cfg, Srv, Err>
|
///
|
||||||
|
/// Any function that has following form `Fn(Config) -> Future<Output = Service>` could
|
||||||
|
/// act as a `ServiceFactory`.
|
||||||
|
///
|
||||||
|
/// # Example
|
||||||
|
///
|
||||||
|
/// ```rust
|
||||||
|
/// use std::io;
|
||||||
|
/// use actix_service::{fn_factory_with_config, fn_service, Service, ServiceFactory};
|
||||||
|
/// use futures_util::future::ok;
|
||||||
|
///
|
||||||
|
/// #[actix_rt::main]
|
||||||
|
/// async fn main() -> io::Result<()> {
|
||||||
|
/// // Create service factory. factory uses config argument for
|
||||||
|
/// // services it generates.
|
||||||
|
/// let factory = fn_factory_with_config(|y: usize| {
|
||||||
|
/// ok::<_, io::Error>(fn_service(move |x: usize| ok::<_, io::Error>(x * y)))
|
||||||
|
/// });
|
||||||
|
///
|
||||||
|
/// // construct new service with config argument
|
||||||
|
/// let mut srv = factory.new_service(10).await?;
|
||||||
|
///
|
||||||
|
/// let result = srv.call(10).await?;
|
||||||
|
/// assert_eq!(result, 100);
|
||||||
|
///
|
||||||
|
/// println!("10 * 10 = {}", result);
|
||||||
|
/// Ok(())
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
pub fn fn_factory_with_config<F, Fut, Cfg, Srv, Err>(
|
||||||
|
f: F,
|
||||||
|
) -> FnServiceConfig<F, Fut, Cfg, Srv, Err>
|
||||||
where
|
where
|
||||||
F: Fn(Cfg) -> Fut,
|
F: Fn(Cfg) -> Fut,
|
||||||
Fut: Future<Output = Result<Srv, Err>>,
|
Fut: Future<Output = Result<Srv, Err>>,
|
||||||
@@ -132,6 +190,25 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<F, Fut, Req, Res, Err> Service for FnServiceFactory<F, Fut, Req, Res, Err, ()>
|
||||||
|
where
|
||||||
|
F: FnMut(Req) -> Fut + Clone,
|
||||||
|
Fut: Future<Output = Result<Res, Err>>,
|
||||||
|
{
|
||||||
|
type Request = Req;
|
||||||
|
type Response = Res;
|
||||||
|
type Error = Err;
|
||||||
|
type Future = Fut;
|
||||||
|
|
||||||
|
fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||||
|
Poll::Ready(Ok(()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn call(&mut self, req: Self::Request) -> Self::Future {
|
||||||
|
(self.f)(req)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl<F, Fut, Req, Res, Err, Cfg> ServiceFactory for FnServiceFactory<F, Fut, Req, Res, Err, Cfg>
|
impl<F, Fut, Req, Res, Err, Cfg> ServiceFactory for FnServiceFactory<F, Fut, Req, Res, Err, Cfg>
|
||||||
where
|
where
|
||||||
F: FnMut(Req) -> Fut + Clone,
|
F: FnMut(Req) -> Fut + Clone,
|
||||||
@@ -280,3 +357,47 @@ where
|
|||||||
FnServiceNoConfig::new(self)
|
FnServiceNoConfig::new(self)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use std::task::Poll;
|
||||||
|
|
||||||
|
use futures_util::future::{lazy, ok};
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
use crate::{Service, ServiceFactory};
|
||||||
|
|
||||||
|
#[actix_rt::test]
|
||||||
|
async fn test_fn_service() {
|
||||||
|
let new_srv = fn_service(|()| ok::<_, ()>("srv"));
|
||||||
|
|
||||||
|
let mut srv = new_srv.new_service(()).await.unwrap();
|
||||||
|
let res = srv.call(()).await;
|
||||||
|
assert_eq!(lazy(|cx| srv.poll_ready(cx)).await, Poll::Ready(Ok(())));
|
||||||
|
assert!(res.is_ok());
|
||||||
|
assert_eq!(res.unwrap(), "srv");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix_rt::test]
|
||||||
|
async fn test_fn_service_service() {
|
||||||
|
let mut srv = fn_service(|()| ok::<_, ()>("srv"));
|
||||||
|
|
||||||
|
let res = srv.call(()).await;
|
||||||
|
assert_eq!(lazy(|cx| srv.poll_ready(cx)).await, Poll::Ready(Ok(())));
|
||||||
|
assert!(res.is_ok());
|
||||||
|
assert_eq!(res.unwrap(), "srv");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix_rt::test]
|
||||||
|
async fn test_fn_service_with_config() {
|
||||||
|
let new_srv = fn_factory_with_config(|cfg: usize| {
|
||||||
|
ok::<_, ()>(fn_service(move |()| ok::<_, ()>(("srv", cfg))))
|
||||||
|
});
|
||||||
|
|
||||||
|
let mut srv = new_srv.new_service(1).await.unwrap();
|
||||||
|
let res = srv.call(()).await;
|
||||||
|
assert_eq!(lazy(|cx| srv.poll_ready(cx)).await, Poll::Ready(Ok(())));
|
||||||
|
assert!(res.is_ok());
|
||||||
|
assert_eq!(res.unwrap(), ("srv", 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@@ -25,12 +25,48 @@ 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::fn_service::{factory_fn, factory_fn_cfg, service_fn, service_fn2};
|
pub use self::fn_service::{fn_factory, fn_factory_with_config, fn_service};
|
||||||
pub use self::map_config::{map_config, unit_config};
|
pub use self::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, Transform};
|
pub use self::transform::{apply, Transform};
|
||||||
|
|
||||||
/// An asynchronous function from `Request` to a `Response`.
|
/// An asynchronous function from `Request` to a `Response`.
|
||||||
|
///
|
||||||
|
/// `Service` represents a service that represanting interation, taking requests and giving back
|
||||||
|
/// replies. You can think about service as a function with one argument and result as a return
|
||||||
|
/// type. In general form it looks like `async fn(Req) -> Result<Res, Err>`. `Service`
|
||||||
|
/// trait just generalizing form of this function. Each parameter described as an assotiated type.
|
||||||
|
///
|
||||||
|
/// Services provides a symmetric and uniform API, same abstractions represents
|
||||||
|
/// clients and servers. Services describe only `transforamtion` operation
|
||||||
|
/// which encorouge to simplify api surface and phrases `value transformation`.
|
||||||
|
/// That leads to simplier design of each service. That also allows better testability
|
||||||
|
/// and better composition.
|
||||||
|
///
|
||||||
|
/// Services could be represented in several different forms. In general,
|
||||||
|
/// Service is a type that implements `Service` trait.
|
||||||
|
///
|
||||||
|
/// ```rust,ignore
|
||||||
|
/// struct MyService;
|
||||||
|
///
|
||||||
|
/// impl Service for MyService {
|
||||||
|
/// type Request = u8;
|
||||||
|
/// type Response = u64;
|
||||||
|
/// type Error = MyError;
|
||||||
|
/// type Future = Pin<Box<Future<Output=Result<Self::Response, Self::Error>>>;
|
||||||
|
///
|
||||||
|
/// fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { ... }
|
||||||
|
///
|
||||||
|
/// fn call(&mut self, req: Self::Request) -> Self::Future { ... }
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// Service can have mutable state that influence computation.
|
||||||
|
/// This service could be rewritten as a simple function:
|
||||||
|
///
|
||||||
|
/// ```rust,ignore
|
||||||
|
/// async fn my_service(req: u8) -> Result<u64, MyError>;
|
||||||
|
/// ```
|
||||||
pub trait Service {
|
pub trait Service {
|
||||||
/// Requests handled by the service.
|
/// Requests handled by the service.
|
||||||
type Request;
|
type Request;
|
||||||
@@ -46,13 +82,19 @@ pub trait Service {
|
|||||||
|
|
||||||
/// Returns `Ready` when the service is able to process requests.
|
/// Returns `Ready` when the service is able to process requests.
|
||||||
///
|
///
|
||||||
/// If the service is at capacity, then `NotReady` is returned and the task
|
/// If the service is at capacity, then `Pending` is returned and the task
|
||||||
/// is notified when the service becomes ready again. This function is
|
/// is notified when the service becomes ready again. This function is
|
||||||
/// expected to be called while on a task.
|
/// expected to be called while on a task.
|
||||||
///
|
///
|
||||||
/// This is a **best effort** implementation. False positives are permitted.
|
/// This is a **best effort** implementation. False positives are permitted.
|
||||||
/// It is permitted for the service to return `Ready` from a `poll_ready`
|
/// It is permitted for the service to return `Ready` from a `poll_ready`
|
||||||
/// call and the next invocation of `call` results in an error.
|
/// call and the next invocation of `call` results in an error.
|
||||||
|
///
|
||||||
|
/// There are several notes to consider:
|
||||||
|
///
|
||||||
|
/// 1. `.poll_ready()` might be called on different task from actual service call.
|
||||||
|
///
|
||||||
|
/// 2. In case of chained services, `.poll_ready()` get called for all services at once.
|
||||||
fn poll_ready(&mut self, ctx: &mut task::Context<'_>) -> Poll<Result<(), Self::Error>>;
|
fn poll_ready(&mut self, ctx: &mut task::Context<'_>) -> Poll<Result<(), Self::Error>>;
|
||||||
|
|
||||||
/// Process the request and return the response asynchronously.
|
/// Process the request and return the response asynchronously.
|
||||||
@@ -287,7 +329,7 @@ pub trait IntoServiceFactory<T>
|
|||||||
where
|
where
|
||||||
T: ServiceFactory,
|
T: ServiceFactory,
|
||||||
{
|
{
|
||||||
/// Convert `Self` an `ServiceFactory`
|
/// Convert `Self` to a `ServiceFactory`
|
||||||
fn into_factory(self) -> T;
|
fn into_factory(self) -> T;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -309,11 +351,17 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Convert object of type `T` to a service `S`
|
||||||
|
pub fn into_service<T, S>(tp: T) -> S
|
||||||
|
where
|
||||||
|
S: Service,
|
||||||
|
T: IntoService<S>,
|
||||||
|
{
|
||||||
|
tp.into_service()
|
||||||
|
}
|
||||||
|
|
||||||
pub mod dev {
|
pub mod dev {
|
||||||
pub use crate::and_then::{AndThenService, AndThenServiceFactory};
|
|
||||||
pub use crate::and_then_apply_fn::{AndThenApplyFn, AndThenApplyFnFactory};
|
|
||||||
pub use crate::apply::{Apply, ApplyServiceFactory};
|
pub use crate::apply::{Apply, ApplyServiceFactory};
|
||||||
pub use crate::apply_cfg::{ApplyConfigService, ApplyConfigServiceFactory};
|
|
||||||
pub use crate::fn_service::{
|
pub use crate::fn_service::{
|
||||||
FnService, FnServiceConfig, FnServiceFactory, FnServiceNoConfig,
|
FnService, FnServiceConfig, FnServiceFactory, FnServiceNoConfig,
|
||||||
};
|
};
|
||||||
@@ -321,7 +369,6 @@ pub mod dev {
|
|||||||
pub use crate::map_config::{MapConfig, UnitConfig};
|
pub use crate::map_config::{MapConfig, UnitConfig};
|
||||||
pub use crate::map_err::{MapErr, MapErrServiceFactory};
|
pub use crate::map_err::{MapErr, MapErrServiceFactory};
|
||||||
pub use crate::map_init_err::MapInitErr;
|
pub use crate::map_init_err::MapInitErr;
|
||||||
pub use crate::then::{ThenService, ThenServiceFactory};
|
|
||||||
pub use crate::transform::ApplyTransform;
|
pub use crate::transform::ApplyTransform;
|
||||||
pub use crate::transform_err::TransformMapInitErr;
|
pub use crate::transform_err::TransformMapInitErr;
|
||||||
}
|
}
|
||||||
|
@@ -1,25 +1,30 @@
|
|||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
|
|
||||||
use super::ServiceFactory;
|
use super::{IntoServiceFactory, ServiceFactory};
|
||||||
|
|
||||||
/// Adapt external config to a config for provided new service
|
/// Adapt external config argument to a config for provided service factory
|
||||||
pub fn map_config<T, F, C>(factory: T, f: F) -> MapConfig<T, F, C>
|
///
|
||||||
|
/// Note that this function consumes the receiving service factory and returns
|
||||||
|
/// a wrapped version of it.
|
||||||
|
pub fn map_config<T, U, F, C>(factory: U, f: F) -> MapConfig<T, F, C>
|
||||||
where
|
where
|
||||||
T: ServiceFactory,
|
T: ServiceFactory,
|
||||||
|
U: IntoServiceFactory<T>,
|
||||||
F: Fn(C) -> T::Config,
|
F: Fn(C) -> T::Config,
|
||||||
{
|
{
|
||||||
MapConfig::new(factory, f)
|
MapConfig::new(factory.into_factory(), f)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Replace config with unit
|
/// Replace config with unit
|
||||||
pub fn unit_config<T, C>(new_service: T) -> UnitConfig<T, C>
|
pub fn unit_config<T, U, C>(factory: U) -> UnitConfig<T, C>
|
||||||
where
|
where
|
||||||
T: ServiceFactory<Config = ()>,
|
T: ServiceFactory<Config = ()>,
|
||||||
|
U: IntoServiceFactory<T>,
|
||||||
{
|
{
|
||||||
UnitConfig::new(new_service)
|
UnitConfig::new(factory.into_factory())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `.map_config()` service combinator
|
/// `map_config()` adapter service factory
|
||||||
pub struct MapConfig<A, F, C> {
|
pub struct MapConfig<A, F, C> {
|
||||||
a: A,
|
a: A,
|
||||||
f: F,
|
f: F,
|
||||||
|
@@ -9,6 +9,7 @@ use crate::map_init_err::MapInitErr;
|
|||||||
use crate::then::{ThenService, ThenServiceFactory};
|
use crate::then::{ThenService, ThenServiceFactory};
|
||||||
use crate::{IntoService, IntoServiceFactory, Service, ServiceFactory};
|
use crate::{IntoService, IntoServiceFactory, Service, ServiceFactory};
|
||||||
|
|
||||||
|
/// Contruct new pipeline with one service in pipeline chain.
|
||||||
pub fn pipeline<F, T>(service: F) -> Pipeline<T>
|
pub fn pipeline<F, T>(service: F) -> Pipeline<T>
|
||||||
where
|
where
|
||||||
F: IntoService<T>,
|
F: IntoService<T>,
|
||||||
@@ -19,6 +20,7 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Contruct new pipeline factory with one service factory.
|
||||||
pub fn pipeline_factory<T, F>(factory: F) -> PipelineFactory<T>
|
pub fn pipeline_factory<T, F>(factory: F) -> PipelineFactory<T>
|
||||||
where
|
where
|
||||||
T: ServiceFactory,
|
T: ServiceFactory,
|
||||||
@@ -29,7 +31,7 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Pipeline service
|
/// Pipeline service - pipeline allows to compose multiple service into one service.
|
||||||
pub struct Pipeline<T> {
|
pub struct Pipeline<T> {
|
||||||
service: T,
|
service: T,
|
||||||
}
|
}
|
||||||
@@ -44,7 +46,12 @@ impl<T: Service> Pipeline<T> {
|
|||||||
///
|
///
|
||||||
/// 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.
|
||||||
pub fn and_then<F, U>(self, service: F) -> Pipeline<AndThenService<T, U>>
|
pub fn and_then<F, U>(
|
||||||
|
self,
|
||||||
|
service: F,
|
||||||
|
) -> Pipeline<
|
||||||
|
impl Service<Request = T::Request, Response = U::Response, Error = T::Error> + Clone,
|
||||||
|
>
|
||||||
where
|
where
|
||||||
Self: Sized,
|
Self: Sized,
|
||||||
F: IntoService<U>,
|
F: IntoService<U>,
|
||||||
@@ -63,7 +70,7 @@ impl<T: Service> Pipeline<T> {
|
|||||||
self,
|
self,
|
||||||
service: I,
|
service: I,
|
||||||
f: F,
|
f: F,
|
||||||
) -> Pipeline<AndThenApplyFn<T, U, F, Fut, Res, Err>>
|
) -> Pipeline<impl Service<Request = T::Request, Response = Res, Error = Err> + Clone>
|
||||||
where
|
where
|
||||||
Self: Sized,
|
Self: Sized,
|
||||||
I: IntoService<U>,
|
I: IntoService<U>,
|
||||||
@@ -82,7 +89,12 @@ impl<T: Service> Pipeline<T> {
|
|||||||
///
|
///
|
||||||
/// Note that this function consumes the receiving pipeline and returns a
|
/// Note that this function consumes the receiving pipeline and returns a
|
||||||
/// wrapped version of it.
|
/// wrapped version of it.
|
||||||
pub fn then<F, U>(self, service: F) -> Pipeline<ThenService<T, U>>
|
pub fn then<F, U>(
|
||||||
|
self,
|
||||||
|
service: F,
|
||||||
|
) -> Pipeline<
|
||||||
|
impl Service<Request = T::Request, Response = U::Response, Error = T::Error> + Clone,
|
||||||
|
>
|
||||||
where
|
where
|
||||||
Self: Sized,
|
Self: Sized,
|
||||||
F: IntoService<U>,
|
F: IntoService<U>,
|
||||||
@@ -159,14 +171,30 @@ impl<T: Service> Service for Pipeline<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Pipeline constructor
|
/// Pipeline factory
|
||||||
pub struct PipelineFactory<T> {
|
pub struct PipelineFactory<T> {
|
||||||
factory: T,
|
factory: T,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: ServiceFactory> PipelineFactory<T> {
|
impl<T: ServiceFactory> PipelineFactory<T> {
|
||||||
/// Call another service after call to this one has resolved successfully.
|
/// Call another service after call to this one has resolved successfully.
|
||||||
pub fn and_then<F, U>(self, factory: F) -> PipelineFactory<AndThenServiceFactory<T, U>>
|
pub fn and_then<F, U>(
|
||||||
|
self,
|
||||||
|
factory: F,
|
||||||
|
) -> PipelineFactory<
|
||||||
|
impl ServiceFactory<
|
||||||
|
Request = T::Request,
|
||||||
|
Response = U::Response,
|
||||||
|
Error = T::Error,
|
||||||
|
Config = T::Config,
|
||||||
|
InitError = T::InitError,
|
||||||
|
Service = impl Service<
|
||||||
|
Request = T::Request,
|
||||||
|
Response = U::Response,
|
||||||
|
Error = T::Error,
|
||||||
|
> + Clone,
|
||||||
|
> + Clone,
|
||||||
|
>
|
||||||
where
|
where
|
||||||
Self: Sized,
|
Self: Sized,
|
||||||
T::Config: Clone,
|
T::Config: Clone,
|
||||||
@@ -191,7 +219,16 @@ impl<T: ServiceFactory> PipelineFactory<T> {
|
|||||||
self,
|
self,
|
||||||
factory: I,
|
factory: I,
|
||||||
f: F,
|
f: F,
|
||||||
) -> PipelineFactory<AndThenApplyFnFactory<T, U, F, Fut, Res, Err>>
|
) -> PipelineFactory<
|
||||||
|
impl ServiceFactory<
|
||||||
|
Request = T::Request,
|
||||||
|
Response = Res,
|
||||||
|
Error = Err,
|
||||||
|
Config = T::Config,
|
||||||
|
InitError = T::InitError,
|
||||||
|
Service = impl Service<Request = T::Request, Response = Res, Error = Err> + Clone,
|
||||||
|
> + Clone,
|
||||||
|
>
|
||||||
where
|
where
|
||||||
Self: Sized,
|
Self: Sized,
|
||||||
T::Config: Clone,
|
T::Config: Clone,
|
||||||
@@ -212,7 +249,23 @@ impl<T: ServiceFactory> PipelineFactory<T> {
|
|||||||
///
|
///
|
||||||
/// Note that this function consumes the receiving pipeline and returns a
|
/// Note that this function consumes the receiving pipeline and returns a
|
||||||
/// wrapped version of it.
|
/// wrapped version of it.
|
||||||
pub fn then<F, U>(self, factory: F) -> PipelineFactory<ThenServiceFactory<T, U>>
|
pub fn then<F, U>(
|
||||||
|
self,
|
||||||
|
factory: F,
|
||||||
|
) -> PipelineFactory<
|
||||||
|
impl ServiceFactory<
|
||||||
|
Request = T::Request,
|
||||||
|
Response = U::Response,
|
||||||
|
Error = T::Error,
|
||||||
|
Config = T::Config,
|
||||||
|
InitError = T::InitError,
|
||||||
|
Service = impl Service<
|
||||||
|
Request = T::Request,
|
||||||
|
Response = U::Response,
|
||||||
|
Error = T::Error,
|
||||||
|
> + Clone,
|
||||||
|
> + Clone,
|
||||||
|
>
|
||||||
where
|
where
|
||||||
Self: Sized,
|
Self: Sized,
|
||||||
T::Config: Clone,
|
T::Config: Clone,
|
||||||
|
@@ -1,5 +1,6 @@
|
|||||||
use std::future::Future;
|
use std::future::Future;
|
||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
|
use std::rc::Rc;
|
||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
use super::{Service, ServiceFactory};
|
use super::{Service, ServiceFactory};
|
||||||
@@ -8,11 +9,8 @@ use crate::cell::Cell;
|
|||||||
/// Service for the `then` combinator, chaining a computation onto the end of
|
/// Service for the `then` combinator, chaining a computation onto the end of
|
||||||
/// another service.
|
/// another service.
|
||||||
///
|
///
|
||||||
/// This is created by the `ServiceExt::then` method.
|
/// This is created by the `Pipeline::then` method.
|
||||||
pub struct ThenService<A, B> {
|
pub(crate) struct ThenService<A, B>(Cell<(A, B)>);
|
||||||
a: A,
|
|
||||||
b: Cell<B>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<A, B> ThenService<A, B> {
|
impl<A, B> ThenService<A, B> {
|
||||||
/// Create new `.then()` combinator
|
/// Create new `.then()` combinator
|
||||||
@@ -21,19 +19,13 @@ impl<A, B> ThenService<A, B> {
|
|||||||
A: Service,
|
A: Service,
|
||||||
B: Service<Request = Result<A::Response, A::Error>, Error = A::Error>,
|
B: Service<Request = Result<A::Response, A::Error>, Error = A::Error>,
|
||||||
{
|
{
|
||||||
Self { a, b: Cell::new(b) }
|
Self(Cell::new((a, b)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, B> Clone for ThenService<A, B>
|
impl<A, B> Clone for ThenService<A, B> {
|
||||||
where
|
|
||||||
A: Clone,
|
|
||||||
{
|
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
ThenService {
|
ThenService(self.0.clone())
|
||||||
a: self.a.clone(),
|
|
||||||
b: self.b.clone(),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -47,9 +39,10 @@ where
|
|||||||
type Error = B::Error;
|
type Error = B::Error;
|
||||||
type Future = ThenServiceResponse<A, B>;
|
type Future = ThenServiceResponse<A, B>;
|
||||||
|
|
||||||
fn poll_ready(&mut self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||||
let not_ready = !self.a.poll_ready(ctx)?.is_ready();
|
let srv = self.0.get_mut();
|
||||||
if !self.b.get_mut().poll_ready(ctx)?.is_ready() || not_ready {
|
let not_ready = !srv.0.poll_ready(cx)?.is_ready();
|
||||||
|
if !srv.1.poll_ready(cx)?.is_ready() || not_ready {
|
||||||
Poll::Pending
|
Poll::Pending
|
||||||
} else {
|
} else {
|
||||||
Poll::Ready(Ok(()))
|
Poll::Ready(Ok(()))
|
||||||
@@ -58,13 +51,13 @@ where
|
|||||||
|
|
||||||
fn call(&mut self, req: A::Request) -> Self::Future {
|
fn call(&mut self, req: A::Request) -> Self::Future {
|
||||||
ThenServiceResponse {
|
ThenServiceResponse {
|
||||||
state: State::A(self.a.call(req), Some(self.b.clone())),
|
state: State::A(self.0.get_mut().0.call(req), Some(self.0.clone())),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[pin_project::pin_project]
|
#[pin_project::pin_project]
|
||||||
pub struct ThenServiceResponse<A, B>
|
pub(crate) struct ThenServiceResponse<A, B>
|
||||||
where
|
where
|
||||||
A: Service,
|
A: Service,
|
||||||
B: Service<Request = Result<A::Response, A::Error>>,
|
B: Service<Request = Result<A::Response, A::Error>>,
|
||||||
@@ -79,7 +72,7 @@ where
|
|||||||
A: Service,
|
A: Service,
|
||||||
B: Service<Request = Result<A::Response, A::Error>>,
|
B: Service<Request = Result<A::Response, A::Error>>,
|
||||||
{
|
{
|
||||||
A(#[pin] A::Future, Option<Cell<B>>),
|
A(#[pin] A::Future, Option<Cell<(A, B)>>),
|
||||||
B(#[pin] B::Future),
|
B(#[pin] B::Future),
|
||||||
Empty,
|
Empty,
|
||||||
}
|
}
|
||||||
@@ -101,7 +94,7 @@ where
|
|||||||
Poll::Ready(res) => {
|
Poll::Ready(res) => {
|
||||||
let mut b = b.take().unwrap();
|
let mut b = b.take().unwrap();
|
||||||
this.state.set(State::Empty); // drop fut A
|
this.state.set(State::Empty); // drop fut A
|
||||||
let fut = b.get_mut().call(res);
|
let fut = b.get_mut().1.call(res);
|
||||||
this.state.set(State::B(fut));
|
this.state.set(State::B(fut));
|
||||||
self.poll(cx)
|
self.poll(cx)
|
||||||
}
|
}
|
||||||
@@ -117,10 +110,7 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// `.then()` service factory combinator
|
/// `.then()` service factory combinator
|
||||||
pub struct ThenServiceFactory<A, B> {
|
pub(crate) struct ThenServiceFactory<A, B>(Rc<(A, B)>);
|
||||||
a: A,
|
|
||||||
b: B,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<A, B> ThenServiceFactory<A, B>
|
impl<A, B> ThenServiceFactory<A, B>
|
||||||
where
|
where
|
||||||
@@ -135,7 +125,7 @@ where
|
|||||||
{
|
{
|
||||||
/// Create new `AndThen` combinator
|
/// Create new `AndThen` combinator
|
||||||
pub(crate) fn new(a: A, b: B) -> Self {
|
pub(crate) fn new(a: A, b: B) -> Self {
|
||||||
Self { a, b }
|
Self(Rc::new((a, b)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -160,28 +150,19 @@ where
|
|||||||
type Future = ThenServiceFactoryResponse<A, B>;
|
type Future = ThenServiceFactoryResponse<A, B>;
|
||||||
|
|
||||||
fn new_service(&self, cfg: A::Config) -> Self::Future {
|
fn new_service(&self, cfg: A::Config) -> Self::Future {
|
||||||
ThenServiceFactoryResponse::new(
|
let srv = &*self.0;
|
||||||
self.a.new_service(cfg.clone()),
|
ThenServiceFactoryResponse::new(srv.0.new_service(cfg.clone()), srv.1.new_service(cfg))
|
||||||
self.b.new_service(cfg),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, B> Clone for ThenServiceFactory<A, B>
|
impl<A, B> Clone for ThenServiceFactory<A, B> {
|
||||||
where
|
|
||||||
A: Clone,
|
|
||||||
B: Clone,
|
|
||||||
{
|
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
Self {
|
Self(self.0.clone())
|
||||||
a: self.a.clone(),
|
|
||||||
b: self.b.clone(),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[pin_project::pin_project]
|
#[pin_project::pin_project]
|
||||||
pub struct ThenServiceFactoryResponse<A, B>
|
pub(crate) struct ThenServiceFactoryResponse<A, B>
|
||||||
where
|
where
|
||||||
A: ServiceFactory,
|
A: ServiceFactory,
|
||||||
B: ServiceFactory<
|
B: ServiceFactory<
|
||||||
@@ -324,11 +305,11 @@ mod tests {
|
|||||||
|
|
||||||
let res = srv.call(Ok("srv1")).await;
|
let res = srv.call(Ok("srv1")).await;
|
||||||
assert!(res.is_ok());
|
assert!(res.is_ok());
|
||||||
assert_eq!(res.unwrap(), (("srv1", "ok")));
|
assert_eq!(res.unwrap(), ("srv1", "ok"));
|
||||||
|
|
||||||
let res = srv.call(Err("srv")).await;
|
let res = srv.call(Err("srv")).await;
|
||||||
assert!(res.is_ok());
|
assert!(res.is_ok());
|
||||||
assert_eq!(res.unwrap(), (("srv2", "err")));
|
assert_eq!(res.unwrap(), ("srv2", "err"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
@@ -340,10 +321,10 @@ mod tests {
|
|||||||
let mut srv = factory.new_service(&()).await.unwrap();
|
let mut srv = factory.new_service(&()).await.unwrap();
|
||||||
let res = srv.call(Ok("srv1")).await;
|
let res = srv.call(Ok("srv1")).await;
|
||||||
assert!(res.is_ok());
|
assert!(res.is_ok());
|
||||||
assert_eq!(res.unwrap(), (("srv1", "ok")));
|
assert_eq!(res.unwrap(), ("srv1", "ok"));
|
||||||
|
|
||||||
let res = srv.call(Err("srv")).await;
|
let res = srv.call(Err("srv")).await;
|
||||||
assert!(res.is_ok());
|
assert!(res.is_ok());
|
||||||
assert_eq!(res.unwrap(), (("srv2", "err")));
|
assert_eq!(res.unwrap(), ("srv2", "err"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -7,23 +7,88 @@ use std::task::{Context, Poll};
|
|||||||
use crate::transform_err::TransformMapInitErr;
|
use crate::transform_err::TransformMapInitErr;
|
||||||
use crate::{IntoServiceFactory, Service, ServiceFactory};
|
use crate::{IntoServiceFactory, Service, ServiceFactory};
|
||||||
|
|
||||||
/// Apply transform to a service. Function returns
|
/// Apply transform to a service.
|
||||||
/// services factory that in initialization creates
|
pub fn apply<T, S, U>(t: T, factory: U) -> ApplyTransform<T, S>
|
||||||
/// service and applies transform to this service.
|
|
||||||
pub fn apply<T, S, U>(t: T, service: U) -> ApplyTransform<T, S>
|
|
||||||
where
|
where
|
||||||
S: ServiceFactory,
|
S: ServiceFactory,
|
||||||
T: Transform<S::Service, InitError = S::InitError>,
|
T: Transform<S::Service, InitError = S::InitError>,
|
||||||
U: IntoServiceFactory<S>,
|
U: IntoServiceFactory<S>,
|
||||||
{
|
{
|
||||||
ApplyTransform::new(t, service.into_factory())
|
ApplyTransform::new(t, factory.into_factory())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The `Transform` trait defines the interface of a service factory that wraps inner service
|
||||||
|
/// during construction.
|
||||||
|
///
|
||||||
|
/// Transform(middleware) wraps inner service and runs during
|
||||||
|
/// inbound and/or outbound processing in the request/response lifecycle.
|
||||||
|
/// It may modify request and/or response.
|
||||||
|
///
|
||||||
|
/// For example, timeout transform:
|
||||||
|
///
|
||||||
|
/// ```rust,ignore
|
||||||
|
/// pub struct Timeout<S> {
|
||||||
|
/// service: S,
|
||||||
|
/// timeout: Duration,
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// impl<S> Service for Timeout<S>
|
||||||
|
/// where
|
||||||
|
/// S: Service,
|
||||||
|
/// {
|
||||||
|
/// type Request = S::Request;
|
||||||
|
/// type Response = S::Response;
|
||||||
|
/// type Error = TimeoutError<S::Error>;
|
||||||
|
/// type Future = TimeoutServiceResponse<S>;
|
||||||
|
///
|
||||||
|
/// fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||||
|
/// ready!(self.service.poll_ready(cx)).map_err(TimeoutError::Service)
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// fn call(&mut self, req: S::Request) -> Self::Future {
|
||||||
|
/// TimeoutServiceResponse {
|
||||||
|
/// fut: self.service.call(req),
|
||||||
|
/// sleep: Delay::new(clock::now() + self.timeout),
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// Timeout service in above example is decoupled from underlying service implementation
|
||||||
|
/// and could be applied to any service.
|
||||||
|
///
|
||||||
/// The `Transform` trait defines the interface of a Service factory. `Transform`
|
/// The `Transform` trait defines the interface of a Service factory. `Transform`
|
||||||
/// is often implemented for middleware, defining how to construct a
|
/// is often implemented for middleware, defining how to construct a
|
||||||
/// middleware Service. A Service that is constructed by the factory takes
|
/// middleware Service. A Service that is constructed by the factory takes
|
||||||
/// the Service that follows it during execution as a parameter, assuming
|
/// the Service that follows it during execution as a parameter, assuming
|
||||||
/// ownership of the next Service.
|
/// ownership of the next Service.
|
||||||
|
///
|
||||||
|
/// Factory for `Timeout` middleware from the above example could look like this:
|
||||||
|
///
|
||||||
|
/// ```rust,,ignore
|
||||||
|
/// pub struct TimeoutTransform {
|
||||||
|
/// timeout: Duration,
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// impl<S> Transform<S> for TimeoutTransform<E>
|
||||||
|
/// where
|
||||||
|
/// S: Service,
|
||||||
|
/// {
|
||||||
|
/// type Request = S::Request;
|
||||||
|
/// type Response = S::Response;
|
||||||
|
/// type Error = TimeoutError<S::Error>;
|
||||||
|
/// type InitError = S::Error;
|
||||||
|
/// type Transform = Timeout<S>;
|
||||||
|
/// type Future = Ready<Result<Self::Transform, Self::InitError>>;
|
||||||
|
///
|
||||||
|
/// fn new_transform(&self, service: S) -> Self::Future {
|
||||||
|
/// ok(TimeoutService {
|
||||||
|
/// service,
|
||||||
|
/// timeout: self.timeout,
|
||||||
|
/// })
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
pub trait Transform<S> {
|
pub trait Transform<S> {
|
||||||
/// Requests handled by the service.
|
/// Requests handled by the service.
|
||||||
type Request;
|
type Request;
|
||||||
@@ -41,13 +106,13 @@ pub trait Transform<S> {
|
|||||||
Error = Self::Error,
|
Error = Self::Error,
|
||||||
>;
|
>;
|
||||||
|
|
||||||
/// Errors produced while building a service.
|
/// Errors produced while building a transform service.
|
||||||
type InitError;
|
type InitError;
|
||||||
|
|
||||||
/// The future response value.
|
/// The future response value.
|
||||||
type Future: Future<Output = Result<Self::Transform, Self::InitError>>;
|
type Future: Future<Output = Result<Self::Transform, Self::InitError>>;
|
||||||
|
|
||||||
/// Creates and returns a new Service component, asynchronously
|
/// Creates and returns a new Transform component, asynchronously
|
||||||
fn new_transform(&self, service: S) -> Self::Future;
|
fn new_transform(&self, service: S) -> Self::Future;
|
||||||
|
|
||||||
/// Map this transforms's factory error to a different error,
|
/// Map this transforms's factory error to a different error,
|
||||||
|
@@ -1,5 +1,15 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [1.0.1] - 2020-05-19
|
||||||
|
|
||||||
|
* Replace deprecated `net2` crate with `socket2`
|
||||||
|
|
||||||
|
* Remove unused `futures` dependency
|
||||||
|
|
||||||
|
## [1.0.0] - 2019-12-11
|
||||||
|
|
||||||
|
* Update actix-server to 1.0.0
|
||||||
|
|
||||||
## [1.0.0-alpha.3] - 2019-12-07
|
## [1.0.0-alpha.3] - 2019-12-07
|
||||||
|
|
||||||
* Migrate to tokio 0.2
|
* Migrate to tokio 0.2
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-testing"
|
name = "actix-testing"
|
||||||
version = "1.0.0-alpha.3"
|
version = "1.0.1"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix testing utils"
|
description = "Actix testing utils"
|
||||||
keywords = ["network", "framework", "async", "futures"]
|
keywords = ["network", "framework", "async", "futures"]
|
||||||
@@ -11,17 +11,17 @@ categories = ["network-programming", "asynchronous"]
|
|||||||
license = "MIT/Apache-2.0"
|
license = "MIT/Apache-2.0"
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
workspace = ".."
|
workspace = ".."
|
||||||
|
readme = "README.md"
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
name = "actix_testing"
|
name = "actix_testing"
|
||||||
path = "src/lib.rs"
|
path = "src/lib.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-rt = "1.0.0-alpha.3"
|
actix-rt = "1.0.0"
|
||||||
actix-macros = "0.1.0-alpha.1"
|
actix-macros = "0.1.0"
|
||||||
actix-server = "1.0.0-alpha.3"
|
actix-server = "1.0.0"
|
||||||
actix-service = "1.0.0-alpha.3"
|
actix-service = "1.0.0"
|
||||||
|
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
net2 = "0.2"
|
socket2 = "0.3"
|
||||||
futures = "0.3.1"
|
|
||||||
|
@@ -1,13 +1,13 @@
|
|||||||
//! Various helpers for Actix applications to use during testing.
|
//! Various helpers for Actix applications to use during testing.
|
||||||
#![deny(rust_2018_idioms, warnings)]
|
#![deny(rust_2018_idioms, warnings)]
|
||||||
#![allow(clippy::type_complexity)]
|
#![allow(clippy::type_complexity, clippy::needless_doctest_main)]
|
||||||
|
|
||||||
use std::sync::mpsc;
|
use std::sync::mpsc;
|
||||||
use std::{net, thread};
|
use std::{net, thread};
|
||||||
|
|
||||||
use actix_rt::{net::TcpStream, System};
|
use actix_rt::{net::TcpStream, System};
|
||||||
use actix_server::{Server, ServerBuilder, ServiceFactory};
|
use actix_server::{Server, ServerBuilder, ServiceFactory};
|
||||||
use net2::TcpBuilder;
|
use socket2::{Domain, Protocol, Socket, Type};
|
||||||
|
|
||||||
#[cfg(not(test))] // Work around for rust-lang/rust#62127
|
#[cfg(not(test))] // Work around for rust-lang/rust#62127
|
||||||
pub use actix_macros::test;
|
pub use actix_macros::test;
|
||||||
@@ -20,12 +20,12 @@ pub use actix_macros::test;
|
|||||||
/// # Examples
|
/// # Examples
|
||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// use actix_service::{service_fn};
|
/// use actix_service::fn_service;
|
||||||
/// use actix_testing::TestServer;
|
/// use actix_testing::TestServer;
|
||||||
///
|
///
|
||||||
/// #[actix_rt::main]
|
/// #[actix_rt::main]
|
||||||
/// async fn main() {
|
/// async fn main() {
|
||||||
/// let srv = TestServer::with(|| service_fn(
|
/// let srv = TestServer::with(|| fn_service(
|
||||||
/// |sock| async move {
|
/// |sock| async move {
|
||||||
/// println!("New connection: {:?}", sock);
|
/// println!("New connection: {:?}", sock);
|
||||||
/// Ok::<_, ()>(())
|
/// Ok::<_, ()>(())
|
||||||
@@ -110,10 +110,11 @@ impl TestServer {
|
|||||||
/// Get firat available unused local address
|
/// Get firat available unused local address
|
||||||
pub fn unused_addr() -> net::SocketAddr {
|
pub fn unused_addr() -> net::SocketAddr {
|
||||||
let addr: net::SocketAddr = "127.0.0.1:0".parse().unwrap();
|
let addr: net::SocketAddr = "127.0.0.1:0".parse().unwrap();
|
||||||
let socket = TcpBuilder::new_v4().unwrap();
|
let socket =
|
||||||
socket.bind(&addr).unwrap();
|
Socket::new(Domain::ipv4(), Type::stream(), Some(Protocol::tcp())).unwrap();
|
||||||
socket.reuse_address(true).unwrap();
|
socket.bind(&addr.into()).unwrap();
|
||||||
let tcp = socket.to_tcp_listener().unwrap();
|
socket.set_reuse_address(true).unwrap();
|
||||||
|
let tcp = socket.into_tcp_listener();
|
||||||
tcp.local_addr().unwrap()
|
tcp.local_addr().unwrap()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,5 +1,11 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [0.3.1] - 2019-12-12
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Use parking_lot 0.10
|
||||||
|
|
||||||
## [0.3.0] - 2019-12-02
|
## [0.3.0] - 2019-12-02
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-threadpool"
|
name = "actix-threadpool"
|
||||||
version = "0.3.0"
|
version = "0.3.1"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix thread pool for sync code"
|
description = "Actix thread pool for sync code"
|
||||||
keywords = ["actix", "network", "framework", "async", "futures"]
|
keywords = ["actix", "network", "framework", "async", "futures"]
|
||||||
@@ -19,9 +19,9 @@ path = "src/lib.rs"
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
derive_more = "0.99.2"
|
derive_more = "0.99.2"
|
||||||
futures = "0.3.1"
|
futures-channel = "0.3.1"
|
||||||
parking_lot = "0.9"
|
parking_lot = "0.10"
|
||||||
lazy_static = "1.2"
|
lazy_static = "1.3"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
num_cpus = "1.10"
|
num_cpus = "1.10"
|
||||||
threadpool = "1.7"
|
threadpool = "1.7"
|
||||||
|
@@ -6,7 +6,7 @@ use std::pin::Pin;
|
|||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
use derive_more::Display;
|
use derive_more::Display;
|
||||||
use futures::channel::oneshot;
|
use futures_channel::oneshot;
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
use threadpool::ThreadPool;
|
use threadpool::ThreadPool;
|
||||||
|
|
||||||
@@ -48,6 +48,8 @@ pub enum BlockingError<E: fmt::Debug> {
|
|||||||
Canceled,
|
Canceled,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<E: fmt::Debug> std::error::Error for BlockingError<E> {}
|
||||||
|
|
||||||
/// Execute blocking function on a thread pool, returns future that resolves
|
/// Execute blocking function on a thread pool, returns future that resolves
|
||||||
/// to result of the function execution.
|
/// to result of the function execution.
|
||||||
pub fn run<F, I, E>(f: F) -> CpuFuture<I, E>
|
pub fn run<F, I, E>(f: F) -> CpuFuture<I, E>
|
||||||
@@ -79,9 +81,12 @@ impl<I, E: fmt::Debug> Future for CpuFuture<I, E> {
|
|||||||
|
|
||||||
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||||
let rx = Pin::new(&mut self.rx);
|
let rx = Pin::new(&mut self.rx);
|
||||||
let res = futures::ready!(rx.poll(cx))
|
let res = match rx.poll(cx) {
|
||||||
.map_err(|_| BlockingError::Canceled)
|
Poll::Pending => return Poll::Pending,
|
||||||
.and_then(|res| res.map_err(BlockingError::Error));
|
Poll::Ready(res) => res
|
||||||
|
.map_err(|_| BlockingError::Canceled)
|
||||||
|
.and_then(|res| res.map_err(BlockingError::Error)),
|
||||||
|
};
|
||||||
Poll::Ready(res)
|
Poll::Ready(res)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,6 +1,18 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
[1.0.0-alpha.3] - 2019-12-07
|
## [2.0.0-alpha.1] - 2020-03-03
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Update `rustls` dependency to 0.17
|
||||||
|
* Update `tokio-rustls` dependency to 0.13
|
||||||
|
* Update `webpki-roots` dependency to 0.19
|
||||||
|
|
||||||
|
## [1.0.0] - 2019-12-11
|
||||||
|
|
||||||
|
* 1.0.0 release
|
||||||
|
|
||||||
|
## [1.0.0-alpha.3] - 2019-12-07
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-tls"
|
name = "actix-tls"
|
||||||
version = "1.0.0-alpha.3"
|
version = "2.0.0-alpha.1"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix tls services"
|
description = "Actix tls services"
|
||||||
keywords = ["network", "framework", "async", "futures"]
|
keywords = ["network", "framework", "async", "futures"]
|
||||||
@@ -32,13 +32,13 @@ rustls = ["rust-tls", "webpki", "webpki-roots", "tokio-rustls"]
|
|||||||
nativetls = ["native-tls", "tokio-tls"]
|
nativetls = ["native-tls", "tokio-tls"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-service = "1.0.0-alpha.3"
|
actix-service = "1.0.0"
|
||||||
actix-codec = "0.2.0-alpha.3"
|
actix-codec = "0.2.0"
|
||||||
actix-utils = "1.0.0-alpha.3"
|
actix-utils = "1.0.0"
|
||||||
actix-rt = "1.0.0-alpha.3"
|
actix-rt = "1.0.0"
|
||||||
derive_more = "0.99.2"
|
derive_more = "0.99.2"
|
||||||
either = "1.5.2"
|
either = "1.5.2"
|
||||||
futures = "0.3.1"
|
futures-util = { version = "0.3.4", default-features = false }
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
|
|
||||||
# openssl
|
# openssl
|
||||||
@@ -46,10 +46,10 @@ open-ssl = { version="0.10", package = "openssl", optional = true }
|
|||||||
tokio-openssl = { version = "0.4.0", optional = true }
|
tokio-openssl = { version = "0.4.0", optional = true }
|
||||||
|
|
||||||
# rustls
|
# rustls
|
||||||
rust-tls = { version = "0.16.0", package = "rustls", optional = true }
|
rust-tls = { version = "0.17.0", package = "rustls", optional = true }
|
||||||
webpki = { version = "0.21", optional = true }
|
webpki = { version = "0.21", optional = true }
|
||||||
webpki-roots = { version = "0.17", optional = true }
|
webpki-roots = { version = "0.19", optional = true }
|
||||||
tokio-rustls = { version = "0.12.0", optional = true }
|
tokio-rustls = { version = "0.13.0", optional = true }
|
||||||
|
|
||||||
# native-tls
|
# native-tls
|
||||||
native-tls = { version="0.2", optional = true }
|
native-tls = { version="0.2", optional = true }
|
||||||
@@ -57,4 +57,4 @@ tokio-tls = { version="0.3", optional = true }
|
|||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
bytes = "0.5"
|
bytes = "0.5"
|
||||||
actix-testing = { version="1.0.0-alpha.3" }
|
actix-testing = { version="1.0.0" }
|
||||||
|
@@ -4,7 +4,7 @@ use std::task::{Context, Poll};
|
|||||||
use actix_codec::{AsyncRead, AsyncWrite};
|
use actix_codec::{AsyncRead, AsyncWrite};
|
||||||
use actix_service::{Service, ServiceFactory};
|
use actix_service::{Service, ServiceFactory};
|
||||||
use actix_utils::counter::Counter;
|
use actix_utils::counter::Counter;
|
||||||
use futures::future::{self, FutureExt, LocalBoxFuture, TryFutureExt};
|
use futures_util::future::{self, FutureExt, LocalBoxFuture, TryFutureExt};
|
||||||
pub use native_tls::Error;
|
pub use native_tls::Error;
|
||||||
pub use tokio_tls::{TlsAcceptor, TlsStream};
|
pub use tokio_tls::{TlsAcceptor, TlsStream};
|
||||||
|
|
||||||
|
@@ -3,13 +3,13 @@ use std::marker::PhantomData;
|
|||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
pub use open_ssl::ssl::{SslAcceptor, SslAcceptorBuilder};
|
pub use open_ssl::ssl::{AlpnError, SslAcceptor, SslAcceptorBuilder};
|
||||||
pub use tokio_openssl::{HandshakeError, SslStream};
|
pub use tokio_openssl::{HandshakeError, SslStream};
|
||||||
|
|
||||||
use actix_codec::{AsyncRead, AsyncWrite};
|
use actix_codec::{AsyncRead, AsyncWrite};
|
||||||
use actix_service::{Service, ServiceFactory};
|
use actix_service::{Service, ServiceFactory};
|
||||||
use actix_utils::counter::{Counter, CounterGuard};
|
use actix_utils::counter::{Counter, CounterGuard};
|
||||||
use futures::future::{ok, FutureExt, LocalBoxFuture, Ready};
|
use futures_util::future::{ok, FutureExt, LocalBoxFuture, Ready};
|
||||||
|
|
||||||
use crate::MAX_CONN_COUNTER;
|
use crate::MAX_CONN_COUNTER;
|
||||||
|
|
||||||
@@ -88,7 +88,7 @@ impl<T: AsyncRead + AsyncWrite + Unpin + 'static> Service for AcceptorService<T>
|
|||||||
let acc = acc;
|
let acc = acc;
|
||||||
tokio_openssl::accept(&acc, req).await
|
tokio_openssl::accept(&acc, req).await
|
||||||
}
|
}
|
||||||
.boxed_local(),
|
.boxed_local(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -105,7 +105,7 @@ impl<T: AsyncRead + AsyncWrite + Unpin> Future for AcceptorServiceResponse<T> {
|
|||||||
type Output = Result<SslStream<T>, HandshakeError<T>>;
|
type Output = Result<SslStream<T>, HandshakeError<T>>;
|
||||||
|
|
||||||
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||||
let io = futures::ready!(Pin::new(&mut self.fut).poll(cx))?;
|
let io = futures_util::ready!(Pin::new(&mut self.fut).poll(cx))?;
|
||||||
Poll::Ready(Ok(io))
|
Poll::Ready(Ok(io))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -8,7 +8,7 @@ use std::task::{Context, Poll};
|
|||||||
use actix_codec::{AsyncRead, AsyncWrite};
|
use actix_codec::{AsyncRead, AsyncWrite};
|
||||||
use actix_service::{Service, ServiceFactory};
|
use actix_service::{Service, ServiceFactory};
|
||||||
use actix_utils::counter::{Counter, CounterGuard};
|
use actix_utils::counter::{Counter, CounterGuard};
|
||||||
use futures::future::{ok, Ready};
|
use futures_util::future::{ok, Ready};
|
||||||
use tokio_rustls::{Accept, TlsAcceptor};
|
use tokio_rustls::{Accept, TlsAcceptor};
|
||||||
|
|
||||||
pub use rust_tls::{ServerConfig, Session};
|
pub use rust_tls::{ServerConfig, Session};
|
||||||
@@ -108,7 +108,7 @@ impl<T: AsyncRead + AsyncWrite + Unpin> Future for AcceptorServiceFut<T> {
|
|||||||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||||
let this = self.get_mut();
|
let this = self.get_mut();
|
||||||
|
|
||||||
let res = futures::ready!(Pin::new(&mut this.fut).poll(cx));
|
let res = futures_util::ready!(Pin::new(&mut this.fut).poll(cx));
|
||||||
match res {
|
match res {
|
||||||
Ok(io) => Poll::Ready(Ok(io)),
|
Ok(io) => Poll::Ready(Ok(io)),
|
||||||
Err(e) => Poll::Ready(Err(e)),
|
Err(e) => Poll::Ready(Err(e)),
|
||||||
|
5
actix-tracing/CHANGES.md
Normal file
5
actix-tracing/CHANGES.md
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
# Changes
|
||||||
|
|
||||||
|
## [0.1.0] - 2020-01-15
|
||||||
|
|
||||||
|
* Initial release
|
26
actix-tracing/Cargo.toml
Normal file
26
actix-tracing/Cargo.toml
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
[package]
|
||||||
|
name = "actix-tracing"
|
||||||
|
version = "0.1.0"
|
||||||
|
authors = ["Rajasekharan Vengalil <avranju@gmail.com>"]
|
||||||
|
description = "Support for tokio tracing with Actix services"
|
||||||
|
keywords = ["network", "framework", "tracing"]
|
||||||
|
homepage = "https://actix.rs"
|
||||||
|
repository = "https://github.com/actix/actix-net.git"
|
||||||
|
documentation = "https://docs.rs/actix-tracing/"
|
||||||
|
categories = ["network-programming", "asynchronous"]
|
||||||
|
license = "MIT/Apache-2.0"
|
||||||
|
edition = "2018"
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
name = "actix_tracing"
|
||||||
|
path = "src/lib.rs"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
actix-service = "1.0.4"
|
||||||
|
futures-util = { version = "0.3.4", default-features = false }
|
||||||
|
tracing = "0.1"
|
||||||
|
tracing-futures = "0.2"
|
||||||
|
|
||||||
|
[dev_dependencies]
|
||||||
|
actix-rt = "1.0"
|
||||||
|
slab = "0.4"
|
1
actix-tracing/LICENSE-APACHE
Symbolic link
1
actix-tracing/LICENSE-APACHE
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../LICENSE-APACHE
|
1
actix-tracing/LICENSE-MIT
Symbolic link
1
actix-tracing/LICENSE-MIT
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../LICENSE-MIT
|
261
actix-tracing/src/lib.rs
Normal file
261
actix-tracing/src/lib.rs
Normal file
@@ -0,0 +1,261 @@
|
|||||||
|
//! Actix tracing - support for tokio tracing with Actix services.
|
||||||
|
#![deny(rust_2018_idioms, warnings)]
|
||||||
|
|
||||||
|
use std::marker::PhantomData;
|
||||||
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
|
use actix_service::{
|
||||||
|
apply, dev::ApplyTransform, IntoServiceFactory, Service, ServiceFactory, Transform,
|
||||||
|
};
|
||||||
|
use futures_util::future::{ok, Either, Ready};
|
||||||
|
use tracing_futures::{Instrument, Instrumented};
|
||||||
|
|
||||||
|
/// A `Service` implementation that automatically enters/exits tracing spans
|
||||||
|
/// for the wrapped inner service.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct TracingService<S, F> {
|
||||||
|
inner: S,
|
||||||
|
make_span: F,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<S, F> TracingService<S, F> {
|
||||||
|
pub fn new(inner: S, make_span: F) -> Self {
|
||||||
|
TracingService { inner, make_span }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<S, F> Service for TracingService<S, F>
|
||||||
|
where
|
||||||
|
S: Service,
|
||||||
|
F: Fn(&S::Request) -> Option<tracing::Span>,
|
||||||
|
{
|
||||||
|
type Request = S::Request;
|
||||||
|
type Response = S::Response;
|
||||||
|
type Error = S::Error;
|
||||||
|
type Future = Either<S::Future, Instrumented<S::Future>>;
|
||||||
|
|
||||||
|
fn poll_ready(&mut self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||||
|
self.inner.poll_ready(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn call(&mut self, req: Self::Request) -> Self::Future {
|
||||||
|
let span = (self.make_span)(&req);
|
||||||
|
let _enter = span.as_ref().map(|s| s.enter());
|
||||||
|
|
||||||
|
let fut = self.inner.call(req);
|
||||||
|
|
||||||
|
// make a child span to track the future's execution
|
||||||
|
if let Some(span) = span
|
||||||
|
.clone()
|
||||||
|
.map(|span| tracing::span!(parent: &span, tracing::Level::INFO, "future"))
|
||||||
|
{
|
||||||
|
Either::Right(fut.instrument(span))
|
||||||
|
} else {
|
||||||
|
Either::Left(fut)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A `Transform` implementation that wraps services with a [`TracingService`].
|
||||||
|
///
|
||||||
|
/// [`TracingService`]: struct.TracingService.html
|
||||||
|
pub struct TracingTransform<S, U, F> {
|
||||||
|
make_span: F,
|
||||||
|
_p: PhantomData<fn(S, U)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<S, U, F> TracingTransform<S, U, F> {
|
||||||
|
pub fn new(make_span: F) -> Self {
|
||||||
|
TracingTransform {
|
||||||
|
make_span,
|
||||||
|
_p: PhantomData,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<S, U, F> Transform<S> for TracingTransform<S, U, F>
|
||||||
|
where
|
||||||
|
S: Service,
|
||||||
|
U: ServiceFactory<
|
||||||
|
Request = S::Request,
|
||||||
|
Response = S::Response,
|
||||||
|
Error = S::Error,
|
||||||
|
Service = S,
|
||||||
|
>,
|
||||||
|
F: Fn(&S::Request) -> Option<tracing::Span> + Clone,
|
||||||
|
{
|
||||||
|
type Request = S::Request;
|
||||||
|
type Response = S::Response;
|
||||||
|
type Error = S::Error;
|
||||||
|
type Transform = TracingService<S, F>;
|
||||||
|
type InitError = U::InitError;
|
||||||
|
type Future = Ready<Result<Self::Transform, Self::InitError>>;
|
||||||
|
|
||||||
|
fn new_transform(&self, service: S) -> Self::Future {
|
||||||
|
ok(TracingService::new(service, self.make_span.clone()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wraps the provided service factory with a transform that automatically
|
||||||
|
/// enters/exits the given span.
|
||||||
|
///
|
||||||
|
/// The span to be entered/exited can be provided via a closure. The closure
|
||||||
|
/// is passed in a reference to the request being handled by the service.
|
||||||
|
///
|
||||||
|
/// For example:
|
||||||
|
/// ```rust,ignore
|
||||||
|
/// let traced_service = trace(
|
||||||
|
/// web_service,
|
||||||
|
/// |req: &Request| Some(span!(Level::INFO, "request", req.id))
|
||||||
|
/// );
|
||||||
|
/// ```
|
||||||
|
pub fn trace<S, U, F>(
|
||||||
|
service_factory: U,
|
||||||
|
make_span: F,
|
||||||
|
) -> ApplyTransform<TracingTransform<S::Service, S, F>, S>
|
||||||
|
where
|
||||||
|
S: ServiceFactory,
|
||||||
|
F: Fn(&S::Request) -> Option<tracing::Span> + Clone,
|
||||||
|
U: IntoServiceFactory<S>,
|
||||||
|
{
|
||||||
|
apply(
|
||||||
|
TracingTransform::new(make_span),
|
||||||
|
service_factory.into_factory(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod test {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
use std::cell::RefCell;
|
||||||
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
use std::sync::{Arc, RwLock};
|
||||||
|
|
||||||
|
use actix_service::{fn_factory, fn_service};
|
||||||
|
use slab::Slab;
|
||||||
|
use tracing::{span, Event, Level, Metadata, Subscriber};
|
||||||
|
|
||||||
|
thread_local! {
|
||||||
|
static SPAN: RefCell<Vec<span::Id>> = RefCell::new(Vec::new());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct Stats {
|
||||||
|
entered_spans: BTreeSet<u64>,
|
||||||
|
exited_spans: BTreeSet<u64>,
|
||||||
|
events_count: BTreeMap<u64, usize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct Inner {
|
||||||
|
spans: Slab<&'static Metadata<'static>>,
|
||||||
|
stats: Stats,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Default)]
|
||||||
|
struct TestSubscriber {
|
||||||
|
inner: Arc<RwLock<Inner>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Subscriber for TestSubscriber {
|
||||||
|
fn enabled(&self, _metadata: &Metadata<'_>) -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
fn new_span(&self, span: &span::Attributes<'_>) -> span::Id {
|
||||||
|
let id = self.inner.write().unwrap().spans.insert(span.metadata());
|
||||||
|
span::Id::from_u64(id as u64 + 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn record(&self, _span: &span::Id, _values: &span::Record<'_>) {}
|
||||||
|
|
||||||
|
fn record_follows_from(&self, _span: &span::Id, _follows: &span::Id) {}
|
||||||
|
|
||||||
|
fn event(&self, event: &Event<'_>) {
|
||||||
|
let id = event
|
||||||
|
.parent()
|
||||||
|
.cloned()
|
||||||
|
.or_else(|| SPAN.with(|current_span| current_span.borrow().last().cloned()))
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
*self
|
||||||
|
.inner
|
||||||
|
.write()
|
||||||
|
.unwrap()
|
||||||
|
.stats
|
||||||
|
.events_count
|
||||||
|
.entry(id.into_u64())
|
||||||
|
.or_insert(0) += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn enter(&self, span: &span::Id) {
|
||||||
|
self.inner
|
||||||
|
.write()
|
||||||
|
.unwrap()
|
||||||
|
.stats
|
||||||
|
.entered_spans
|
||||||
|
.insert(span.into_u64());
|
||||||
|
|
||||||
|
SPAN.with(|current_span| {
|
||||||
|
current_span.borrow_mut().push(span.clone());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn exit(&self, span: &span::Id) {
|
||||||
|
self.inner
|
||||||
|
.write()
|
||||||
|
.unwrap()
|
||||||
|
.stats
|
||||||
|
.exited_spans
|
||||||
|
.insert(span.into_u64());
|
||||||
|
|
||||||
|
// we are guaranteed that on any given thread, spans are exited in reverse order
|
||||||
|
SPAN.with(|current_span| {
|
||||||
|
let leaving = current_span
|
||||||
|
.borrow_mut()
|
||||||
|
.pop()
|
||||||
|
.expect("told to exit span when not in span");
|
||||||
|
assert_eq!(
|
||||||
|
&leaving, span,
|
||||||
|
"told to exit span that was not most recently entered"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix_rt::test]
|
||||||
|
async fn service_call() {
|
||||||
|
let service_factory = fn_factory(|| {
|
||||||
|
ok::<_, ()>(fn_service(|req: &'static str| {
|
||||||
|
tracing::event!(Level::TRACE, "It's happening - {}!", req);
|
||||||
|
ok::<_, ()>(())
|
||||||
|
}))
|
||||||
|
});
|
||||||
|
|
||||||
|
let subscriber = TestSubscriber::default();
|
||||||
|
let _guard = tracing::subscriber::set_default(subscriber.clone());
|
||||||
|
|
||||||
|
let span_svc = span!(Level::TRACE, "span_svc");
|
||||||
|
let trace_service_factory = trace(service_factory, |_: &&str| Some(span_svc.clone()));
|
||||||
|
let mut service = trace_service_factory.new_service(()).await.unwrap();
|
||||||
|
service.call("boo").await.unwrap();
|
||||||
|
|
||||||
|
let id = span_svc.id().unwrap().into_u64();
|
||||||
|
assert!(subscriber
|
||||||
|
.inner
|
||||||
|
.read()
|
||||||
|
.unwrap()
|
||||||
|
.stats
|
||||||
|
.entered_spans
|
||||||
|
.contains(&id));
|
||||||
|
assert!(subscriber
|
||||||
|
.inner
|
||||||
|
.read()
|
||||||
|
.unwrap()
|
||||||
|
.stats
|
||||||
|
.exited_spans
|
||||||
|
.contains(&id));
|
||||||
|
assert_eq!(subscriber.inner.read().unwrap().stats.events_count[&id], 1);
|
||||||
|
}
|
||||||
|
}
|
@@ -1,5 +1,37 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [1.0.6] - 2020-01-08
|
||||||
|
|
||||||
|
* Add `Clone` impl for `condition::Waiter`
|
||||||
|
|
||||||
|
## [1.0.5] - 2020-01-08
|
||||||
|
|
||||||
|
* Add `Condition` type.
|
||||||
|
|
||||||
|
* Add `Pool` of one-shot's.
|
||||||
|
|
||||||
|
## [1.0.4] - 2019-12-20
|
||||||
|
|
||||||
|
* Add methods to check `LocalWaker` registration state.
|
||||||
|
|
||||||
|
## [1.0.3] - 2019-12-11
|
||||||
|
|
||||||
|
* Revert InOrder service changes
|
||||||
|
|
||||||
|
## [1.0.2] - 2019-12-11
|
||||||
|
|
||||||
|
* Allow to create `framed::Dispatcher` with custom `mpsc::Receiver`
|
||||||
|
|
||||||
|
* Add `oneshot::Sender::is_canceled()` method
|
||||||
|
|
||||||
|
## [1.0.1] - 2019-12-11
|
||||||
|
|
||||||
|
* Optimize InOrder service
|
||||||
|
|
||||||
|
## [1.0.0] - 2019-12-11
|
||||||
|
|
||||||
|
* Simplify oneshot and mpsc implementations
|
||||||
|
|
||||||
## [1.0.0-alpha.3] - 2019-12-07
|
## [1.0.0-alpha.3] - 2019-12-07
|
||||||
|
|
||||||
* Migrate to tokio 0.2
|
* Migrate to tokio 0.2
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-utils"
|
name = "actix-utils"
|
||||||
version = "1.0.0-alpha.3"
|
version = "1.0.6"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix utils - various actix net related services"
|
description = "Actix utils - various actix net related services"
|
||||||
keywords = ["network", "framework", "async", "futures"]
|
keywords = ["network", "framework", "async", "futures"]
|
||||||
@@ -9,20 +9,22 @@ repository = "https://github.com/actix/actix-net.git"
|
|||||||
documentation = "https://docs.rs/actix-utils/"
|
documentation = "https://docs.rs/actix-utils/"
|
||||||
categories = ["network-programming", "asynchronous"]
|
categories = ["network-programming", "asynchronous"]
|
||||||
license = "MIT/Apache-2.0"
|
license = "MIT/Apache-2.0"
|
||||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
workspace = ".."
|
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
name = "actix_utils"
|
name = "actix_utils"
|
||||||
path = "src/lib.rs"
|
path = "src/lib.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-service = "1.0.0-alpha.3"
|
actix-service = "1.0.1"
|
||||||
actix-rt = "1.0.0-alpha.3"
|
actix-rt = "1.0.0"
|
||||||
actix-codec = "0.2.0-alpha.3"
|
actix-codec = "0.2.0"
|
||||||
bytes = "0.5.2"
|
bitflags = "1.2"
|
||||||
either = "1.5.2"
|
bytes = "0.5.3"
|
||||||
futures = "0.3.1"
|
either = "1.5.3"
|
||||||
|
futures-channel = { version = "0.3.4", default-features = false }
|
||||||
|
futures-sink = { version = "0.3.4", default-features = false }
|
||||||
|
futures-util = { version = "0.3.4", default-features = false }
|
||||||
pin-project = "0.4.6"
|
pin-project = "0.4.6"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
|
slab = "0.4"
|
||||||
|
@@ -2,16 +2,12 @@
|
|||||||
|
|
||||||
use std::cell::UnsafeCell;
|
use std::cell::UnsafeCell;
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
use std::rc::{Rc, Weak};
|
use std::rc::Rc;
|
||||||
|
|
||||||
pub(crate) struct Cell<T> {
|
pub(crate) struct Cell<T> {
|
||||||
pub(crate) inner: Rc<UnsafeCell<T>>,
|
pub(crate) inner: Rc<UnsafeCell<T>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) struct WeakCell<T> {
|
|
||||||
inner: Weak<UnsafeCell<T>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> Clone for Cell<T> {
|
impl<T> Clone for Cell<T> {
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
Self {
|
Self {
|
||||||
@@ -27,39 +23,26 @@ impl<T: fmt::Debug> fmt::Debug for Cell<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<T> Cell<T> {
|
impl<T> Cell<T> {
|
||||||
pub fn new(inner: T) -> Self {
|
pub(crate) fn new(inner: T) -> Self {
|
||||||
Self {
|
Self {
|
||||||
inner: Rc::new(UnsafeCell::new(inner)),
|
inner: Rc::new(UnsafeCell::new(inner)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn downgrade(&self) -> WeakCell<T> {
|
pub(crate) fn strong_count(&self) -> usize {
|
||||||
WeakCell {
|
Rc::strong_count(&self.inner)
|
||||||
inner: Rc::downgrade(&self.inner),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_ref(&self) -> &T {
|
pub(crate) fn get_ref(&self) -> &T {
|
||||||
unsafe { &*self.inner.as_ref().get() }
|
unsafe { &*self.inner.as_ref().get() }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_mut(&mut self) -> &mut T {
|
pub(crate) fn get_mut(&mut self) -> &mut T {
|
||||||
unsafe { &mut *self.inner.as_ref().get() }
|
unsafe { &mut *self.inner.as_ref().get() }
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> WeakCell<T> {
|
#[allow(clippy::mut_from_ref)]
|
||||||
pub fn upgrade(&self) -> Option<Cell<T>> {
|
pub(crate) unsafe fn get_mut_unsafe(&self) -> &mut T {
|
||||||
if let Some(inner) = self.inner.upgrade() {
|
&mut *self.inner.as_ref().get()
|
||||||
Some(Cell { inner })
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: fmt::Debug> fmt::Debug for WeakCell<T> {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
self.inner.fmt(f)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user