mirror of
https://github.com/fafhrd91/actix-net
synced 2025-08-13 11:58:23 +02:00
Compare commits
52 Commits
service-v1
...
server-v1.
Author | SHA1 | Date | |
---|---|---|---|
|
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 |
@@ -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
|
77
.github/workflows/linux.yml
vendored
Normal file
77
.github/workflows/linux.yml
vendored
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
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'
|
||||||
|
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'
|
||||||
|
uses: codecov/codecov-action@v1
|
||||||
|
with:
|
||||||
|
token: ${{ secrets.CODECOV_TOKEN }}
|
||||||
|
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
|
78
.github/workflows/main.yml
vendored
78
.github/workflows/main.yml
vendored
@@ -1,78 +0,0 @@
|
|||||||
name: CI
|
|
||||||
|
|
||||||
on: [push, pull_request]
|
|
||||||
|
|
||||||
env:
|
|
||||||
VCPKGRS_DYNAMIC: 1
|
|
||||||
|
|
||||||
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
|
|
||||||
arch: x64
|
|
||||||
- toolchain: x86_64-pc-windows-gnu
|
|
||||||
os: windows-latest
|
|
||||||
- toolchain: i686-pc-windows-msvc
|
|
||||||
os: windows-latest
|
|
||||||
arch: x86
|
|
||||||
- toolchain: x86_64-apple-darwin
|
|
||||||
os: macOS-latest
|
|
||||||
|
|
||||||
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: Install OpenSSL
|
|
||||||
if: matrix.toolchain == 'x86_64-pc-windows-msvc' || matrix.toolchain == 'i686-pc-windows-msvc'
|
|
||||||
run: |
|
|
||||||
vcpkg integrate install
|
|
||||||
vcpkg install openssl:${{ matrix.arch }}-windows
|
|
||||||
|
|
||||||
- name: check nightly
|
|
||||||
if: matrix.version == 'nightly'
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
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
|
|
||||||
if: matrix.toolchain != 'x86_64-pc-windows-gnu'
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: test
|
|
||||||
args: --all --all-features -- --nocapture
|
|
||||||
|
|
||||||
- name: tests on x86_64-pc-windows-gnu
|
|
||||||
if: matrix.toolchain == 'x86_64-pc-windows-gnu'
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: test
|
|
||||||
args: --all -- --nocapture
|
|
54
.github/workflows/windows-mingw.yml
vendored
Normal file
54
.github/workflows/windows-mingw.yml
vendored
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
name: CI (Windows-mingw)
|
||||||
|
|
||||||
|
on: [push, pull_request]
|
||||||
|
|
||||||
|
env:
|
||||||
|
OPENSSL_DIR: d:\a\_temp\msys\msys64\usr
|
||||||
|
|
||||||
|
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 OpenSSL
|
||||||
|
run: |
|
||||||
|
msys2do pacman --noconfirm -S openssl-devel pkg-config
|
||||||
|
|
||||||
|
- name: Copy and check libs
|
||||||
|
run: |
|
||||||
|
Copy-Item d:\a\_temp\msys\msys64\usr\lib\libssl.dll.a d:\a\_temp\msys\msys64\usr\lib\libssl.dll
|
||||||
|
Copy-Item d:\a\_temp\msys\msys64\usr\lib\libcrypto.dll.a d:\a\_temp\msys\msys64\usr\lib\libcrypto.dll
|
||||||
|
Get-ChildItem d:\a\_temp\msys\msys64\usr\lib
|
||||||
|
Get-ChildItem d:\a\_temp\msys\msys64\usr
|
||||||
|
|
||||||
|
- 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
|
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" }
|
||||||
|
11
README.md
11
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)
|
||||||
|
@@ -1,5 +1,9 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [1.0.2] - 2020-01-15
|
||||||
|
|
||||||
|
* Fix actix-service 1.0.3 compatibility
|
||||||
|
|
||||||
## [1.0.1] - 2019-12-15
|
## [1.0.1] - 2019-12-15
|
||||||
|
|
||||||
* Fix trust-dns-resolver compilation
|
* Fix trust-dns-resolver compilation
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-connect"
|
name = "actix-connect"
|
||||||
version = "1.0.1"
|
version = "1.0.2"
|
||||||
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"]
|
||||||
@@ -10,7 +10,6 @@ documentation = "https://docs.rs/actix-connect/"
|
|||||||
categories = ["network-programming", "asynchronous"]
|
categories = ["network-programming", "asynchronous"]
|
||||||
license = "MIT/Apache-2.0"
|
license = "MIT/Apache-2.0"
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
workspace = ".."
|
|
||||||
|
|
||||||
[package.metadata.docs.rs]
|
[package.metadata.docs.rs]
|
||||||
features = ["openssl", "rustls", "uri"]
|
features = ["openssl", "rustls", "uri"]
|
||||||
@@ -32,12 +31,12 @@ rustls = ["rust-tls", "tokio-rustls", "webpki"]
|
|||||||
uri = ["http"]
|
uri = ["http"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-service = "1.0.0"
|
actix-service = "1.0.3"
|
||||||
actix-codec = "0.2.0"
|
actix-codec = "0.2.0"
|
||||||
actix-utils = "1.0.3"
|
actix-utils = "1.0.6"
|
||||||
actix-rt = "1.0.0"
|
actix-rt = "1.0.0"
|
||||||
derive_more = "0.99.2"
|
derive_more = "0.99.2"
|
||||||
either = "1.5.2"
|
either = "1.5.3"
|
||||||
futures = "0.3.1"
|
futures = "0.3.1"
|
||||||
http = { version = "0.2.0", optional = true }
|
http = { version = "0.2.0", optional = true }
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
|
@@ -72,7 +72,7 @@ pub fn start_default_resolver() -> AsyncResolver {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// 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>,
|
||||||
|
@@ -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,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,5 +1,13 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [0.5.0] - 2019-12-29
|
||||||
|
|
||||||
|
* Simplify state management
|
||||||
|
|
||||||
|
* Allow to set custom output stream
|
||||||
|
|
||||||
|
* Removed disconnect callback
|
||||||
|
|
||||||
## [0.4.1] - 2019-12-11
|
## [0.4.1] - 2019-12-11
|
||||||
|
|
||||||
* Disconnect callback accepts owned state
|
* Disconnect callback accepts owned state
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-ioframe"
|
name = "actix-ioframe"
|
||||||
version = "0.4.1"
|
version = "0.5.0"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix framed service"
|
description = "Actix framed service"
|
||||||
keywords = ["network", "framework", "async", "futures"]
|
keywords = ["network", "framework", "async", "futures"]
|
||||||
@@ -10,19 +10,18 @@ documentation = "https://docs.rs/actix-ioframe/"
|
|||||||
categories = ["network-programming", "asynchronous"]
|
categories = ["network-programming", "asynchronous"]
|
||||||
license = "MIT/Apache-2.0"
|
license = "MIT/Apache-2.0"
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
workspace = ".."
|
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
name = "actix_ioframe"
|
name = "actix_ioframe"
|
||||||
path = "src/lib.rs"
|
path = "src/lib.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-service = "1.0.0"
|
actix-service = "1.0.1"
|
||||||
actix-codec = "0.2.0"
|
actix-codec = "0.2.0"
|
||||||
actix-utils = "1.0.1"
|
actix-utils = "1.0.4"
|
||||||
actix-rt = "1.0.0"
|
actix-rt = "1.0.0"
|
||||||
bytes = "0.5"
|
bytes = "0.5.3"
|
||||||
either = "1.5.2"
|
either = "1.5.3"
|
||||||
futures = "0.3.1"
|
futures = "0.3.1"
|
||||||
pin-project = "0.4.6"
|
pin-project = "0.4.6"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
|
@@ -3,17 +3,15 @@ use std::pin::Pin;
|
|||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
|
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
|
||||||
|
use actix_utils::mpsc::Receiver;
|
||||||
use futures::Stream;
|
use futures::Stream;
|
||||||
|
|
||||||
use crate::sink::Sink;
|
pub struct Connect<Io, Codec>
|
||||||
|
|
||||||
pub struct Connect<Io, Codec, St = ()>
|
|
||||||
where
|
where
|
||||||
Codec: Encoder + Decoder,
|
Codec: Encoder + Decoder,
|
||||||
{
|
{
|
||||||
io: Io,
|
io: Io,
|
||||||
sink: Sink<<Codec as Encoder>::Item>,
|
_t: PhantomData<Codec>,
|
||||||
_t: PhantomData<(St, Codec)>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<Io, Codec> Connect<Io, Codec>
|
impl<Io, Codec> Connect<Io, Codec>
|
||||||
@@ -21,36 +19,33 @@ where
|
|||||||
Io: AsyncRead + AsyncWrite,
|
Io: AsyncRead + AsyncWrite,
|
||||||
Codec: Encoder + Decoder,
|
Codec: Encoder + Decoder,
|
||||||
{
|
{
|
||||||
pub(crate) fn new(io: Io, sink: Sink<<Codec as Encoder>::Item>) -> Self {
|
pub(crate) fn new(io: Io) -> Self {
|
||||||
Self {
|
Self {
|
||||||
io,
|
io,
|
||||||
sink,
|
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn codec(self, codec: Codec) -> ConnectResult<Io, (), Codec> {
|
pub fn codec(
|
||||||
|
self,
|
||||||
|
codec: Codec,
|
||||||
|
) -> ConnectResult<Io, (), Codec, Receiver<<Codec as Encoder>::Item>> {
|
||||||
ConnectResult {
|
ConnectResult {
|
||||||
state: (),
|
state: (),
|
||||||
sink: self.sink,
|
out: None,
|
||||||
framed: Framed::new(self.io, codec),
|
framed: Framed::new(self.io, codec),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[pin_project::pin_project]
|
#[pin_project::pin_project]
|
||||||
pub struct ConnectResult<Io, St, Codec: Encoder + Decoder> {
|
pub struct ConnectResult<Io, St, Codec: Encoder + Decoder, Out> {
|
||||||
pub(crate) state: St,
|
pub(crate) state: St,
|
||||||
|
pub(crate) out: Option<Out>,
|
||||||
pub(crate) framed: Framed<Io, Codec>,
|
pub(crate) framed: Framed<Io, Codec>,
|
||||||
pub(crate) sink: Sink<<Codec as Encoder>::Item>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<Io, St, Codec: Encoder + Decoder> ConnectResult<Io, St, Codec> {
|
impl<Io, St, Codec: Encoder + Decoder, Out: Unpin> ConnectResult<Io, St, Codec, Out> {
|
||||||
#[inline]
|
|
||||||
pub fn sink(&self) -> &Sink<<Codec as Encoder>::Item> {
|
|
||||||
&self.sink
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn get_ref(&self) -> &Io {
|
pub fn get_ref(&self) -> &Io {
|
||||||
self.framed.get_ref()
|
self.framed.get_ref()
|
||||||
@@ -61,17 +56,28 @@ impl<Io, St, Codec: Encoder + Decoder> ConnectResult<Io, St, Codec> {
|
|||||||
self.framed.get_mut()
|
self.framed.get_mut()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn out<U>(self, out: U) -> ConnectResult<Io, St, Codec, U>
|
||||||
|
where
|
||||||
|
U: Stream<Item = <Codec as Encoder>::Item> + Unpin,
|
||||||
|
{
|
||||||
|
ConnectResult {
|
||||||
|
state: self.state,
|
||||||
|
framed: self.framed,
|
||||||
|
out: Some(out),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn state<S>(self, state: S) -> ConnectResult<Io, S, Codec> {
|
pub fn state<S>(self, state: S) -> ConnectResult<Io, S, Codec, Out> {
|
||||||
ConnectResult {
|
ConnectResult {
|
||||||
state,
|
state,
|
||||||
framed: self.framed,
|
framed: self.framed,
|
||||||
sink: self.sink,
|
out: self.out,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<Io, St, Codec> Stream for ConnectResult<Io, St, Codec>
|
impl<Io, St, Codec, Out> Stream for ConnectResult<Io, St, Codec, Out>
|
||||||
where
|
where
|
||||||
Io: AsyncRead + AsyncWrite,
|
Io: AsyncRead + AsyncWrite,
|
||||||
Codec: Encoder + Decoder,
|
Codec: Encoder + Decoder,
|
||||||
@@ -83,7 +89,8 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<Io, St, Codec> futures::Sink<<Codec as Encoder>::Item> for ConnectResult<Io, St, Codec>
|
impl<Io, St, Codec, Out> futures::Sink<<Codec as Encoder>::Item>
|
||||||
|
for ConnectResult<Io, St, Codec, Out>
|
||||||
where
|
where
|
||||||
Io: AsyncRead + AsyncWrite,
|
Io: AsyncRead + AsyncWrite,
|
||||||
Codec: Encoder + Decoder,
|
Codec: Encoder + Decoder,
|
||||||
|
@@ -1,81 +1,56 @@
|
|||||||
//! Framed dispatcher service and related utilities
|
//! Framed dispatcher service and related utilities
|
||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
use std::rc::Rc;
|
|
||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
|
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
|
||||||
use actix_service::{IntoService, Service};
|
use actix_service::Service;
|
||||||
use actix_utils::{mpsc, oneshot};
|
use actix_utils::mpsc;
|
||||||
use futures::{FutureExt, Stream};
|
use futures::Stream;
|
||||||
use log::debug;
|
use log::debug;
|
||||||
|
|
||||||
use crate::error::ServiceError;
|
use crate::error::ServiceError;
|
||||||
use crate::item::Item;
|
|
||||||
use crate::sink::Sink;
|
|
||||||
|
|
||||||
type Request<S, U> = Item<S, U>;
|
type Request<U> = <U as Decoder>::Item;
|
||||||
type Response<U> = <U as Encoder>::Item;
|
type Response<U> = <U as Encoder>::Item;
|
||||||
|
|
||||||
pub(crate) enum Message<T> {
|
|
||||||
Item(T),
|
|
||||||
WaitClose(oneshot::Sender<()>),
|
|
||||||
Close,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// FramedTransport - is a future that reads frames from Framed object
|
/// FramedTransport - is a future that reads frames from Framed object
|
||||||
/// and pass then to the service.
|
/// and pass then to the service.
|
||||||
#[pin_project::pin_project]
|
pub(crate) struct Dispatcher<S, T, U, Out>
|
||||||
pub(crate) struct Dispatcher<St, S, T, U>
|
|
||||||
where
|
where
|
||||||
St: Clone,
|
S: Service<Request = Request<U>, Response = Option<Response<U>>>,
|
||||||
S: Service<Request = Request<St, U>, Response = Option<Response<U>>>,
|
|
||||||
S::Error: 'static,
|
S::Error: 'static,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
T: AsyncRead + AsyncWrite,
|
T: AsyncRead + AsyncWrite,
|
||||||
U: Encoder + Decoder,
|
U: Encoder + Decoder,
|
||||||
<U as Encoder>::Item: 'static,
|
<U as Encoder>::Item: 'static,
|
||||||
<U as Encoder>::Error: std::fmt::Debug,
|
<U as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <U as Encoder>::Item> + Unpin,
|
||||||
{
|
{
|
||||||
service: S,
|
service: S,
|
||||||
sink: Sink<<U as Encoder>::Item>,
|
sink: Option<Out>,
|
||||||
state: St,
|
state: FramedState<S, U>,
|
||||||
dispatch_state: FramedState<S, U>,
|
|
||||||
framed: Framed<T, U>,
|
framed: Framed<T, U>,
|
||||||
rx: mpsc::Receiver<Result<Message<<U as Encoder>::Item>, S::Error>>,
|
rx: mpsc::Receiver<Result<<U as Encoder>::Item, S::Error>>,
|
||||||
tx: mpsc::Sender<Result<Message<<U as Encoder>::Item>, S::Error>>,
|
|
||||||
disconnect: Option<Rc<dyn Fn(St, bool)>>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<St, S, T, U> Dispatcher<St, S, T, U>
|
impl<S, T, U, Out> Dispatcher<S, T, U, Out>
|
||||||
where
|
where
|
||||||
St: Clone,
|
S: Service<Request = Request<U>, Response = Option<Response<U>>>,
|
||||||
S: Service<Request = Request<St, U>, Response = Option<Response<U>>>,
|
|
||||||
S::Error: 'static,
|
S::Error: 'static,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
T: AsyncRead + AsyncWrite,
|
T: AsyncRead + AsyncWrite,
|
||||||
U: Decoder + Encoder,
|
U: Decoder + Encoder,
|
||||||
<U as Encoder>::Item: 'static,
|
<U as Encoder>::Item: 'static,
|
||||||
<U as Encoder>::Error: std::fmt::Debug,
|
<U as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <U as Encoder>::Item> + Unpin,
|
||||||
{
|
{
|
||||||
pub(crate) fn new<F: IntoService<S>>(
|
pub(crate) fn new(framed: Framed<T, U>, service: S, sink: Option<Out>) -> Self {
|
||||||
framed: Framed<T, U>,
|
|
||||||
state: St,
|
|
||||||
service: F,
|
|
||||||
sink: Sink<<U as Encoder>::Item>,
|
|
||||||
rx: mpsc::Receiver<Result<Message<<U as Encoder>::Item>, S::Error>>,
|
|
||||||
disconnect: Option<Rc<dyn Fn(St, bool)>>,
|
|
||||||
) -> Self {
|
|
||||||
let tx = rx.sender();
|
|
||||||
|
|
||||||
Dispatcher {
|
Dispatcher {
|
||||||
framed,
|
|
||||||
state,
|
|
||||||
sink,
|
sink,
|
||||||
disconnect,
|
service,
|
||||||
rx,
|
framed,
|
||||||
tx,
|
rx: mpsc::channel().1,
|
||||||
service: service.into_service(),
|
state: FramedState::Processing,
|
||||||
dispatch_state: FramedState::Processing,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -84,33 +59,11 @@ enum FramedState<S: Service, U: Encoder + Decoder> {
|
|||||||
Processing,
|
Processing,
|
||||||
Error(ServiceError<S::Error, U>),
|
Error(ServiceError<S::Error, U>),
|
||||||
FramedError(ServiceError<S::Error, U>),
|
FramedError(ServiceError<S::Error, U>),
|
||||||
FlushAndStop(Vec<oneshot::Sender<()>>),
|
FlushAndStop,
|
||||||
Stopping,
|
Stopping,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S: Service, U: Encoder + Decoder> FramedState<S, U> {
|
impl<S: Service, U: Encoder + Decoder> FramedState<S, U> {
|
||||||
fn stop(&mut self, tx: Option<oneshot::Sender<()>>) {
|
|
||||||
match self {
|
|
||||||
FramedState::FlushAndStop(ref mut vec) => {
|
|
||||||
if let Some(tx) = tx {
|
|
||||||
vec.push(tx)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
FramedState::Processing => {
|
|
||||||
*self = FramedState::FlushAndStop(if let Some(tx) = tx {
|
|
||||||
vec![tx]
|
|
||||||
} else {
|
|
||||||
Vec::new()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
FramedState::Error(_) | FramedState::FramedError(_) | FramedState::Stopping => {
|
|
||||||
if let Some(tx) = tx {
|
|
||||||
let _ = tx.send(());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn take_error(&mut self) -> ServiceError<S::Error, U> {
|
fn take_error(&mut self) -> ServiceError<S::Error, U> {
|
||||||
match std::mem::replace(self, FramedState::Processing) {
|
match std::mem::replace(self, FramedState::Processing) {
|
||||||
FramedState::Error(err) => err,
|
FramedState::Error(err) => err,
|
||||||
@@ -126,16 +79,16 @@ impl<S: Service, U: Encoder + Decoder> FramedState<S, U> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<St, S, T, U> Dispatcher<St, S, T, U>
|
impl<S, T, U, Out> Dispatcher<S, T, U, Out>
|
||||||
where
|
where
|
||||||
St: Clone,
|
S: Service<Request = Request<U>, Response = Option<Response<U>>>,
|
||||||
S: Service<Request = Request<St, U>, Response = Option<Response<U>>>,
|
|
||||||
S::Error: 'static,
|
S::Error: 'static,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
T: AsyncRead + AsyncWrite,
|
T: AsyncRead + AsyncWrite,
|
||||||
U: Decoder + Encoder,
|
U: Decoder + Encoder,
|
||||||
<U as Encoder>::Item: 'static,
|
<U as Encoder>::Item: 'static,
|
||||||
<U as Encoder>::Error: std::fmt::Debug,
|
<U as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <U as Encoder>::Item> + Unpin,
|
||||||
{
|
{
|
||||||
fn poll_read(&mut self, cx: &mut Context<'_>) -> bool {
|
fn poll_read(&mut self, cx: &mut Context<'_>) -> bool {
|
||||||
loop {
|
loop {
|
||||||
@@ -144,35 +97,32 @@ where
|
|||||||
let item = match self.framed.next_item(cx) {
|
let item = match self.framed.next_item(cx) {
|
||||||
Poll::Ready(Some(Ok(el))) => el,
|
Poll::Ready(Some(Ok(el))) => el,
|
||||||
Poll::Ready(Some(Err(err))) => {
|
Poll::Ready(Some(Err(err))) => {
|
||||||
self.dispatch_state =
|
self.state = FramedState::FramedError(ServiceError::Decoder(err));
|
||||||
FramedState::FramedError(ServiceError::Decoder(err));
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
Poll::Pending => return false,
|
Poll::Pending => return false,
|
||||||
Poll::Ready(None) => {
|
Poll::Ready(None) => {
|
||||||
log::trace!("Client disconnected");
|
log::trace!("Client disconnected");
|
||||||
self.dispatch_state = FramedState::Stopping;
|
self.state = FramedState::Stopping;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let tx = self.tx.clone();
|
let tx = self.rx.sender();
|
||||||
actix_rt::spawn(
|
let fut = self.service.call(item);
|
||||||
self.service
|
actix_rt::spawn(async move {
|
||||||
.call(Item::new(self.state.clone(), self.sink.clone(), item))
|
let item = fut.await;
|
||||||
.map(move |item| {
|
let item = match item {
|
||||||
let item = match item {
|
Ok(Some(item)) => Ok(item),
|
||||||
Ok(Some(item)) => Ok(Message::Item(item)),
|
Ok(None) => return,
|
||||||
Ok(None) => return,
|
Err(err) => Err(err),
|
||||||
Err(err) => Err(err),
|
};
|
||||||
};
|
let _ = tx.send(item);
|
||||||
let _ = tx.send(item);
|
});
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
Poll::Pending => return false,
|
Poll::Pending => return false,
|
||||||
Poll::Ready(Err(err)) => {
|
Poll::Ready(Err(err)) => {
|
||||||
self.dispatch_state = FramedState::Error(ServiceError::Service(err));
|
self.state = FramedState::Error(ServiceError::Service(err));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -184,27 +134,39 @@ where
|
|||||||
loop {
|
loop {
|
||||||
while !self.framed.is_write_buf_full() {
|
while !self.framed.is_write_buf_full() {
|
||||||
match Pin::new(&mut self.rx).poll_next(cx) {
|
match Pin::new(&mut self.rx).poll_next(cx) {
|
||||||
Poll::Ready(Some(Ok(Message::Item(msg)))) => {
|
Poll::Ready(Some(Ok(msg))) => {
|
||||||
if let Err(err) = self.framed.write(msg) {
|
if let Err(err) = self.framed.write(msg) {
|
||||||
self.dispatch_state =
|
self.state = FramedState::FramedError(ServiceError::Encoder(err));
|
||||||
FramedState::FramedError(ServiceError::Encoder(err));
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
continue;
|
||||||
Poll::Ready(Some(Ok(Message::Close))) => {
|
|
||||||
self.dispatch_state.stop(None);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
Poll::Ready(Some(Ok(Message::WaitClose(tx)))) => {
|
|
||||||
self.dispatch_state.stop(Some(tx));
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
Poll::Ready(Some(Err(err))) => {
|
Poll::Ready(Some(Err(err))) => {
|
||||||
self.dispatch_state = FramedState::Error(ServiceError::Service(err));
|
self.state = FramedState::Error(ServiceError::Service(err));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
Poll::Ready(None) | Poll::Pending => break,
|
Poll::Ready(None) | Poll::Pending => (),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if self.sink.is_some() {
|
||||||
|
match Pin::new(self.sink.as_mut().unwrap()).poll_next(cx) {
|
||||||
|
Poll::Ready(Some(msg)) => {
|
||||||
|
if let Err(err) = self.framed.write(msg) {
|
||||||
|
self.state =
|
||||||
|
FramedState::FramedError(ServiceError::Encoder(err));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Poll::Ready(None) => {
|
||||||
|
let _ = self.sink.take();
|
||||||
|
self.state = FramedState::FlushAndStop;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
Poll::Pending => (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
if !self.framed.is_write_buf_empty() {
|
if !self.framed.is_write_buf_empty() {
|
||||||
@@ -213,8 +175,7 @@ where
|
|||||||
Poll::Ready(Ok(_)) => (),
|
Poll::Ready(Ok(_)) => (),
|
||||||
Poll::Ready(Err(err)) => {
|
Poll::Ready(Err(err)) => {
|
||||||
debug!("Error sending data: {:?}", err);
|
debug!("Error sending data: {:?}", err);
|
||||||
self.dispatch_state =
|
self.state = FramedState::FramedError(ServiceError::Encoder(err));
|
||||||
FramedState::FramedError(ServiceError::Encoder(err));
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -229,14 +190,16 @@ where
|
|||||||
&mut self,
|
&mut self,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Poll<Result<(), ServiceError<S::Error, U>>> {
|
) -> Poll<Result<(), ServiceError<S::Error, U>>> {
|
||||||
match self.dispatch_state {
|
match self.state {
|
||||||
FramedState::Processing => {
|
FramedState::Processing => loop {
|
||||||
if self.poll_read(cx) || self.poll_write(cx) {
|
let read = self.poll_read(cx);
|
||||||
self.poll(cx)
|
let write = self.poll_write(cx);
|
||||||
|
if read || write {
|
||||||
|
continue;
|
||||||
} else {
|
} else {
|
||||||
Poll::Pending
|
return Poll::Pending;
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
FramedState::Error(_) => {
|
FramedState::Error(_) => {
|
||||||
// flush write buffer
|
// flush write buffer
|
||||||
if !self.framed.is_write_buf_empty() {
|
if !self.framed.is_write_buf_empty() {
|
||||||
@@ -244,12 +207,21 @@ where
|
|||||||
return Poll::Pending;
|
return Poll::Pending;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if let Some(ref disconnect) = self.disconnect {
|
Poll::Ready(Err(self.state.take_error()))
|
||||||
(&*disconnect)(self.state.clone(), true);
|
|
||||||
}
|
|
||||||
Poll::Ready(Err(self.dispatch_state.take_error()))
|
|
||||||
}
|
}
|
||||||
FramedState::FlushAndStop(ref mut vec) => {
|
FramedState::FlushAndStop => {
|
||||||
|
// drain service responses
|
||||||
|
match Pin::new(&mut self.rx).poll_next(cx) {
|
||||||
|
Poll::Ready(Some(Ok(msg))) => {
|
||||||
|
if self.framed.write(msg).is_err() {
|
||||||
|
return Poll::Ready(Ok(()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Poll::Ready(Some(Err(_))) => return Poll::Ready(Ok(())),
|
||||||
|
Poll::Ready(None) | Poll::Pending => (),
|
||||||
|
}
|
||||||
|
|
||||||
|
// flush io
|
||||||
if !self.framed.is_write_buf_empty() {
|
if !self.framed.is_write_buf_empty() {
|
||||||
match self.framed.flush(cx) {
|
match self.framed.flush(cx) {
|
||||||
Poll::Ready(Err(err)) => {
|
Poll::Ready(Err(err)) => {
|
||||||
@@ -261,26 +233,10 @@ where
|
|||||||
Poll::Ready(_) => (),
|
Poll::Ready(_) => (),
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
for tx in vec.drain(..) {
|
|
||||||
let _ = tx.send(());
|
|
||||||
}
|
|
||||||
if let Some(ref disconnect) = self.disconnect {
|
|
||||||
(&*disconnect)(self.state.clone(), false);
|
|
||||||
}
|
|
||||||
Poll::Ready(Ok(()))
|
|
||||||
}
|
|
||||||
FramedState::FramedError(_) => {
|
|
||||||
if let Some(ref disconnect) = self.disconnect {
|
|
||||||
(&*disconnect)(self.state.clone(), true);
|
|
||||||
}
|
|
||||||
Poll::Ready(Err(self.dispatch_state.take_framed_error()))
|
|
||||||
}
|
|
||||||
FramedState::Stopping => {
|
|
||||||
if let Some(ref disconnect) = self.disconnect {
|
|
||||||
(&*disconnect)(self.state.clone(), false);
|
|
||||||
}
|
|
||||||
Poll::Ready(Ok(()))
|
Poll::Ready(Ok(()))
|
||||||
}
|
}
|
||||||
|
FramedState::FramedError(_) => Poll::Ready(Err(self.state.take_framed_error())),
|
||||||
|
FramedState::Stopping => Poll::Ready(Ok(())),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,82 +0,0 @@
|
|||||||
use std::fmt;
|
|
||||||
use std::ops::{Deref, DerefMut};
|
|
||||||
|
|
||||||
use actix_codec::{Decoder, Encoder};
|
|
||||||
|
|
||||||
use crate::sink::Sink;
|
|
||||||
|
|
||||||
pub struct Item<St, Codec: Encoder + Decoder> {
|
|
||||||
state: St,
|
|
||||||
sink: Sink<<Codec as Encoder>::Item>,
|
|
||||||
item: <Codec as Decoder>::Item,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<St, Codec> Item<St, Codec>
|
|
||||||
where
|
|
||||||
Codec: Encoder + Decoder,
|
|
||||||
{
|
|
||||||
pub(crate) fn new(
|
|
||||||
state: St,
|
|
||||||
sink: Sink<<Codec as Encoder>::Item>,
|
|
||||||
item: <Codec as Decoder>::Item,
|
|
||||||
) -> Self {
|
|
||||||
Item { state, sink, item }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn state(&self) -> &St {
|
|
||||||
&self.state
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn state_mut(&mut self) -> &mut St {
|
|
||||||
&mut self.state
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn sink(&self) -> &Sink<<Codec as Encoder>::Item> {
|
|
||||||
&self.sink
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn into_inner(self) -> <Codec as Decoder>::Item {
|
|
||||||
self.item
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn into_parts(self) -> (St, Sink<<Codec as Encoder>::Item>, <Codec as Decoder>::Item) {
|
|
||||||
(self.state, self.sink, self.item)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<St, Codec> Deref for Item<St, Codec>
|
|
||||||
where
|
|
||||||
Codec: Encoder + Decoder,
|
|
||||||
{
|
|
||||||
type Target = <Codec as Decoder>::Item;
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn deref(&self) -> &<Codec as Decoder>::Item {
|
|
||||||
&self.item
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<St, Codec> DerefMut for Item<St, Codec>
|
|
||||||
where
|
|
||||||
Codec: Encoder + Decoder,
|
|
||||||
{
|
|
||||||
#[inline]
|
|
||||||
fn deref_mut(&mut self) -> &mut <Codec as Decoder>::Item {
|
|
||||||
&mut self.item
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<St, Codec> fmt::Debug for Item<St, Codec>
|
|
||||||
where
|
|
||||||
Codec: Encoder + Decoder,
|
|
||||||
<Codec as Decoder>::Item: fmt::Debug,
|
|
||||||
{
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
f.debug_tuple("Item").field(&self.item).finish()
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,15 +1,11 @@
|
|||||||
#![deny(rust_2018_idioms, warnings)]
|
// #![deny(rust_2018_idioms, warnings)]
|
||||||
#![allow(clippy::type_complexity, clippy::too_many_arguments)]
|
#![allow(clippy::type_complexity, clippy::too_many_arguments)]
|
||||||
|
|
||||||
mod connect;
|
mod connect;
|
||||||
mod dispatcher;
|
mod dispatcher;
|
||||||
mod error;
|
mod error;
|
||||||
mod item;
|
|
||||||
mod service;
|
mod service;
|
||||||
mod sink;
|
|
||||||
|
|
||||||
pub use self::connect::{Connect, ConnectResult};
|
pub use self::connect::{Connect, ConnectResult};
|
||||||
pub use self::error::ServiceError;
|
pub use self::error::ServiceError;
|
||||||
pub use self::item::Item;
|
pub use self::service::{Builder, FactoryBuilder};
|
||||||
pub use self::service::{Builder, NewServiceBuilder, ServiceBuilder};
|
|
||||||
pub use self::sink::Sink;
|
|
||||||
|
@@ -4,108 +4,57 @@ use std::pin::Pin;
|
|||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder};
|
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
|
||||||
use actix_service::{IntoService, IntoServiceFactory, Service, ServiceFactory};
|
use actix_service::{IntoService, IntoServiceFactory, Service, ServiceFactory};
|
||||||
use actix_utils::mpsc;
|
|
||||||
use either::Either;
|
use either::Either;
|
||||||
use futures::future::{FutureExt, LocalBoxFuture};
|
use futures::{ready, Stream};
|
||||||
use pin_project::project;
|
use pin_project::project;
|
||||||
|
|
||||||
use crate::connect::{Connect, ConnectResult};
|
use crate::connect::{Connect, ConnectResult};
|
||||||
use crate::dispatcher::{Dispatcher, Message};
|
use crate::dispatcher::Dispatcher;
|
||||||
use crate::error::ServiceError;
|
use crate::error::ServiceError;
|
||||||
use crate::item::Item;
|
|
||||||
use crate::sink::Sink;
|
|
||||||
|
|
||||||
type RequestItem<S, U> = Item<S, U>;
|
type RequestItem<U> = <U as Decoder>::Item;
|
||||||
type ResponseItem<U> = Option<<U as Encoder>::Item>;
|
type ResponseItem<U> = Option<<U as Encoder>::Item>;
|
||||||
type ServiceResult<U, E> = Result<Message<<U as Encoder>::Item>, E>;
|
|
||||||
|
|
||||||
/// Service builder - structure that follows the builder pattern
|
/// Service builder - structure that follows the builder pattern
|
||||||
/// for building instances for framed services.
|
/// for building instances for framed services.
|
||||||
pub struct Builder<St, Codec>(PhantomData<(St, Codec)>);
|
pub struct Builder<St, C, Io, Codec, Out> {
|
||||||
|
|
||||||
impl<St: Clone, Codec> Default for Builder<St, Codec> {
|
|
||||||
fn default() -> Builder<St, Codec> {
|
|
||||||
Builder::new()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<St: Clone, Codec> Builder<St, Codec> {
|
|
||||||
pub fn new() -> Builder<St, Codec> {
|
|
||||||
Builder(PhantomData)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Construct framed handler service with specified connect service
|
|
||||||
pub fn service<Io, C, F>(self, connect: F) -> ServiceBuilder<St, C, Io, Codec>
|
|
||||||
where
|
|
||||||
F: IntoService<C>,
|
|
||||||
Io: AsyncRead + AsyncWrite,
|
|
||||||
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec>>,
|
|
||||||
Codec: Decoder + Encoder,
|
|
||||||
{
|
|
||||||
ServiceBuilder {
|
|
||||||
connect: connect.into_service(),
|
|
||||||
disconnect: None,
|
|
||||||
_t: PhantomData,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Construct framed handler new service with specified connect service
|
|
||||||
pub fn factory<Io, C, F>(self, connect: F) -> NewServiceBuilder<St, C, Io, Codec>
|
|
||||||
where
|
|
||||||
F: IntoServiceFactory<C>,
|
|
||||||
Io: AsyncRead + AsyncWrite,
|
|
||||||
C: ServiceFactory<
|
|
||||||
Config = (),
|
|
||||||
Request = Connect<Io, Codec>,
|
|
||||||
Response = ConnectResult<Io, St, Codec>,
|
|
||||||
>,
|
|
||||||
C::Error: 'static,
|
|
||||||
C::Future: 'static,
|
|
||||||
Codec: Decoder + Encoder,
|
|
||||||
{
|
|
||||||
NewServiceBuilder {
|
|
||||||
connect: connect.into_factory(),
|
|
||||||
disconnect: None,
|
|
||||||
_t: PhantomData,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct ServiceBuilder<St, C, Io, Codec> {
|
|
||||||
connect: C,
|
connect: C,
|
||||||
disconnect: Option<Rc<dyn Fn(St, bool)>>,
|
_t: PhantomData<(St, Io, Codec, Out)>,
|
||||||
_t: PhantomData<(St, Io, Codec)>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<St, C, Io, Codec> ServiceBuilder<St, C, Io, Codec>
|
impl<St, C, Io, Codec, Out> Builder<St, C, Io, Codec, Out>
|
||||||
where
|
where
|
||||||
St: Clone,
|
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec, Out>>,
|
||||||
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec>>,
|
|
||||||
Io: AsyncRead + AsyncWrite,
|
Io: AsyncRead + AsyncWrite,
|
||||||
Codec: Decoder + Encoder,
|
Codec: Decoder + Encoder,
|
||||||
<Codec as Encoder>::Item: 'static,
|
<Codec as Encoder>::Item: 'static,
|
||||||
<Codec as Encoder>::Error: std::fmt::Debug,
|
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
|
||||||
{
|
{
|
||||||
/// Callback to execute on disconnect
|
/// Construct framed handler service with specified connect service
|
||||||
///
|
pub fn new<F>(connect: F) -> Builder<St, C, Io, Codec, Out>
|
||||||
/// Second parameter indicates error occured during disconnect.
|
|
||||||
pub fn disconnect<F, Out>(mut self, disconnect: F) -> Self
|
|
||||||
where
|
where
|
||||||
F: Fn(St, bool) + 'static,
|
F: IntoService<C>,
|
||||||
|
Io: AsyncRead + AsyncWrite,
|
||||||
|
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec, Out>>,
|
||||||
|
Codec: Decoder + Encoder,
|
||||||
|
Out: Stream<Item = <Codec as Encoder>::Item>,
|
||||||
{
|
{
|
||||||
self.disconnect = Some(Rc::new(disconnect));
|
Builder {
|
||||||
self
|
connect: connect.into_service(),
|
||||||
|
_t: PhantomData,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Provide stream items handler service and construct service factory.
|
/// Provide stream items handler service and construct service factory.
|
||||||
pub fn finish<F, T>(self, service: F) -> FramedServiceImpl<St, C, T, Io, Codec>
|
pub fn build<F, T>(self, service: F) -> FramedServiceImpl<St, C, T, Io, Codec, Out>
|
||||||
where
|
where
|
||||||
F: IntoServiceFactory<T>,
|
F: IntoServiceFactory<T>,
|
||||||
T: ServiceFactory<
|
T: ServiceFactory<
|
||||||
Config = St,
|
Config = St,
|
||||||
Request = RequestItem<St, Codec>,
|
Request = RequestItem<Codec>,
|
||||||
Response = ResponseItem<Codec>,
|
Response = ResponseItem<Codec>,
|
||||||
Error = C::Error,
|
Error = C::Error,
|
||||||
InitError = C::Error,
|
InitError = C::Error,
|
||||||
@@ -114,211 +63,261 @@ where
|
|||||||
FramedServiceImpl {
|
FramedServiceImpl {
|
||||||
connect: self.connect,
|
connect: self.connect,
|
||||||
handler: Rc::new(service.into_factory()),
|
handler: Rc::new(service.into_factory()),
|
||||||
disconnect: self.disconnect.clone(),
|
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct NewServiceBuilder<St, C, Io, Codec> {
|
/// Service builder - structure that follows the builder pattern
|
||||||
|
/// for building instances for framed services.
|
||||||
|
pub struct FactoryBuilder<St, C, Io, Codec, Out> {
|
||||||
connect: C,
|
connect: C,
|
||||||
disconnect: Option<Rc<dyn Fn(St, bool)>>,
|
_t: PhantomData<(St, Io, Codec, Out)>,
|
||||||
_t: PhantomData<(St, Io, Codec)>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<St, C, Io, Codec> NewServiceBuilder<St, C, Io, Codec>
|
impl<St, C, Io, Codec, Out> FactoryBuilder<St, C, Io, Codec, Out>
|
||||||
where
|
where
|
||||||
St: Clone,
|
|
||||||
Io: AsyncRead + AsyncWrite,
|
Io: AsyncRead + AsyncWrite,
|
||||||
C: ServiceFactory<
|
C: ServiceFactory<
|
||||||
Config = (),
|
Config = (),
|
||||||
Request = Connect<Io, Codec>,
|
Request = Connect<Io, Codec>,
|
||||||
Response = ConnectResult<Io, St, Codec>,
|
Response = ConnectResult<Io, St, Codec, Out>,
|
||||||
>,
|
>,
|
||||||
C::Error: 'static,
|
|
||||||
C::Future: 'static,
|
|
||||||
Codec: Decoder + Encoder,
|
Codec: Decoder + Encoder,
|
||||||
<Codec as Encoder>::Item: 'static,
|
|
||||||
<Codec as Encoder>::Error: std::fmt::Debug,
|
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
|
||||||
{
|
{
|
||||||
/// Callback to execute on disconnect
|
/// Construct framed handler new service with specified connect service
|
||||||
///
|
pub fn new<F>(connect: F) -> FactoryBuilder<St, C, Io, Codec, Out>
|
||||||
/// Second parameter indicates error occured during disconnect.
|
|
||||||
pub fn disconnect<F>(mut self, disconnect: F) -> Self
|
|
||||||
where
|
where
|
||||||
F: Fn(St, bool) + 'static,
|
F: IntoServiceFactory<C>,
|
||||||
|
Io: AsyncRead + AsyncWrite,
|
||||||
|
C: ServiceFactory<
|
||||||
|
Config = (),
|
||||||
|
Request = Connect<Io, Codec>,
|
||||||
|
Response = ConnectResult<Io, St, Codec, Out>,
|
||||||
|
>,
|
||||||
|
Codec: Decoder + Encoder,
|
||||||
|
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
|
||||||
{
|
{
|
||||||
self.disconnect = Some(Rc::new(disconnect));
|
FactoryBuilder {
|
||||||
self
|
connect: connect.into_factory(),
|
||||||
|
_t: PhantomData,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn finish<F, T, Cfg>(self, service: F) -> FramedService<St, C, T, Io, Codec, Cfg>
|
pub fn build<F, T, Cfg>(self, service: F) -> FramedService<St, C, T, Io, Codec, Out, Cfg>
|
||||||
where
|
where
|
||||||
F: IntoServiceFactory<T>,
|
F: IntoServiceFactory<T>,
|
||||||
T: ServiceFactory<
|
T: ServiceFactory<
|
||||||
Config = St,
|
Config = St,
|
||||||
Request = RequestItem<St, Codec>,
|
Request = RequestItem<Codec>,
|
||||||
Response = ResponseItem<Codec>,
|
Response = ResponseItem<Codec>,
|
||||||
Error = C::Error,
|
Error = C::Error,
|
||||||
InitError = C::Error,
|
InitError = C::Error,
|
||||||
> + 'static,
|
>,
|
||||||
{
|
{
|
||||||
FramedService {
|
FramedService {
|
||||||
connect: self.connect,
|
connect: self.connect,
|
||||||
handler: Rc::new(service.into_factory()),
|
handler: Rc::new(service.into_factory()),
|
||||||
disconnect: self.disconnect,
|
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct FramedService<St, C, T, Io, Codec, Cfg> {
|
pub struct FramedService<St, C, T, Io, Codec, Out, Cfg> {
|
||||||
connect: C,
|
connect: C,
|
||||||
handler: Rc<T>,
|
handler: Rc<T>,
|
||||||
disconnect: Option<Rc<dyn Fn(St, bool)>>,
|
_t: PhantomData<(St, Io, Codec, Out, Cfg)>,
|
||||||
_t: PhantomData<(St, Io, Codec, Cfg)>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<St, C, T, Io, Codec, Cfg> ServiceFactory for FramedService<St, C, T, Io, Codec, Cfg>
|
impl<St, C, T, Io, Codec, Out, Cfg> ServiceFactory
|
||||||
|
for FramedService<St, C, T, Io, Codec, Out, Cfg>
|
||||||
where
|
where
|
||||||
St: Clone + 'static,
|
|
||||||
Io: AsyncRead + AsyncWrite,
|
Io: AsyncRead + AsyncWrite,
|
||||||
C: ServiceFactory<
|
C: ServiceFactory<
|
||||||
Config = (),
|
Config = (),
|
||||||
Request = Connect<Io, Codec>,
|
Request = Connect<Io, Codec>,
|
||||||
Response = ConnectResult<Io, St, Codec>,
|
Response = ConnectResult<Io, St, Codec, Out>,
|
||||||
>,
|
>,
|
||||||
C::Error: 'static,
|
|
||||||
C::Future: 'static,
|
|
||||||
T: ServiceFactory<
|
T: ServiceFactory<
|
||||||
Config = St,
|
Config = St,
|
||||||
Request = RequestItem<St, Codec>,
|
Request = RequestItem<Codec>,
|
||||||
Response = ResponseItem<Codec>,
|
Response = ResponseItem<Codec>,
|
||||||
Error = C::Error,
|
Error = C::Error,
|
||||||
InitError = C::Error,
|
InitError = C::Error,
|
||||||
> + 'static,
|
>,
|
||||||
|
<T::Service as Service>::Error: 'static,
|
||||||
<T::Service as Service>::Future: 'static,
|
<T::Service as Service>::Future: 'static,
|
||||||
Codec: Decoder + Encoder,
|
Codec: Decoder + Encoder,
|
||||||
<Codec as Encoder>::Item: 'static,
|
<Codec as Encoder>::Item: 'static,
|
||||||
<Codec as Encoder>::Error: std::fmt::Debug,
|
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
|
||||||
{
|
{
|
||||||
type Config = Cfg;
|
type Config = Cfg;
|
||||||
type Request = Io;
|
type Request = Io;
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = ServiceError<C::Error, Codec>;
|
type Error = ServiceError<C::Error, Codec>;
|
||||||
type InitError = C::InitError;
|
type InitError = C::InitError;
|
||||||
type Service = FramedServiceImpl<St, C::Service, T, Io, Codec>;
|
type Service = FramedServiceImpl<St, C::Service, T, Io, Codec, Out>;
|
||||||
type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>;
|
type Future = FramedServiceResponse<St, C, T, Io, Codec, Out>;
|
||||||
|
|
||||||
fn new_service(&self, _: Cfg) -> Self::Future {
|
fn new_service(&self, _: Cfg) -> Self::Future {
|
||||||
let handler = self.handler.clone();
|
|
||||||
let disconnect = self.disconnect.clone();
|
|
||||||
|
|
||||||
// create connect service and then create service impl
|
// create connect service and then create service impl
|
||||||
self.connect
|
FramedServiceResponse {
|
||||||
.new_service(())
|
fut: self.connect.new_service(()),
|
||||||
.map(move |result| {
|
handler: self.handler.clone(),
|
||||||
result.map(move |connect| FramedServiceImpl {
|
}
|
||||||
connect,
|
|
||||||
handler,
|
|
||||||
disconnect,
|
|
||||||
_t: PhantomData,
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.boxed_local()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct FramedServiceImpl<St, C, T, Io, Codec> {
|
#[pin_project::pin_project]
|
||||||
connect: C,
|
pub struct FramedServiceResponse<St, C, T, Io, Codec, Out>
|
||||||
handler: Rc<T>,
|
|
||||||
disconnect: Option<Rc<dyn Fn(St, bool)>>,
|
|
||||||
_t: PhantomData<(St, Io, Codec)>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<St, C, T, Io, Codec> Service for FramedServiceImpl<St, C, T, Io, Codec>
|
|
||||||
where
|
where
|
||||||
St: Clone,
|
|
||||||
Io: AsyncRead + AsyncWrite,
|
Io: AsyncRead + AsyncWrite,
|
||||||
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec>>,
|
C: ServiceFactory<
|
||||||
C::Error: 'static,
|
Config = (),
|
||||||
|
Request = Connect<Io, Codec>,
|
||||||
|
Response = ConnectResult<Io, St, Codec, Out>,
|
||||||
|
>,
|
||||||
T: ServiceFactory<
|
T: ServiceFactory<
|
||||||
Config = St,
|
Config = St,
|
||||||
Request = RequestItem<St, Codec>,
|
Request = RequestItem<Codec>,
|
||||||
Response = ResponseItem<Codec>,
|
Response = ResponseItem<Codec>,
|
||||||
Error = C::Error,
|
Error = C::Error,
|
||||||
InitError = C::Error,
|
InitError = C::Error,
|
||||||
>,
|
>,
|
||||||
|
<T::Service as Service>::Error: 'static,
|
||||||
<T::Service as Service>::Future: 'static,
|
<T::Service as Service>::Future: 'static,
|
||||||
Codec: Decoder + Encoder,
|
Codec: Decoder + Encoder,
|
||||||
<Codec as Encoder>::Item: 'static,
|
<Codec as Encoder>::Item: 'static,
|
||||||
<Codec as Encoder>::Error: std::fmt::Debug,
|
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
|
||||||
|
{
|
||||||
|
#[pin]
|
||||||
|
fut: C::Future,
|
||||||
|
handler: Rc<T>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<St, C, T, Io, Codec, Out> Future for FramedServiceResponse<St, C, T, Io, Codec, Out>
|
||||||
|
where
|
||||||
|
Io: AsyncRead + AsyncWrite,
|
||||||
|
C: ServiceFactory<
|
||||||
|
Config = (),
|
||||||
|
Request = Connect<Io, Codec>,
|
||||||
|
Response = ConnectResult<Io, St, Codec, Out>,
|
||||||
|
>,
|
||||||
|
T: ServiceFactory<
|
||||||
|
Config = St,
|
||||||
|
Request = RequestItem<Codec>,
|
||||||
|
Response = ResponseItem<Codec>,
|
||||||
|
Error = C::Error,
|
||||||
|
InitError = C::Error,
|
||||||
|
>,
|
||||||
|
<T::Service as Service>::Error: 'static,
|
||||||
|
<T::Service as Service>::Future: 'static,
|
||||||
|
Codec: Decoder + Encoder,
|
||||||
|
<Codec as Encoder>::Item: 'static,
|
||||||
|
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
|
||||||
|
{
|
||||||
|
type Output = Result<FramedServiceImpl<St, C::Service, T, Io, Codec, Out>, C::InitError>;
|
||||||
|
|
||||||
|
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||||
|
let this = self.project();
|
||||||
|
let connect = ready!(this.fut.poll(cx))?;
|
||||||
|
|
||||||
|
Poll::Ready(Ok(FramedServiceImpl {
|
||||||
|
connect,
|
||||||
|
handler: this.handler.clone(),
|
||||||
|
_t: PhantomData,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct FramedServiceImpl<St, C, T, Io, Codec, Out> {
|
||||||
|
connect: C,
|
||||||
|
handler: Rc<T>,
|
||||||
|
_t: PhantomData<(St, Io, Codec, Out)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<St, C, T, Io, Codec, Out> Service for FramedServiceImpl<St, C, T, Io, Codec, Out>
|
||||||
|
where
|
||||||
|
Io: AsyncRead + AsyncWrite,
|
||||||
|
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec, Out>>,
|
||||||
|
T: ServiceFactory<
|
||||||
|
Config = St,
|
||||||
|
Request = RequestItem<Codec>,
|
||||||
|
Response = ResponseItem<Codec>,
|
||||||
|
Error = C::Error,
|
||||||
|
InitError = C::Error,
|
||||||
|
>,
|
||||||
|
<T::Service as Service>::Error: 'static,
|
||||||
|
<T::Service as Service>::Future: 'static,
|
||||||
|
Codec: Decoder + Encoder,
|
||||||
|
<Codec as Encoder>::Item: 'static,
|
||||||
|
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
|
||||||
{
|
{
|
||||||
type Request = Io;
|
type Request = Io;
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = ServiceError<C::Error, Codec>;
|
type Error = ServiceError<C::Error, Codec>;
|
||||||
type Future = FramedServiceImplResponse<St, Io, Codec, C, T>;
|
type Future = FramedServiceImplResponse<St, Io, Codec, Out, C, T>;
|
||||||
|
|
||||||
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||||
self.connect.poll_ready(cx).map_err(|e| e.into())
|
self.connect.poll_ready(cx).map_err(|e| e.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: Io) -> Self::Future {
|
fn call(&mut self, req: Io) -> Self::Future {
|
||||||
let (tx, rx) = mpsc::channel();
|
|
||||||
let sink = Sink::new(Rc::new(move |msg| {
|
|
||||||
let _ = tx.send(Ok(msg));
|
|
||||||
}));
|
|
||||||
FramedServiceImplResponse {
|
FramedServiceImplResponse {
|
||||||
inner: FramedServiceImplResponseInner::Connect(
|
inner: FramedServiceImplResponseInner::Connect(
|
||||||
self.connect.call(Connect::new(req, sink.clone())),
|
self.connect.call(Connect::new(req)),
|
||||||
self.handler.clone(),
|
self.handler.clone(),
|
||||||
self.disconnect.clone(),
|
|
||||||
Some(rx),
|
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[pin_project::pin_project]
|
#[pin_project::pin_project]
|
||||||
pub struct FramedServiceImplResponse<St, Io, Codec, C, T>
|
pub struct FramedServiceImplResponse<St, Io, Codec, Out, C, T>
|
||||||
where
|
where
|
||||||
St: Clone,
|
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec, Out>>,
|
||||||
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec>>,
|
|
||||||
C::Error: 'static,
|
|
||||||
T: ServiceFactory<
|
T: ServiceFactory<
|
||||||
Config = St,
|
Config = St,
|
||||||
Request = RequestItem<St, Codec>,
|
Request = RequestItem<Codec>,
|
||||||
Response = ResponseItem<Codec>,
|
Response = ResponseItem<Codec>,
|
||||||
Error = C::Error,
|
Error = C::Error,
|
||||||
InitError = C::Error,
|
InitError = C::Error,
|
||||||
>,
|
>,
|
||||||
|
<T::Service as Service>::Error: 'static,
|
||||||
<T::Service as Service>::Future: 'static,
|
<T::Service as Service>::Future: 'static,
|
||||||
Io: AsyncRead + AsyncWrite,
|
Io: AsyncRead + AsyncWrite,
|
||||||
Codec: Encoder + Decoder,
|
Codec: Encoder + Decoder,
|
||||||
<Codec as Encoder>::Item: 'static,
|
<Codec as Encoder>::Item: 'static,
|
||||||
<Codec as Encoder>::Error: std::fmt::Debug,
|
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
|
||||||
{
|
{
|
||||||
#[pin]
|
#[pin]
|
||||||
inner: FramedServiceImplResponseInner<St, Io, Codec, C, T>,
|
inner: FramedServiceImplResponseInner<St, Io, Codec, Out, C, T>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<St, Io, Codec, C, T> Future for FramedServiceImplResponse<St, Io, Codec, C, T>
|
impl<St, Io, Codec, Out, C, T> Future for FramedServiceImplResponse<St, Io, Codec, Out, C, T>
|
||||||
where
|
where
|
||||||
St: Clone,
|
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec, Out>>,
|
||||||
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec>>,
|
|
||||||
C::Error: 'static,
|
|
||||||
T: ServiceFactory<
|
T: ServiceFactory<
|
||||||
Config = St,
|
Config = St,
|
||||||
Request = RequestItem<St, Codec>,
|
Request = RequestItem<Codec>,
|
||||||
Response = ResponseItem<Codec>,
|
Response = ResponseItem<Codec>,
|
||||||
Error = C::Error,
|
Error = C::Error,
|
||||||
InitError = C::Error,
|
InitError = C::Error,
|
||||||
>,
|
>,
|
||||||
|
<T::Service as Service>::Error: 'static,
|
||||||
<T::Service as Service>::Future: 'static,
|
<T::Service as Service>::Future: 'static,
|
||||||
Io: AsyncRead + AsyncWrite,
|
Io: AsyncRead + AsyncWrite,
|
||||||
Codec: Encoder + Decoder,
|
Codec: Encoder + Decoder,
|
||||||
<Codec as Encoder>::Item: 'static,
|
<Codec as Encoder>::Item: 'static,
|
||||||
<Codec as Encoder>::Error: std::fmt::Debug,
|
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
|
||||||
{
|
{
|
||||||
type Output = Result<(), ServiceError<C::Error, Codec>>;
|
type Output = Result<(), ServiceError<C::Error, Codec>>;
|
||||||
|
|
||||||
@@ -338,94 +337,71 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[pin_project::pin_project]
|
#[pin_project::pin_project]
|
||||||
enum FramedServiceImplResponseInner<St, Io, Codec, C, T>
|
enum FramedServiceImplResponseInner<St, Io, Codec, Out, C, T>
|
||||||
where
|
where
|
||||||
St: Clone,
|
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec, Out>>,
|
||||||
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec>>,
|
|
||||||
C::Error: 'static,
|
|
||||||
T: ServiceFactory<
|
T: ServiceFactory<
|
||||||
Config = St,
|
Config = St,
|
||||||
Request = RequestItem<St, Codec>,
|
Request = RequestItem<Codec>,
|
||||||
Response = ResponseItem<Codec>,
|
Response = ResponseItem<Codec>,
|
||||||
Error = C::Error,
|
Error = C::Error,
|
||||||
InitError = C::Error,
|
InitError = C::Error,
|
||||||
>,
|
>,
|
||||||
|
<T::Service as Service>::Error: 'static,
|
||||||
<T::Service as Service>::Future: 'static,
|
<T::Service as Service>::Future: 'static,
|
||||||
Io: AsyncRead + AsyncWrite,
|
Io: AsyncRead + AsyncWrite,
|
||||||
Codec: Encoder + Decoder,
|
Codec: Encoder + Decoder,
|
||||||
<Codec as Encoder>::Item: 'static,
|
<Codec as Encoder>::Item: 'static,
|
||||||
<Codec as Encoder>::Error: std::fmt::Debug,
|
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
|
||||||
{
|
{
|
||||||
Connect(
|
Connect(#[pin] C::Future, Rc<T>),
|
||||||
#[pin] C::Future,
|
Handler(#[pin] T::Future, Option<Framed<Io, Codec>>, Option<Out>),
|
||||||
Rc<T>,
|
Dispatcher(Dispatcher<T::Service, Io, Codec, Out>),
|
||||||
Option<Rc<dyn Fn(St, bool)>>,
|
|
||||||
Option<mpsc::Receiver<ServiceResult<Codec, C::Error>>>,
|
|
||||||
),
|
|
||||||
Handler(
|
|
||||||
#[pin] T::Future,
|
|
||||||
Option<ConnectResult<Io, St, Codec>>,
|
|
||||||
Option<Rc<dyn Fn(St, bool)>>,
|
|
||||||
Option<mpsc::Receiver<ServiceResult<Codec, C::Error>>>,
|
|
||||||
),
|
|
||||||
Dispatcher(Dispatcher<St, T::Service, Io, Codec>),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<St, Io, Codec, C, T> FramedServiceImplResponseInner<St, Io, Codec, C, T>
|
impl<St, Io, Codec, Out, C, T> FramedServiceImplResponseInner<St, Io, Codec, Out, C, T>
|
||||||
where
|
where
|
||||||
St: Clone,
|
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec, Out>>,
|
||||||
C: Service<Request = Connect<Io, Codec>, Response = ConnectResult<Io, St, Codec>>,
|
|
||||||
C::Error: 'static,
|
|
||||||
T: ServiceFactory<
|
T: ServiceFactory<
|
||||||
Config = St,
|
Config = St,
|
||||||
Request = RequestItem<St, Codec>,
|
Request = RequestItem<Codec>,
|
||||||
Response = ResponseItem<Codec>,
|
Response = ResponseItem<Codec>,
|
||||||
Error = C::Error,
|
Error = C::Error,
|
||||||
InitError = C::Error,
|
InitError = C::Error,
|
||||||
>,
|
>,
|
||||||
|
<T::Service as Service>::Error: 'static,
|
||||||
<T::Service as Service>::Future: 'static,
|
<T::Service as Service>::Future: 'static,
|
||||||
Io: AsyncRead + AsyncWrite,
|
Io: AsyncRead + AsyncWrite,
|
||||||
Codec: Encoder + Decoder,
|
Codec: Encoder + Decoder,
|
||||||
<Codec as Encoder>::Item: 'static,
|
<Codec as Encoder>::Item: 'static,
|
||||||
<Codec as Encoder>::Error: std::fmt::Debug,
|
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||||
|
Out: Stream<Item = <Codec as Encoder>::Item> + Unpin,
|
||||||
{
|
{
|
||||||
#[project]
|
#[project]
|
||||||
fn poll(
|
fn poll(
|
||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Either<
|
) -> Either<
|
||||||
FramedServiceImplResponseInner<St, Io, Codec, C, T>,
|
FramedServiceImplResponseInner<St, Io, Codec, Out, C, T>,
|
||||||
Poll<Result<(), ServiceError<C::Error, Codec>>>,
|
Poll<Result<(), ServiceError<C::Error, Codec>>>,
|
||||||
> {
|
> {
|
||||||
#[project]
|
#[project]
|
||||||
match self.project() {
|
match self.project() {
|
||||||
FramedServiceImplResponseInner::Connect(fut, handler, disconnect, rx) => {
|
FramedServiceImplResponseInner::Connect(fut, handler) => match fut.poll(cx) {
|
||||||
match fut.poll(cx) {
|
Poll::Ready(Ok(res)) => Either::Left(FramedServiceImplResponseInner::Handler(
|
||||||
Poll::Ready(Ok(res)) => {
|
handler.new_service(res.state),
|
||||||
Either::Left(FramedServiceImplResponseInner::Handler(
|
Some(res.framed),
|
||||||
handler.new_service(res.state.clone()),
|
res.out,
|
||||||
Some(res),
|
)),
|
||||||
disconnect.take(),
|
Poll::Pending => Either::Right(Poll::Pending),
|
||||||
rx.take(),
|
Poll::Ready(Err(e)) => Either::Right(Poll::Ready(Err(e.into()))),
|
||||||
))
|
},
|
||||||
}
|
FramedServiceImplResponseInner::Handler(fut, framed, out) => {
|
||||||
Poll::Pending => Either::Right(Poll::Pending),
|
|
||||||
Poll::Ready(Err(e)) => Either::Right(Poll::Ready(Err(e.into()))),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
FramedServiceImplResponseInner::Handler(fut, res, disconnect, rx) => {
|
|
||||||
match fut.poll(cx) {
|
match fut.poll(cx) {
|
||||||
Poll::Ready(Ok(handler)) => {
|
Poll::Ready(Ok(handler)) => {
|
||||||
let res = res.take().unwrap();
|
|
||||||
Either::Left(FramedServiceImplResponseInner::Dispatcher(
|
Either::Left(FramedServiceImplResponseInner::Dispatcher(
|
||||||
Dispatcher::new(
|
Dispatcher::new(framed.take().unwrap(), handler, out.take()),
|
||||||
res.framed,
|
|
||||||
res.state,
|
|
||||||
handler,
|
|
||||||
res.sink,
|
|
||||||
rx.take().unwrap(),
|
|
||||||
disconnect.take(),
|
|
||||||
),
|
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
Poll::Pending => Either::Right(Poll::Pending),
|
Poll::Pending => Either::Right(Poll::Pending),
|
||||||
|
@@ -1,45 +0,0 @@
|
|||||||
use std::fmt;
|
|
||||||
use std::rc::Rc;
|
|
||||||
|
|
||||||
use actix_utils::oneshot;
|
|
||||||
use futures::future::{Future, FutureExt};
|
|
||||||
|
|
||||||
use crate::dispatcher::Message;
|
|
||||||
|
|
||||||
pub struct Sink<T>(Rc<dyn Fn(Message<T>)>);
|
|
||||||
|
|
||||||
impl<T> Clone for Sink<T> {
|
|
||||||
fn clone(&self) -> Self {
|
|
||||||
Sink(self.0.clone())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> Sink<T> {
|
|
||||||
pub(crate) fn new(tx: Rc<dyn Fn(Message<T>)>) -> Self {
|
|
||||||
Sink(tx)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Close connection
|
|
||||||
pub fn close(&self) {
|
|
||||||
(self.0)(Message::Close);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Close connection
|
|
||||||
pub fn wait_close(&self) -> impl Future<Output = ()> {
|
|
||||||
let (tx, rx) = oneshot::channel();
|
|
||||||
(self.0)(Message::WaitClose(tx));
|
|
||||||
|
|
||||||
rx.map(|_| ())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Send item
|
|
||||||
pub fn send(&self, item: T) {
|
|
||||||
(self.0)(Message::Item(item));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> fmt::Debug for Sink<T> {
|
|
||||||
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
fmt.debug_struct("Sink").finish()
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,43 +1,49 @@
|
|||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::cell::Cell;
|
||||||
use std::sync::Arc;
|
use std::rc::Rc;
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
use actix_codec::BytesCodec;
|
use actix_codec::BytesCodec;
|
||||||
use actix_rt::time::delay_for;
|
use actix_service::{fn_factory_with_config, fn_service, IntoService, Service};
|
||||||
use actix_service::{fn_service, Service};
|
|
||||||
use actix_testing::TestServer;
|
use actix_testing::TestServer;
|
||||||
|
use actix_utils::mpsc;
|
||||||
|
use bytes::{Bytes, BytesMut};
|
||||||
use futures::future::ok;
|
use futures::future::ok;
|
||||||
|
|
||||||
use actix_ioframe::{Builder, Connect};
|
use actix_ioframe::{Builder, Connect, FactoryBuilder};
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
struct State;
|
struct State(Option<mpsc::Sender<Bytes>>);
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_disconnect() -> std::io::Result<()> {
|
async fn test_basic() {
|
||||||
let disconnect = Arc::new(AtomicBool::new(false));
|
let client_item = Rc::new(Cell::new(false));
|
||||||
let disconnect1 = disconnect.clone();
|
|
||||||
|
|
||||||
let srv = TestServer::with(move || {
|
let srv = TestServer::with(move || {
|
||||||
let disconnect1 = disconnect1.clone();
|
FactoryBuilder::new(fn_service(|conn: Connect<_, _>| {
|
||||||
|
ok(conn.codec(BytesCodec).state(State(None)))
|
||||||
Builder::new()
|
}))
|
||||||
.factory(fn_service(|conn: Connect<_, _>| {
|
// echo
|
||||||
ok(conn.codec(BytesCodec).state(State))
|
.build(fn_service(|t: BytesMut| ok(Some(t.freeze()))))
|
||||||
}))
|
|
||||||
.disconnect(move |_, _| {
|
|
||||||
disconnect1.store(true, Ordering::Relaxed);
|
|
||||||
})
|
|
||||||
.finish(fn_service(|_t| ok(None)))
|
|
||||||
});
|
});
|
||||||
|
|
||||||
let mut client = Builder::new()
|
let item = client_item.clone();
|
||||||
.service(|conn: Connect<_, _>| {
|
let mut client = Builder::new(fn_service(move |conn: Connect<_, _>| {
|
||||||
let conn = conn.codec(BytesCodec).state(State);
|
async move {
|
||||||
conn.sink().close();
|
let (tx, rx) = mpsc::channel();
|
||||||
ok(conn)
|
let _ = tx.send(Bytes::from_static(b"Hello"));
|
||||||
|
Ok(conn.codec(BytesCodec).out(rx).state(State(Some(tx))))
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
.build(fn_factory_with_config(move |mut cfg: State| {
|
||||||
|
let item = item.clone();
|
||||||
|
ok((move |t: BytesMut| {
|
||||||
|
assert_eq!(t.freeze(), Bytes::from_static(b"Hello"));
|
||||||
|
item.set(true);
|
||||||
|
// drop Sender, which will close connection
|
||||||
|
cfg.0.take();
|
||||||
|
ok::<_, ()>(None)
|
||||||
})
|
})
|
||||||
.finish(fn_service(|_t| ok(None)));
|
.into_service())
|
||||||
|
}));
|
||||||
|
|
||||||
let conn = actix_connect::default_connector()
|
let conn = actix_connect::default_connector()
|
||||||
.call(actix_connect::Connect::with(String::new(), srv.addr()))
|
.call(actix_connect::Connect::with(String::new(), srv.addr()))
|
||||||
@@ -45,8 +51,5 @@ async fn test_disconnect() -> std::io::Result<()> {
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
client.call(conn.into_parts().0).await.unwrap();
|
client.call(conn.into_parts().0).await.unwrap();
|
||||||
let _ = delay_for(Duration::from_millis(100)).await;
|
assert!(client_item.get());
|
||||||
assert!(disconnect.load(Ordering::Relaxed));
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
@@ -14,6 +14,7 @@ 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 {
|
||||||
|
@@ -1,5 +1,9 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [TBD] - [TBD]
|
||||||
|
|
||||||
|
- Expose `System::is_set` to check if current system is running
|
||||||
|
|
||||||
## [1.0.0] - 2019-12-11
|
## [1.0.0] - 2019-12-11
|
||||||
|
|
||||||
* Update dependencies
|
* Update dependencies
|
||||||
|
@@ -42,8 +42,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<()>>,
|
||||||
|
@@ -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
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -79,8 +79,8 @@ impl System {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set current running system.
|
/// Check if current system is running.
|
||||||
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())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -1,5 +1,19 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [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
|
## [1.0.0] - 2019-12-11
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-server"
|
name = "actix-server"
|
||||||
version = "1.0.0"
|
version = "1.0.2"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix server - General purpose tcp server"
|
description = "Actix server - General purpose tcp server"
|
||||||
keywords = ["network", "framework", "async", "futures"]
|
keywords = ["network", "framework", "async", "futures"]
|
||||||
@@ -21,10 +21,10 @@ path = "src/lib.rs"
|
|||||||
default = []
|
default = []
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-service = "1.0.0"
|
actix-service = "1.0.1"
|
||||||
actix-rt = "1.0.0"
|
actix-rt = "1.0.0"
|
||||||
actix-codec = "0.2.0"
|
actix-codec = "0.2.0"
|
||||||
actix-utils = "1.0.0"
|
actix-utils = "1.0.4"
|
||||||
|
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
num_cpus = "1.11"
|
num_cpus = "1.11"
|
||||||
@@ -34,9 +34,10 @@ futures = "0.3.1"
|
|||||||
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"
|
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);
|
||||||
|
@@ -13,7 +13,6 @@ use futures::stream::FuturesUnordered;
|
|||||||
use futures::{ready, Future, FutureExt, Stream, StreamExt};
|
use futures::{ready, Future, FutureExt, Stream, StreamExt};
|
||||||
use log::{error, info};
|
use log::{error, info};
|
||||||
use net2::TcpBuilder;
|
use net2::TcpBuilder;
|
||||||
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 {
|
||||||
|
@@ -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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -153,7 +153,7 @@ impl InternalServiceFactory for ConfiguredService {
|
|||||||
}
|
}
|
||||||
return Ok(res);
|
return Ok(res);
|
||||||
}
|
}
|
||||||
.boxed_local()
|
.boxed_local()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -280,6 +280,6 @@ where
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
.boxed_local()
|
.boxed_local()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -217,7 +217,7 @@ impl Worker {
|
|||||||
wrk.await
|
wrk.await
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
.boxed(),
|
.boxed(),
|
||||||
);
|
);
|
||||||
|
|
||||||
WorkerClient::new(idx, tx1, tx2, avail)
|
WorkerClient::new(idx, tx1, tx2, avail)
|
||||||
@@ -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,15 +1,10 @@
|
|||||||
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::fn_service;
|
use actix_service::fn_service;
|
||||||
use bytes::Bytes;
|
|
||||||
use futures::future::{lazy, ok};
|
use futures::future::{lazy, ok};
|
||||||
use futures::SinkExt;
|
|
||||||
use net2::TcpBuilder;
|
use net2::TcpBuilder;
|
||||||
|
|
||||||
fn unused_addr() -> net::SocketAddr {
|
fn unused_addr() -> net::SocketAddr {
|
||||||
@@ -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();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -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::SinkExt;
|
||||||
|
use std::io::Read;
|
||||||
|
|
||||||
let addr = unused_addr();
|
let addr = unused_addr();
|
||||||
let (tx, rx) = mpsc::channel();
|
let (tx, rx) = mpsc::channel();
|
||||||
|
|
||||||
@@ -130,7 +131,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();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -178,6 +179,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,30 @@
|
|||||||
# 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
|
## [1.0.1] - 2019-12-22
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-service"
|
name = "actix-service"
|
||||||
version = "1.0.1"
|
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"]
|
||||||
@@ -10,12 +10,6 @@ documentation = "https://docs.rs/actix-service/"
|
|||||||
categories = ["network-programming", "asynchronous"]
|
categories = ["network-programming", "asynchronous"]
|
||||||
license = "MIT/Apache-2.0"
|
license = "MIT/Apache-2.0"
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
workspace = ".."
|
|
||||||
|
|
||||||
[badges]
|
|
||||||
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,3 +21,12 @@ pin-project = "0.4.6"
|
|||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-rt = "1.0.0"
|
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>,
|
||||||
@@ -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]
|
||||||
|
@@ -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 {
|
||||||
@@ -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::<_, ()>(fn_service(|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)),
|
||||||
|
@@ -233,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, ()))
|
||||||
}
|
}
|
||||||
}));
|
}));
|
||||||
|
|
||||||
@@ -242,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]
|
||||||
@@ -252,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, ()))
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
));
|
));
|
||||||
@@ -264,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", ()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -7,7 +7,18 @@ use crate::cell::Cell;
|
|||||||
use crate::{Service, ServiceFactory};
|
use crate::{Service, ServiceFactory};
|
||||||
|
|
||||||
/// Convert `Fn(Config, &mut Service1) -> Future<Service2>` fn to a service factory
|
/// 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,
|
||||||
@@ -26,7 +37,14 @@ where
|
|||||||
pub fn apply_cfg_factory<F, C, T, R, S>(
|
pub fn apply_cfg_factory<F, C, T, R, S>(
|
||||||
factory: 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 = ()>,
|
||||||
@@ -41,7 +59,7 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Convert `Fn(Config, &mut Server) -> 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,
|
||||||
@@ -92,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 = ()>,
|
||||||
@@ -145,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 = ()>,
|
||||||
|
@@ -57,7 +57,7 @@ pub use self::transform::{apply, Transform};
|
|||||||
///
|
///
|
||||||
/// fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { ... }
|
/// fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { ... }
|
||||||
///
|
///
|
||||||
/// fn call(&mut self) -> Self::Future { ... }
|
/// fn call(&mut self, req: Self::Request) -> Self::Future { ... }
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
///
|
///
|
||||||
@@ -82,7 +82,7 @@ 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.
|
||||||
///
|
///
|
||||||
@@ -351,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,
|
||||||
};
|
};
|
||||||
@@ -363,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;
|
||||||
}
|
}
|
||||||
|
@@ -46,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>,
|
||||||
@@ -65,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>,
|
||||||
@@ -84,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>,
|
||||||
@@ -168,7 +178,23 @@ pub struct PipelineFactory<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,
|
||||||
@@ -193,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,
|
||||||
@@ -214,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"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
//! 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};
|
||||||
|
@@ -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(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
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 = "0.3.1"
|
||||||
|
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,15 @@
|
|||||||
# 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
|
## [1.0.4] - 2019-12-20
|
||||||
|
|
||||||
* Add methods to check `LocalWaker` registration state.
|
* Add methods to check `LocalWaker` registration state.
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-utils"
|
name = "actix-utils"
|
||||||
version = "1.0.4"
|
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"]
|
||||||
@@ -16,11 +16,13 @@ name = "actix_utils"
|
|||||||
path = "src/lib.rs"
|
path = "src/lib.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-service = "1.0.0"
|
actix-service = "1.0.1"
|
||||||
actix-rt = "1.0.0"
|
actix-rt = "1.0.0"
|
||||||
actix-codec = "0.2.0"
|
actix-codec = "0.2.0"
|
||||||
|
bitflags = "1.2"
|
||||||
bytes = "0.5.3"
|
bytes = "0.5.3"
|
||||||
either = "1.5.3"
|
either = "1.5.3"
|
||||||
futures = "0.3.1"
|
futures = "0.3.1"
|
||||||
pin-project = "0.4.6"
|
pin-project = "0.4.6"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
|
slab = "0.4"
|
||||||
|
127
actix-utils/src/condition.rs
Normal file
127
actix-utils/src/condition.rs
Normal file
@@ -0,0 +1,127 @@
|
|||||||
|
use std::future::Future;
|
||||||
|
use std::pin::Pin;
|
||||||
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
|
use slab::Slab;
|
||||||
|
|
||||||
|
use crate::cell::Cell;
|
||||||
|
use crate::task::LocalWaker;
|
||||||
|
|
||||||
|
/// Condition allows to notify multiple receivers at the same time
|
||||||
|
pub struct Condition(Cell<Inner>);
|
||||||
|
|
||||||
|
struct Inner {
|
||||||
|
data: Slab<Option<LocalWaker>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Condition {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Condition {
|
||||||
|
pub fn new() -> Condition {
|
||||||
|
Condition(Cell::new(Inner { data: Slab::new() }))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get condition waiter
|
||||||
|
pub fn wait(&mut self) -> Waiter {
|
||||||
|
let token = self.0.get_mut().data.insert(None);
|
||||||
|
Waiter {
|
||||||
|
token,
|
||||||
|
inner: self.0.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Notify all waiters
|
||||||
|
pub fn notify(&self) {
|
||||||
|
let inner = self.0.get_ref();
|
||||||
|
for item in inner.data.iter() {
|
||||||
|
if let Some(waker) = item.1 {
|
||||||
|
waker.wake();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Condition {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.notify()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use = "Waiter do nothing unless polled"]
|
||||||
|
pub struct Waiter {
|
||||||
|
token: usize,
|
||||||
|
inner: Cell<Inner>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Clone for Waiter {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
let token = unsafe { self.inner.get_mut_unsafe() }.data.insert(None);
|
||||||
|
Waiter {
|
||||||
|
token,
|
||||||
|
inner: self.inner.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Future for Waiter {
|
||||||
|
type Output = ();
|
||||||
|
|
||||||
|
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||||
|
let this = self.get_mut();
|
||||||
|
|
||||||
|
let inner = unsafe { this.inner.get_mut().data.get_unchecked_mut(this.token) };
|
||||||
|
if inner.is_none() {
|
||||||
|
let waker = LocalWaker::default();
|
||||||
|
waker.register(cx.waker());
|
||||||
|
*inner = Some(waker);
|
||||||
|
Poll::Pending
|
||||||
|
} else if inner.as_mut().unwrap().register(cx.waker()) {
|
||||||
|
Poll::Pending
|
||||||
|
} else {
|
||||||
|
Poll::Ready(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Waiter {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.inner.get_mut().data.remove(self.token);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use futures::future::lazy;
|
||||||
|
|
||||||
|
#[actix_rt::test]
|
||||||
|
async fn test_condition() {
|
||||||
|
let mut cond = Condition::new();
|
||||||
|
let mut waiter = cond.wait();
|
||||||
|
assert_eq!(
|
||||||
|
lazy(|cx| Pin::new(&mut waiter).poll(cx)).await,
|
||||||
|
Poll::Pending
|
||||||
|
);
|
||||||
|
cond.notify();
|
||||||
|
waiter.await;
|
||||||
|
|
||||||
|
let mut waiter = cond.wait();
|
||||||
|
assert_eq!(
|
||||||
|
lazy(|cx| Pin::new(&mut waiter).poll(cx)).await,
|
||||||
|
Poll::Pending
|
||||||
|
);
|
||||||
|
let mut waiter2 = waiter.clone();
|
||||||
|
assert_eq!(
|
||||||
|
lazy(|cx| Pin::new(&mut waiter2).poll(cx)).await,
|
||||||
|
Poll::Pending
|
||||||
|
);
|
||||||
|
|
||||||
|
drop(cond);
|
||||||
|
waiter.await;
|
||||||
|
waiter2.await;
|
||||||
|
}
|
||||||
|
}
|
@@ -3,6 +3,7 @@
|
|||||||
#![allow(clippy::type_complexity)]
|
#![allow(clippy::type_complexity)]
|
||||||
|
|
||||||
mod cell;
|
mod cell;
|
||||||
|
pub mod condition;
|
||||||
pub mod counter;
|
pub mod counter;
|
||||||
pub mod either;
|
pub mod either;
|
||||||
pub mod framed;
|
pub mod framed;
|
||||||
|
@@ -4,6 +4,7 @@ use std::pin::Pin;
|
|||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
pub use futures::channel::oneshot::Canceled;
|
pub use futures::channel::oneshot::Canceled;
|
||||||
|
use slab::Slab;
|
||||||
|
|
||||||
use crate::cell::Cell;
|
use crate::cell::Cell;
|
||||||
use crate::task::LocalWaker;
|
use crate::task::LocalWaker;
|
||||||
@@ -21,6 +22,11 @@ pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
|
|||||||
(tx, rx)
|
(tx, rx)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Creates a new futures-aware, pool of one-shot's.
|
||||||
|
pub fn pool<T>() -> Pool<T> {
|
||||||
|
Pool(Cell::new(Slab::new()))
|
||||||
|
}
|
||||||
|
|
||||||
/// Represents the completion half of a oneshot through which the result of a
|
/// Represents the completion half of a oneshot through which the result of a
|
||||||
/// computation is signaled.
|
/// computation is signaled.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
@@ -77,9 +83,7 @@ impl<T> Sender<T> {
|
|||||||
|
|
||||||
impl<T> Drop for Sender<T> {
|
impl<T> Drop for Sender<T> {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
if self.inner.strong_count() == 2 {
|
self.inner.get_ref().rx_task.wake();
|
||||||
self.inner.get_ref().rx_task.wake();
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -104,6 +108,148 @@ impl<T> Future for Receiver<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Futures-aware, pool of one-shot's.
|
||||||
|
pub struct Pool<T>(Cell<Slab<PoolInner<T>>>);
|
||||||
|
|
||||||
|
bitflags::bitflags! {
|
||||||
|
pub struct Flags: u8 {
|
||||||
|
const SENDER = 0b0000_0001;
|
||||||
|
const RECEIVER = 0b0000_0010;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct PoolInner<T> {
|
||||||
|
flags: Flags,
|
||||||
|
value: Option<T>,
|
||||||
|
waker: LocalWaker,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Pool<T> {
|
||||||
|
pub fn channel(&mut self) -> (PSender<T>, PReceiver<T>) {
|
||||||
|
let token = self.0.get_mut().insert(PoolInner {
|
||||||
|
flags: Flags::all(),
|
||||||
|
value: None,
|
||||||
|
waker: LocalWaker::default(),
|
||||||
|
});
|
||||||
|
|
||||||
|
(
|
||||||
|
PSender {
|
||||||
|
token,
|
||||||
|
inner: self.0.clone(),
|
||||||
|
},
|
||||||
|
PReceiver {
|
||||||
|
token,
|
||||||
|
inner: self.0.clone(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Clone for Pool<T> {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
Pool(self.0.clone())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Represents the completion half of a oneshot through which the result of a
|
||||||
|
/// computation is signaled.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct PSender<T> {
|
||||||
|
token: usize,
|
||||||
|
inner: Cell<Slab<PoolInner<T>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A future representing the completion of a computation happening elsewhere in
|
||||||
|
/// memory.
|
||||||
|
#[derive(Debug)]
|
||||||
|
#[must_use = "futures do nothing unless polled"]
|
||||||
|
pub struct PReceiver<T> {
|
||||||
|
token: usize,
|
||||||
|
inner: Cell<Slab<PoolInner<T>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
// The oneshots do not ever project Pin to the inner T
|
||||||
|
impl<T> Unpin for PReceiver<T> {}
|
||||||
|
impl<T> Unpin for PSender<T> {}
|
||||||
|
|
||||||
|
impl<T> PSender<T> {
|
||||||
|
/// Completes this oneshot with a successful result.
|
||||||
|
///
|
||||||
|
/// This function will consume `self` and indicate to the other end, the
|
||||||
|
/// `Receiver`, that the error provided is the result of the computation this
|
||||||
|
/// represents.
|
||||||
|
///
|
||||||
|
/// If the value is successfully enqueued for the remote end to receive,
|
||||||
|
/// then `Ok(())` is returned. If the receiving end was dropped before
|
||||||
|
/// this function was called, however, then `Err` is returned with the value
|
||||||
|
/// provided.
|
||||||
|
pub fn send(mut self, val: T) -> Result<(), T> {
|
||||||
|
let inner = unsafe { self.inner.get_mut().get_unchecked_mut(self.token) };
|
||||||
|
|
||||||
|
if inner.flags.contains(Flags::RECEIVER) {
|
||||||
|
inner.value = Some(val);
|
||||||
|
inner.waker.wake();
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(val)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tests to see whether this `Sender`'s corresponding `Receiver`
|
||||||
|
/// has gone away.
|
||||||
|
pub fn is_canceled(&self) -> bool {
|
||||||
|
!unsafe { self.inner.get_ref().get_unchecked(self.token) }
|
||||||
|
.flags
|
||||||
|
.contains(Flags::RECEIVER)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Drop for PSender<T> {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let inner = unsafe { self.inner.get_mut().get_unchecked_mut(self.token) };
|
||||||
|
if inner.flags.contains(Flags::RECEIVER) {
|
||||||
|
inner.waker.wake();
|
||||||
|
inner.flags.remove(Flags::SENDER);
|
||||||
|
} else {
|
||||||
|
self.inner.get_mut().remove(self.token);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Drop for PReceiver<T> {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let inner = unsafe { self.inner.get_mut().get_unchecked_mut(self.token) };
|
||||||
|
if inner.flags.contains(Flags::SENDER) {
|
||||||
|
inner.flags.remove(Flags::RECEIVER);
|
||||||
|
} else {
|
||||||
|
self.inner.get_mut().remove(self.token);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Future for PReceiver<T> {
|
||||||
|
type Output = Result<T, Canceled>;
|
||||||
|
|
||||||
|
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||||
|
let this = self.get_mut();
|
||||||
|
let inner = unsafe { this.inner.get_mut().get_unchecked_mut(this.token) };
|
||||||
|
|
||||||
|
// If we've got a value, then skip the logic below as we're done.
|
||||||
|
if let Some(val) = inner.value.take() {
|
||||||
|
return Poll::Ready(Ok(val));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if sender is dropped and return error if it is.
|
||||||
|
if !inner.flags.contains(Flags::SENDER) {
|
||||||
|
Poll::Ready(Err(Canceled))
|
||||||
|
} else {
|
||||||
|
inner.waker.register(cx.waker());
|
||||||
|
Poll::Pending
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -135,4 +281,31 @@ mod tests {
|
|||||||
drop(tx);
|
drop(tx);
|
||||||
assert!(rx.await.is_err());
|
assert!(rx.await.is_err());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[actix_rt::test]
|
||||||
|
async fn test_pool() {
|
||||||
|
let (tx, rx) = pool().channel();
|
||||||
|
tx.send("test").unwrap();
|
||||||
|
assert_eq!(rx.await.unwrap(), "test");
|
||||||
|
|
||||||
|
let (tx, rx) = pool().channel();
|
||||||
|
assert!(!tx.is_canceled());
|
||||||
|
drop(rx);
|
||||||
|
assert!(tx.is_canceled());
|
||||||
|
assert!(tx.send("test").is_err());
|
||||||
|
|
||||||
|
let (tx, rx) = pool::<&'static str>().channel();
|
||||||
|
drop(tx);
|
||||||
|
assert!(rx.await.is_err());
|
||||||
|
|
||||||
|
let (tx, mut rx) = pool::<&'static str>().channel();
|
||||||
|
assert_eq!(lazy(|cx| Pin::new(&mut rx).poll(cx)).await, Poll::Pending);
|
||||||
|
tx.send("test").unwrap();
|
||||||
|
assert_eq!(rx.await.unwrap(), "test");
|
||||||
|
|
||||||
|
let (tx, mut rx) = pool::<&'static str>().channel();
|
||||||
|
assert_eq!(lazy(|cx| Pin::new(&mut rx).poll(cx)).await, Poll::Pending);
|
||||||
|
drop(tx);
|
||||||
|
assert!(rx.await.is_err());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@@ -242,7 +242,7 @@ mod tests {
|
|||||||
let rx2 = rx2;
|
let rx2 = rx2;
|
||||||
let rx3 = rx3;
|
let rx3 = rx3;
|
||||||
let tx_stop = tx_stop;
|
let tx_stop = tx_stop;
|
||||||
let _ = actix_rt::System::new("test").block_on(async {
|
actix_rt::System::new("test").block_on(async {
|
||||||
let mut srv = InOrderService::new(Srv);
|
let mut srv = InOrderService::new(Srv);
|
||||||
|
|
||||||
let _ = lazy(|cx| srv.poll_ready(cx)).await;
|
let _ = lazy(|cx| srv.poll_ready(cx)).await;
|
||||||
@@ -251,7 +251,7 @@ mod tests {
|
|||||||
let res3 = srv.call(rx3);
|
let res3 = srv.call(rx3);
|
||||||
|
|
||||||
actix_rt::spawn(async move {
|
actix_rt::spawn(async move {
|
||||||
let _ = poll_fn(|cx| {
|
poll_fn(|cx| {
|
||||||
let _ = srv.poll_ready(cx);
|
let _ = srv.poll_ready(cx);
|
||||||
Poll::<()>::Pending
|
Poll::<()>::Pending
|
||||||
})
|
})
|
||||||
|
@@ -1,5 +1,23 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [0.2.4] - 2019-12-31
|
||||||
|
|
||||||
|
* Add `ResourceDef::resource_path_named()` path generation method
|
||||||
|
|
||||||
|
## [0.2.3] - 2019-12-25
|
||||||
|
|
||||||
|
* Add impl `IntoPattern` for `&String`
|
||||||
|
|
||||||
|
## [0.2.2] - 2019-12-25
|
||||||
|
|
||||||
|
* Use `IntoPattern` for `RouterBuilder::path()`
|
||||||
|
|
||||||
|
## [0.2.1] - 2019-12-25
|
||||||
|
|
||||||
|
* Add `IntoPattern` trait
|
||||||
|
|
||||||
|
* Add multi-pattern resources
|
||||||
|
|
||||||
## [0.2.0] - 2019-12-07
|
## [0.2.0] - 2019-12-07
|
||||||
|
|
||||||
* Update http to 0.2
|
* Update http to 0.2
|
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-router"
|
name = "actix-router"
|
||||||
version = "0.2.0"
|
version = "0.2.4"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Path router"
|
description = "Path router"
|
||||||
keywords = ["actix"]
|
keywords = ["actix"]
|
||||||
@@ -8,9 +8,7 @@ homepage = "https://actix.rs"
|
|||||||
repository = "https://github.com/actix/actix-net.git"
|
repository = "https://github.com/actix/actix-net.git"
|
||||||
documentation = "https://docs.rs/actix-router/"
|
documentation = "https://docs.rs/actix-router/"
|
||||||
license = "MIT/Apache-2.0"
|
license = "MIT/Apache-2.0"
|
||||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
workspace = ".."
|
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
name = "actix_router"
|
name = "actix_router"
|
||||||
@@ -21,8 +19,8 @@ default = ["http"]
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
regex = "1.3.1"
|
regex = "1.3.1"
|
||||||
serde = "1.0.80"
|
serde = "1.0.104"
|
||||||
bytestring = "0.1.0"
|
bytestring = "0.1.2"
|
||||||
log = "0.4.8"
|
log = "0.4.8"
|
||||||
http = { version="0.2.0", optional=true }
|
http = { version="0.2.0", optional=true }
|
||||||
|
|
||||||
|
@@ -492,7 +492,7 @@ mod tests {
|
|||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct Id {
|
struct Id {
|
||||||
id: String,
|
_id: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize)]
|
||||||
|
@@ -35,6 +35,100 @@ impl ResourcePath for bytestring::ByteString {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Helper trait for type that could be converted to path pattern
|
||||||
|
pub trait IntoPattern {
|
||||||
|
/// Signle patter
|
||||||
|
fn is_single(&self) -> bool;
|
||||||
|
|
||||||
|
fn patterns(&self) -> Vec<String>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IntoPattern for String {
|
||||||
|
fn is_single(&self) -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
fn patterns(&self) -> Vec<String> {
|
||||||
|
vec![self.clone()]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> IntoPattern for &'a String {
|
||||||
|
fn is_single(&self) -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
fn patterns(&self) -> Vec<String> {
|
||||||
|
vec![self.as_str().to_string()]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> IntoPattern for &'a str {
|
||||||
|
fn is_single(&self) -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
fn patterns(&self) -> Vec<String> {
|
||||||
|
vec![(*self).to_string()]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: AsRef<str>> IntoPattern for Vec<T> {
|
||||||
|
fn is_single(&self) -> bool {
|
||||||
|
self.len() == 1
|
||||||
|
}
|
||||||
|
|
||||||
|
fn patterns(&self) -> Vec<String> {
|
||||||
|
self.iter().map(|v| v.as_ref().to_string()).collect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! array_patterns (($tp:ty, $num:tt) => {
|
||||||
|
impl IntoPattern for [$tp; $num] {
|
||||||
|
fn is_single(&self) -> bool {
|
||||||
|
$num == 1
|
||||||
|
}
|
||||||
|
|
||||||
|
fn patterns(&self) -> Vec<String> {
|
||||||
|
self.iter().map(|v| v.to_string()).collect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
array_patterns!(&str, 1);
|
||||||
|
array_patterns!(&str, 2);
|
||||||
|
array_patterns!(&str, 3);
|
||||||
|
array_patterns!(&str, 4);
|
||||||
|
array_patterns!(&str, 5);
|
||||||
|
array_patterns!(&str, 6);
|
||||||
|
array_patterns!(&str, 7);
|
||||||
|
array_patterns!(&str, 8);
|
||||||
|
array_patterns!(&str, 9);
|
||||||
|
array_patterns!(&str, 10);
|
||||||
|
array_patterns!(&str, 11);
|
||||||
|
array_patterns!(&str, 12);
|
||||||
|
array_patterns!(&str, 13);
|
||||||
|
array_patterns!(&str, 14);
|
||||||
|
array_patterns!(&str, 15);
|
||||||
|
array_patterns!(&str, 16);
|
||||||
|
|
||||||
|
array_patterns!(String, 1);
|
||||||
|
array_patterns!(String, 2);
|
||||||
|
array_patterns!(String, 3);
|
||||||
|
array_patterns!(String, 4);
|
||||||
|
array_patterns!(String, 5);
|
||||||
|
array_patterns!(String, 6);
|
||||||
|
array_patterns!(String, 7);
|
||||||
|
array_patterns!(String, 8);
|
||||||
|
array_patterns!(String, 9);
|
||||||
|
array_patterns!(String, 10);
|
||||||
|
array_patterns!(String, 11);
|
||||||
|
array_patterns!(String, 12);
|
||||||
|
array_patterns!(String, 13);
|
||||||
|
array_patterns!(String, 14);
|
||||||
|
array_patterns!(String, 15);
|
||||||
|
array_patterns!(String, 16);
|
||||||
|
|
||||||
#[cfg(feature = "http")]
|
#[cfg(feature = "http")]
|
||||||
mod url;
|
mod url;
|
||||||
|
|
||||||
|
@@ -1,5 +1,4 @@
|
|||||||
use std::ops::Index;
|
use std::ops::Index;
|
||||||
use std::rc::Rc;
|
|
||||||
|
|
||||||
use serde::de;
|
use serde::de;
|
||||||
|
|
||||||
@@ -19,7 +18,7 @@ pub(crate) enum PathItem {
|
|||||||
pub struct Path<T> {
|
pub struct Path<T> {
|
||||||
path: T,
|
path: T,
|
||||||
pub(crate) skip: u16,
|
pub(crate) skip: u16,
|
||||||
pub(crate) segments: Vec<(Rc<String>, PathItem)>,
|
pub(crate) segments: Vec<(&'static str, PathItem)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: Default> Default for Path<T> {
|
impl<T: Default> Default for Path<T> {
|
||||||
@@ -96,7 +95,7 @@ impl<T: ResourcePath> Path<T> {
|
|||||||
self.skip += n;
|
self.skip += n;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn add(&mut self, name: Rc<String>, value: PathItem) {
|
pub(crate) fn add(&mut self, name: &'static str, value: PathItem) {
|
||||||
match value {
|
match value {
|
||||||
PathItem::Static(s) => self.segments.push((name, PathItem::Static(s))),
|
PathItem::Static(s) => self.segments.push((name, PathItem::Static(s))),
|
||||||
PathItem::Segment(begin, end) => self
|
PathItem::Segment(begin, end) => self
|
||||||
@@ -106,9 +105,8 @@ impl<T: ResourcePath> Path<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
pub fn add_static(&mut self, name: &str, value: &'static str) {
|
pub fn add_static(&mut self, name: &'static str, value: &'static str) {
|
||||||
self.segments
|
self.segments.push((name, PathItem::Static(value)));
|
||||||
.push((Rc::new(name.to_string()), PathItem::Static(value)));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
@@ -126,7 +124,7 @@ impl<T: ResourcePath> Path<T> {
|
|||||||
/// Get matched parameter by name without type conversion
|
/// Get matched parameter by name without type conversion
|
||||||
pub fn get(&self, key: &str) -> Option<&str> {
|
pub fn get(&self, key: &str) -> Option<&str> {
|
||||||
for item in self.segments.iter() {
|
for item in self.segments.iter() {
|
||||||
if key == item.0.as_str() {
|
if key == item.0 {
|
||||||
return match item.1 {
|
return match item.1 {
|
||||||
PathItem::Static(ref s) => Some(&s),
|
PathItem::Static(ref s) => Some(&s),
|
||||||
PathItem::Segment(s, e) => {
|
PathItem::Segment(s, e) => {
|
||||||
|
@@ -1,11 +1,11 @@
|
|||||||
use std::cmp::min;
|
use std::cmp::min;
|
||||||
|
use std::collections::HashMap;
|
||||||
use std::hash::{Hash, Hasher};
|
use std::hash::{Hash, Hasher};
|
||||||
use std::rc::Rc;
|
|
||||||
|
|
||||||
use regex::{escape, Regex};
|
use regex::{escape, Regex, RegexSet};
|
||||||
|
|
||||||
use crate::path::{Path, PathItem};
|
use crate::path::{Path, PathItem};
|
||||||
use crate::{Resource, ResourcePath};
|
use crate::{IntoPattern, Resource, ResourcePath};
|
||||||
|
|
||||||
const MAX_DYNAMIC_SEGMENTS: usize = 16;
|
const MAX_DYNAMIC_SEGMENTS: usize = 16;
|
||||||
|
|
||||||
@@ -31,22 +31,56 @@ enum PatternElement {
|
|||||||
enum PatternType {
|
enum PatternType {
|
||||||
Static(String),
|
Static(String),
|
||||||
Prefix(String),
|
Prefix(String),
|
||||||
Dynamic(Regex, Vec<Rc<String>>, usize),
|
Dynamic(Regex, Vec<&'static str>, usize),
|
||||||
|
DynamicSet(RegexSet, Vec<(Regex, Vec<&'static str>, usize)>),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ResourceDef {
|
impl ResourceDef {
|
||||||
/// Parse path pattern and create new `Pattern` instance.
|
/// Parse path pattern and create new `Pattern` instance.
|
||||||
///
|
///
|
||||||
/// Panics if path pattern is wrong.
|
/// Panics if path pattern is malformed.
|
||||||
pub fn new(path: &str) -> Self {
|
pub fn new<T: IntoPattern>(path: T) -> Self {
|
||||||
ResourceDef::with_prefix(path, false)
|
if path.is_single() {
|
||||||
|
let patterns = path.patterns();
|
||||||
|
ResourceDef::with_prefix(&patterns[0], false)
|
||||||
|
} else {
|
||||||
|
let set = path.patterns();
|
||||||
|
let mut data = Vec::new();
|
||||||
|
let mut re_set = Vec::new();
|
||||||
|
|
||||||
|
for path in set {
|
||||||
|
let (pattern, _, _, len) = ResourceDef::parse(&path, false);
|
||||||
|
|
||||||
|
let re = match Regex::new(&pattern) {
|
||||||
|
Ok(re) => re,
|
||||||
|
Err(err) => panic!("Wrong path pattern: \"{}\" {}", path, err),
|
||||||
|
};
|
||||||
|
// actix creates one router per thread
|
||||||
|
let names: Vec<_> = re
|
||||||
|
.capture_names()
|
||||||
|
.filter_map(|name| {
|
||||||
|
name.map(|name| Box::leak(Box::new(name.to_owned())).as_str())
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
data.push((re, names, len));
|
||||||
|
re_set.push(pattern);
|
||||||
|
}
|
||||||
|
|
||||||
|
ResourceDef {
|
||||||
|
id: 0,
|
||||||
|
tp: PatternType::DynamicSet(RegexSet::new(re_set).unwrap(), data),
|
||||||
|
elements: Vec::new(),
|
||||||
|
name: String::new(),
|
||||||
|
pattern: "".to_owned(),
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Parse path pattern and create new `Pattern` instance.
|
/// Parse path pattern and create new `Pattern` instance.
|
||||||
///
|
///
|
||||||
/// Use `prefix` type instead of `static`.
|
/// Use `prefix` type instead of `static`.
|
||||||
///
|
///
|
||||||
/// Panics if path regex pattern is wrong.
|
/// Panics if path regex pattern is malformed.
|
||||||
pub fn prefix(path: &str) -> Self {
|
pub fn prefix(path: &str) -> Self {
|
||||||
ResourceDef::with_prefix(path, true)
|
ResourceDef::with_prefix(path, true)
|
||||||
}
|
}
|
||||||
@@ -57,7 +91,7 @@ impl ResourceDef {
|
|||||||
///
|
///
|
||||||
/// Use `prefix` type instead of `static`.
|
/// Use `prefix` type instead of `static`.
|
||||||
///
|
///
|
||||||
/// Panics if path regex pattern is wrong.
|
/// Panics if path regex pattern is malformed.
|
||||||
pub fn root_prefix(path: &str) -> Self {
|
pub fn root_prefix(path: &str) -> Self {
|
||||||
ResourceDef::with_prefix(&insert_slash(path), true)
|
ResourceDef::with_prefix(&insert_slash(path), true)
|
||||||
}
|
}
|
||||||
@@ -85,7 +119,9 @@ impl ResourceDef {
|
|||||||
// actix creates one router per thread
|
// actix creates one router per thread
|
||||||
let names = re
|
let names = re
|
||||||
.capture_names()
|
.capture_names()
|
||||||
.filter_map(|name| name.map(|name| Rc::new(name.to_owned())))
|
.filter_map(|name| {
|
||||||
|
name.map(|name| Box::leak(Box::new(name.to_owned())).as_str())
|
||||||
|
})
|
||||||
.collect();
|
.collect();
|
||||||
PatternType::Dynamic(re, names, len)
|
PatternType::Dynamic(re, names, len)
|
||||||
} else if for_prefix {
|
} else if for_prefix {
|
||||||
@@ -123,8 +159,9 @@ impl ResourceDef {
|
|||||||
pub fn is_match(&self, path: &str) -> bool {
|
pub fn is_match(&self, path: &str) -> bool {
|
||||||
match self.tp {
|
match self.tp {
|
||||||
PatternType::Static(ref s) => s == path,
|
PatternType::Static(ref s) => s == path,
|
||||||
PatternType::Dynamic(ref re, _, _) => re.is_match(path),
|
|
||||||
PatternType::Prefix(ref s) => path.starts_with(s),
|
PatternType::Prefix(ref s) => path.starts_with(s),
|
||||||
|
PatternType::Dynamic(ref re, _, _) => re.is_match(path),
|
||||||
|
PatternType::DynamicSet(ref re, _) => re.is_match(path),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -176,6 +213,30 @@ impl ResourceDef {
|
|||||||
};
|
};
|
||||||
Some(min(plen, len))
|
Some(min(plen, len))
|
||||||
}
|
}
|
||||||
|
PatternType::DynamicSet(ref re, ref params) => {
|
||||||
|
if let Some(idx) = re.matches(path).into_iter().next() {
|
||||||
|
let (ref pattern, _, len) = params[idx];
|
||||||
|
if let Some(captures) = pattern.captures(path) {
|
||||||
|
let mut pos = 0;
|
||||||
|
let mut passed = false;
|
||||||
|
for capture in captures.iter() {
|
||||||
|
if let Some(ref m) = capture {
|
||||||
|
if !passed {
|
||||||
|
passed = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
pos = m.end();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(pos + len)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -190,6 +251,25 @@ impl ResourceDef {
|
|||||||
false
|
false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
PatternType::Prefix(ref s) => {
|
||||||
|
let rpath = path.path();
|
||||||
|
let len = if s == rpath {
|
||||||
|
s.len()
|
||||||
|
} else if rpath.starts_with(s)
|
||||||
|
&& (s.ends_with('/') || rpath.split_at(s.len()).1.starts_with('/'))
|
||||||
|
{
|
||||||
|
if s.ends_with('/') {
|
||||||
|
s.len() - 1
|
||||||
|
} else {
|
||||||
|
s.len()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let rpath_len = rpath.len();
|
||||||
|
path.skip(min(rpath_len, len) as u16);
|
||||||
|
true
|
||||||
|
}
|
||||||
PatternType::Dynamic(ref re, ref names, len) => {
|
PatternType::Dynamic(ref re, ref names, len) => {
|
||||||
let mut idx = 0;
|
let mut idx = 0;
|
||||||
let mut pos = 0;
|
let mut pos = 0;
|
||||||
@@ -214,29 +294,45 @@ impl ResourceDef {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
for idx in 0..idx {
|
for idx in 0..idx {
|
||||||
path.add(names[idx].clone(), segments[idx]);
|
path.add(names[idx], segments[idx]);
|
||||||
}
|
}
|
||||||
path.skip((pos + len) as u16);
|
path.skip((pos + len) as u16);
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
PatternType::Prefix(ref s) => {
|
PatternType::DynamicSet(ref re, ref params) => {
|
||||||
let rpath = path.path();
|
if let Some(idx) = re.matches(path.path()).into_iter().next() {
|
||||||
let len = if s == rpath {
|
let (ref pattern, ref names, len) = params[idx];
|
||||||
s.len()
|
let mut idx = 0;
|
||||||
} else if rpath.starts_with(s)
|
let mut pos = 0;
|
||||||
&& (s.ends_with('/') || rpath.split_at(s.len()).1.starts_with('/'))
|
let mut segments: [PathItem; MAX_DYNAMIC_SEGMENTS] =
|
||||||
{
|
[PathItem::Static(""); MAX_DYNAMIC_SEGMENTS];
|
||||||
if s.ends_with('/') {
|
|
||||||
s.len() - 1
|
if let Some(captures) = pattern.captures(path.path()) {
|
||||||
|
for (no, name) in names.iter().enumerate() {
|
||||||
|
if let Some(m) = captures.name(&name) {
|
||||||
|
idx += 1;
|
||||||
|
pos = m.end();
|
||||||
|
segments[no] =
|
||||||
|
PathItem::Segment(m.start() as u16, m.end() as u16);
|
||||||
|
} else {
|
||||||
|
log::error!(
|
||||||
|
"Dynamic path match but not all segments found: {}",
|
||||||
|
name
|
||||||
|
);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
s.len()
|
return false;
|
||||||
}
|
}
|
||||||
|
for idx in 0..idx {
|
||||||
|
path.add(names[idx], segments[idx]);
|
||||||
|
}
|
||||||
|
path.skip((pos + len) as u16);
|
||||||
|
true
|
||||||
} else {
|
} else {
|
||||||
return false;
|
false
|
||||||
};
|
}
|
||||||
let rpath_len = rpath.len();
|
|
||||||
path.skip(min(rpath_len, len) as u16);
|
|
||||||
true
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -263,6 +359,30 @@ impl ResourceDef {
|
|||||||
false
|
false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
PatternType::Prefix(ref s) => {
|
||||||
|
let len = {
|
||||||
|
let rpath = res.resource_path().path();
|
||||||
|
if s == rpath {
|
||||||
|
s.len()
|
||||||
|
} else if rpath.starts_with(s)
|
||||||
|
&& (s.ends_with('/') || rpath.split_at(s.len()).1.starts_with('/'))
|
||||||
|
{
|
||||||
|
if s.ends_with('/') {
|
||||||
|
s.len() - 1
|
||||||
|
} else {
|
||||||
|
s.len()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if !check(res, user_data) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let path = res.resource_path();
|
||||||
|
path.skip(min(path.path().len(), len) as u16);
|
||||||
|
true
|
||||||
|
}
|
||||||
PatternType::Dynamic(ref re, ref names, len) => {
|
PatternType::Dynamic(ref re, ref names, len) => {
|
||||||
let mut idx = 0;
|
let mut idx = 0;
|
||||||
let mut pos = 0;
|
let mut pos = 0;
|
||||||
@@ -293,34 +413,52 @@ impl ResourceDef {
|
|||||||
|
|
||||||
let path = res.resource_path();
|
let path = res.resource_path();
|
||||||
for idx in 0..idx {
|
for idx in 0..idx {
|
||||||
path.add(names[idx].clone(), segments[idx]);
|
path.add(names[idx], segments[idx]);
|
||||||
}
|
}
|
||||||
path.skip((pos + len) as u16);
|
path.skip((pos + len) as u16);
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
PatternType::Prefix(ref s) => {
|
PatternType::DynamicSet(ref re, ref params) => {
|
||||||
let len = {
|
let path = res.resource_path().path();
|
||||||
let rpath = res.resource_path().path();
|
if let Some(idx) = re.matches(path).into_iter().next() {
|
||||||
if s == rpath {
|
let (ref pattern, ref names, len) = params[idx];
|
||||||
s.len()
|
let mut idx = 0;
|
||||||
} else if rpath.starts_with(s)
|
let mut pos = 0;
|
||||||
&& (s.ends_with('/') || rpath.split_at(s.len()).1.starts_with('/'))
|
let mut segments: [PathItem; MAX_DYNAMIC_SEGMENTS] =
|
||||||
{
|
[PathItem::Static(""); MAX_DYNAMIC_SEGMENTS];
|
||||||
if s.ends_with('/') {
|
|
||||||
s.len() - 1
|
if let Some(captures) = pattern.captures(path) {
|
||||||
} else {
|
for (no, name) in names.iter().enumerate() {
|
||||||
s.len()
|
if let Some(m) = captures.name(&name) {
|
||||||
|
idx += 1;
|
||||||
|
pos = m.end();
|
||||||
|
segments[no] =
|
||||||
|
PathItem::Segment(m.start() as u16, m.end() as u16);
|
||||||
|
} else {
|
||||||
|
log::error!(
|
||||||
|
"Dynamic path match but not all segments found: {}",
|
||||||
|
name
|
||||||
|
);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
};
|
|
||||||
if !check(res, user_data) {
|
if !check(res, user_data) {
|
||||||
return false;
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
let path = res.resource_path();
|
||||||
|
for idx in 0..idx {
|
||||||
|
path.add(names[idx], segments[idx]);
|
||||||
|
}
|
||||||
|
path.skip((pos + len) as u16);
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
}
|
}
|
||||||
let path = res.resource_path();
|
|
||||||
path.skip(min(path.path().len(), len) as u16);
|
|
||||||
true
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -348,7 +486,45 @@ impl ResourceDef {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
PatternType::DynamicSet(..) => {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build resource path from elements. Returns `true` on success.
|
||||||
|
pub fn resource_path_named<K, V, S>(
|
||||||
|
&self,
|
||||||
|
path: &mut String,
|
||||||
|
elements: &HashMap<K, V, S>,
|
||||||
|
) -> bool
|
||||||
|
where
|
||||||
|
K: std::borrow::Borrow<str> + Eq + Hash,
|
||||||
|
V: AsRef<str>,
|
||||||
|
S: std::hash::BuildHasher,
|
||||||
|
{
|
||||||
|
match self.tp {
|
||||||
|
PatternType::Prefix(ref p) => path.push_str(p),
|
||||||
|
PatternType::Static(ref p) => path.push_str(p),
|
||||||
|
PatternType::Dynamic(..) => {
|
||||||
|
for el in &self.elements {
|
||||||
|
match *el {
|
||||||
|
PatternElement::Str(ref s) => path.push_str(s),
|
||||||
|
PatternElement::Var(ref name) => {
|
||||||
|
if let Some(val) = elements.get(name) {
|
||||||
|
path.push_str(val.as_ref())
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
PatternType::DynamicSet(..) => {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -476,7 +652,7 @@ impl<'a> From<&'a str> for ResourceDef {
|
|||||||
|
|
||||||
impl From<String> for ResourceDef {
|
impl From<String> for ResourceDef {
|
||||||
fn from(path: String) -> ResourceDef {
|
fn from(path: String) -> ResourceDef {
|
||||||
ResourceDef::new(&path)
|
ResourceDef::new(path)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -558,6 +734,66 @@ mod tests {
|
|||||||
assert_eq!(path.get("id").unwrap(), "012345");
|
assert_eq!(path.get("id").unwrap(), "012345");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::cognitive_complexity)]
|
||||||
|
#[test]
|
||||||
|
fn test_dynamic_set() {
|
||||||
|
let re = ResourceDef::new(vec![
|
||||||
|
"/user/{id}",
|
||||||
|
"/v{version}/resource/{id}",
|
||||||
|
"/{id:[[:digit:]]{6}}",
|
||||||
|
]);
|
||||||
|
assert!(re.is_match("/user/profile"));
|
||||||
|
assert!(re.is_match("/user/2345"));
|
||||||
|
assert!(!re.is_match("/user/2345/"));
|
||||||
|
assert!(!re.is_match("/user/2345/sdg"));
|
||||||
|
|
||||||
|
let mut path = Path::new("/user/profile");
|
||||||
|
assert!(re.match_path(&mut path));
|
||||||
|
assert_eq!(path.get("id").unwrap(), "profile");
|
||||||
|
|
||||||
|
let mut path = Path::new("/user/1245125");
|
||||||
|
assert!(re.match_path(&mut path));
|
||||||
|
assert_eq!(path.get("id").unwrap(), "1245125");
|
||||||
|
|
||||||
|
assert!(re.is_match("/v1/resource/320120"));
|
||||||
|
assert!(!re.is_match("/v/resource/1"));
|
||||||
|
assert!(!re.is_match("/resource"));
|
||||||
|
|
||||||
|
let mut path = Path::new("/v151/resource/adahg32");
|
||||||
|
assert!(re.match_path(&mut path));
|
||||||
|
assert_eq!(path.get("version").unwrap(), "151");
|
||||||
|
assert_eq!(path.get("id").unwrap(), "adahg32");
|
||||||
|
|
||||||
|
assert!(re.is_match("/012345"));
|
||||||
|
assert!(!re.is_match("/012"));
|
||||||
|
assert!(!re.is_match("/01234567"));
|
||||||
|
assert!(!re.is_match("/XXXXXX"));
|
||||||
|
|
||||||
|
let mut path = Path::new("/012345");
|
||||||
|
assert!(re.match_path(&mut path));
|
||||||
|
assert_eq!(path.get("id").unwrap(), "012345");
|
||||||
|
|
||||||
|
let re = ResourceDef::new([
|
||||||
|
"/user/{id}",
|
||||||
|
"/v{version}/resource/{id}",
|
||||||
|
"/{id:[[:digit:]]{6}}",
|
||||||
|
]);
|
||||||
|
assert!(re.is_match("/user/profile"));
|
||||||
|
assert!(re.is_match("/user/2345"));
|
||||||
|
assert!(!re.is_match("/user/2345/"));
|
||||||
|
assert!(!re.is_match("/user/2345/sdg"));
|
||||||
|
|
||||||
|
let re = ResourceDef::new([
|
||||||
|
"/user/{id}".to_string(),
|
||||||
|
"/v{version}/resource/{id}".to_string(),
|
||||||
|
"/{id:[[:digit:]]{6}}".to_string(),
|
||||||
|
]);
|
||||||
|
assert!(re.is_match("/user/profile"));
|
||||||
|
assert!(re.is_match("/user/2345"));
|
||||||
|
assert!(!re.is_match("/user/2345/"));
|
||||||
|
assert!(!re.is_match("/user/2345/sdg"));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_parse_tail() {
|
fn test_parse_tail() {
|
||||||
let re = ResourceDef::new("/user/-{id}*");
|
let re = ResourceDef::new("/user/-{id}*");
|
||||||
@@ -659,4 +895,50 @@ mod tests {
|
|||||||
assert_eq!(&path["name"], "test2");
|
assert_eq!(&path["name"], "test2");
|
||||||
assert_eq!(&path[0], "test2");
|
assert_eq!(&path[0], "test2");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_resource_path() {
|
||||||
|
let mut s = String::new();
|
||||||
|
let resource = ResourceDef::new("/user/{item1}/test");
|
||||||
|
assert!(resource.resource_path(&mut s, &mut (&["user1"]).iter()));
|
||||||
|
assert_eq!(s, "/user/user1/test");
|
||||||
|
|
||||||
|
let mut s = String::new();
|
||||||
|
let resource = ResourceDef::new("/user/{item1}/{item2}/test");
|
||||||
|
assert!(resource.resource_path(&mut s, &mut (&["item", "item2"]).iter()));
|
||||||
|
assert_eq!(s, "/user/item/item2/test");
|
||||||
|
|
||||||
|
let mut s = String::new();
|
||||||
|
let resource = ResourceDef::new("/user/{item1}/{item2}");
|
||||||
|
assert!(resource.resource_path(&mut s, &mut (&["item", "item2"]).iter()));
|
||||||
|
assert_eq!(s, "/user/item/item2");
|
||||||
|
|
||||||
|
let mut s = String::new();
|
||||||
|
let resource = ResourceDef::new("/user/{item1}/{item2}/");
|
||||||
|
assert!(resource.resource_path(&mut s, &mut (&["item", "item2"]).iter()));
|
||||||
|
assert_eq!(s, "/user/item/item2/");
|
||||||
|
|
||||||
|
let mut s = String::new();
|
||||||
|
assert!(!resource.resource_path(&mut s, &mut (&["item"]).iter()));
|
||||||
|
|
||||||
|
let mut s = String::new();
|
||||||
|
assert!(resource.resource_path(&mut s, &mut (&["item", "item2"]).iter()));
|
||||||
|
assert_eq!(s, "/user/item/item2/");
|
||||||
|
assert!(!resource.resource_path(&mut s, &mut (&["item"]).iter()));
|
||||||
|
|
||||||
|
let mut s = String::new();
|
||||||
|
assert!(resource.resource_path(&mut s, &mut vec!["item", "item2"].into_iter()));
|
||||||
|
assert_eq!(s, "/user/item/item2/");
|
||||||
|
|
||||||
|
let mut map = HashMap::new();
|
||||||
|
map.insert("item1", "item");
|
||||||
|
|
||||||
|
let mut s = String::new();
|
||||||
|
assert!(!resource.resource_path_named(&mut s, &map));
|
||||||
|
|
||||||
|
let mut s = String::new();
|
||||||
|
map.insert("item2", "item2");
|
||||||
|
assert!(resource.resource_path_named(&mut s, &map));
|
||||||
|
assert_eq!(s, "/user/item/item2/");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,4 +1,4 @@
|
|||||||
use crate::{Resource, ResourceDef, ResourcePath};
|
use crate::{IntoPattern, Resource, ResourceDef, ResourcePath};
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq)]
|
#[derive(Debug, Copy, Clone, PartialEq)]
|
||||||
pub struct ResourceId(pub u16);
|
pub struct ResourceId(pub u16);
|
||||||
@@ -70,7 +70,11 @@ pub struct RouterBuilder<T, U = ()> {
|
|||||||
|
|
||||||
impl<T, U> RouterBuilder<T, U> {
|
impl<T, U> RouterBuilder<T, U> {
|
||||||
/// Register resource for specified path.
|
/// Register resource for specified path.
|
||||||
pub fn path(&mut self, path: &str, resource: T) -> &mut (ResourceDef, T, Option<U>) {
|
pub fn path<P: IntoPattern>(
|
||||||
|
&mut self,
|
||||||
|
path: P,
|
||||||
|
resource: T,
|
||||||
|
) -> &mut (ResourceDef, T, Option<U>) {
|
||||||
self.resources
|
self.resources
|
||||||
.push((ResourceDef::new(path), resource, None));
|
.push((ResourceDef::new(path), resource, None));
|
||||||
self.resources.last_mut().unwrap()
|
self.resources.last_mut().unwrap()
|
||||||
@@ -100,6 +104,7 @@ mod tests {
|
|||||||
use crate::path::Path;
|
use crate::path::Path;
|
||||||
use crate::router::{ResourceId, Router};
|
use crate::router::{ResourceId, Router};
|
||||||
|
|
||||||
|
#[allow(clippy::cognitive_complexity)]
|
||||||
#[test]
|
#[test]
|
||||||
fn test_recognizer_1() {
|
fn test_recognizer_1() {
|
||||||
let mut router = Router::<usize>::build();
|
let mut router = Router::<usize>::build();
|
||||||
|
@@ -1,5 +1,13 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [0.1.4] - 2020-01-14
|
||||||
|
|
||||||
|
* Fix `AsRef<str>` impl
|
||||||
|
|
||||||
|
## [0.1.3] - 2020-01-13
|
||||||
|
|
||||||
|
* Add `PartialEq<T: AsRef<str>>`, `AsRef<[u8]>` impls
|
||||||
|
|
||||||
## [0.1.2] - 2019-12-22
|
## [0.1.2] - 2019-12-22
|
||||||
|
|
||||||
* Fix `new()` method
|
* Fix `new()` method
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "bytestring"
|
name = "bytestring"
|
||||||
version = "0.1.2"
|
version = "0.1.4"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "A UTF-8 encoded string with Bytes as a storage"
|
description = "A UTF-8 encoded string with Bytes as a storage"
|
||||||
keywords = ["actix"]
|
keywords = ["actix"]
|
||||||
|
@@ -7,7 +7,7 @@ use bytes::Bytes;
|
|||||||
/// A utf-8 encoded string with [`Bytes`] as a storage.
|
/// A utf-8 encoded string with [`Bytes`] as a storage.
|
||||||
///
|
///
|
||||||
/// [`Bytes`]: https://docs.rs/bytes/0.5.3/bytes/struct.Bytes.html
|
/// [`Bytes`]: https://docs.rs/bytes/0.5.3/bytes/struct.Bytes.html
|
||||||
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Default)]
|
#[derive(Clone, Eq, Ord, PartialOrd, Default)]
|
||||||
pub struct ByteString(Bytes);
|
pub struct ByteString(Bytes);
|
||||||
|
|
||||||
impl ByteString {
|
impl ByteString {
|
||||||
@@ -43,6 +43,24 @@ impl PartialEq<str> for ByteString {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<T: AsRef<str>> PartialEq<T> for ByteString {
|
||||||
|
fn eq(&self, other: &T) -> bool {
|
||||||
|
&self[..] == other.as_ref()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AsRef<[u8]> for ByteString {
|
||||||
|
fn as_ref(&self) -> &[u8] {
|
||||||
|
self.0.as_ref()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AsRef<str> for ByteString {
|
||||||
|
fn as_ref(&self) -> &str {
|
||||||
|
&*self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl hash::Hash for ByteString {
|
impl hash::Hash for ByteString {
|
||||||
fn hash<H: hash::Hasher>(&self, state: &mut H) {
|
fn hash<H: hash::Hasher>(&self, state: &mut H) {
|
||||||
(**self).hash(state);
|
(**self).hash(state);
|
||||||
@@ -147,6 +165,14 @@ mod test {
|
|||||||
use std::collections::hash_map::DefaultHasher;
|
use std::collections::hash_map::DefaultHasher;
|
||||||
use std::hash::{Hash, Hasher};
|
use std::hash::{Hash, Hasher};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_partial_eq() {
|
||||||
|
let s: ByteString = ByteString::from_static("test");
|
||||||
|
assert_eq!(s, "test");
|
||||||
|
assert_eq!(s, *"test");
|
||||||
|
assert_eq!(s, "test".to_string());
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_new() {
|
fn test_new() {
|
||||||
let _: ByteString = ByteString::new();
|
let _: ByteString = ByteString::new();
|
||||||
@@ -167,6 +193,8 @@ mod test {
|
|||||||
fn test_from_string() {
|
fn test_from_string() {
|
||||||
let s: ByteString = "hello".to_string().into();
|
let s: ByteString = "hello".to_string().into();
|
||||||
assert_eq!(&s, "hello");
|
assert_eq!(&s, "hello");
|
||||||
|
let t: &str = s.as_ref();
|
||||||
|
assert_eq!(t, "hello");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -176,7 +204,7 @@ mod test {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_from_static_str() {
|
fn test_from_static_str() {
|
||||||
const _S: ByteString = ByteString::from_static("hello");
|
static _S: ByteString = ByteString::from_static("hello");
|
||||||
let _ = ByteString::from_static("str");
|
let _ = ByteString::from_static("str");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user