mirror of
https://github.com/fafhrd91/actix-net
synced 2025-08-15 12:30:20 +02:00
Compare commits
20 Commits
server-v2.
...
remove-mps
Author | SHA1 | Date | |
---|---|---|---|
|
45e3a5c0e6 | ||
|
789e6a8a46 | ||
|
6e590fd042 | ||
|
fa8ded3a34 | ||
|
564acfbf3a | ||
|
841c611233 | ||
|
81a2b6a425 | ||
|
a6e79453d0 | ||
|
17f711a9d6 | ||
|
c3be839a69 | ||
|
8d74cf387d | ||
|
7e483cc356 | ||
|
75d7ae3139 | ||
|
2cfe1d88ad | ||
|
cb07ead392 | ||
|
32543809f9 | ||
|
eb4d29e15e | ||
|
7ee42b50b4 | ||
|
0da848e4ae | ||
|
5f80d85010 |
103
.github/workflows/ci.yml
vendored
Normal file
103
.github/workflows/ci.yml
vendored
Normal file
@@ -0,0 +1,103 @@
|
|||||||
|
name: CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
types: [opened, synchronize, reopened]
|
||||||
|
push:
|
||||||
|
branches: [master]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build_and_test:
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
target:
|
||||||
|
- { name: Linux, os: ubuntu-latest, triple: x86_64-unknown-linux-gnu }
|
||||||
|
- { name: macOS, os: macos-latest, triple: x86_64-apple-darwin }
|
||||||
|
- { name: Windows, os: windows-latest, triple: x86_64-pc-windows-msvc }
|
||||||
|
- { name: Windows (MinGW), os: windows-latest, triple: x86_64-pc-windows-gnu }
|
||||||
|
- { name: Windows (32-bit), os: windows-latest, triple: i686-pc-windows-msvc }
|
||||||
|
version:
|
||||||
|
- 1.46.0 # MSRV
|
||||||
|
- stable
|
||||||
|
- nightly
|
||||||
|
|
||||||
|
name: ${{ matrix.target.name }} / ${{ matrix.version }}
|
||||||
|
runs-on: ${{ matrix.target.os }}
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Setup Routing
|
||||||
|
if: matrix.target.os == 'macos-latest'
|
||||||
|
run: sudo ifconfig lo0 alias 127.0.0.3
|
||||||
|
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
|
||||||
|
- name: Install ${{ matrix.version }}
|
||||||
|
uses: actions-rs/toolchain@v1
|
||||||
|
with:
|
||||||
|
toolchain: ${{ matrix.version }}-${{ matrix.target.triple }}
|
||||||
|
profile: minimal
|
||||||
|
override: true
|
||||||
|
|
||||||
|
- name: Install MSYS2
|
||||||
|
if: matrix.target.triple == 'x86_64-pc-windows-gnu'
|
||||||
|
uses: msys2/setup-msys2@v2
|
||||||
|
- name: Install MinGW Packages
|
||||||
|
if: matrix.target.triple == 'x86_64-pc-windows-gnu'
|
||||||
|
run: |
|
||||||
|
msys2 -c 'pacman -Sy --noconfirm pacman'
|
||||||
|
msys2 -c 'pacman --noconfirm -S base-devel pkg-config'
|
||||||
|
|
||||||
|
- name: Generate Cargo.lock
|
||||||
|
uses: actions-rs/cargo@v1
|
||||||
|
with:
|
||||||
|
command: generate-lockfile
|
||||||
|
- name: Cache Dependencies
|
||||||
|
uses: Swatinem/rust-cache@v1.2.0
|
||||||
|
|
||||||
|
- name: Install cargo-hack
|
||||||
|
uses: actions-rs/cargo@v1
|
||||||
|
with:
|
||||||
|
command: install
|
||||||
|
args: cargo-hack
|
||||||
|
|
||||||
|
- name: check minimal
|
||||||
|
uses: actions-rs/cargo@v1
|
||||||
|
with:
|
||||||
|
command: hack
|
||||||
|
args: --clean-per-run check --workspace --no-default-features --tests
|
||||||
|
|
||||||
|
- name: check full
|
||||||
|
uses: actions-rs/cargo@v1
|
||||||
|
with:
|
||||||
|
command: check
|
||||||
|
args: --workspace --bins --examples --tests
|
||||||
|
|
||||||
|
- name: tests
|
||||||
|
if: matrix.target.triple != 'x86_64-pc-windows-gnu'
|
||||||
|
uses: actions-rs/cargo@v1
|
||||||
|
with:
|
||||||
|
command: test
|
||||||
|
args: --workspace --all-features --no-fail-fast -- --nocapture
|
||||||
|
|
||||||
|
- name: Generate coverage file
|
||||||
|
if: >
|
||||||
|
matrix.target.os == 'ubuntu-latest'
|
||||||
|
&& matrix.version == 'stable'
|
||||||
|
&& github.ref == 'refs/heads/master'
|
||||||
|
run: |
|
||||||
|
cargo install cargo-tarpaulin
|
||||||
|
cargo tarpaulin --out Xml --verbose
|
||||||
|
- name: Upload to Codecov
|
||||||
|
if: >
|
||||||
|
matrix.target.os == 'ubuntu-latest'
|
||||||
|
&& matrix.version == 'stable'
|
||||||
|
&& github.ref == 'refs/heads/master'
|
||||||
|
uses: codecov/codecov-action@v1
|
||||||
|
with:
|
||||||
|
file: cobertura.xml
|
||||||
|
|
||||||
|
- name: Clear the cargo caches
|
||||||
|
run: |
|
||||||
|
cargo install cargo-cache --no-default-features --features ci-autoclean
|
||||||
|
cargo-cache
|
28
.github/workflows/clippy-fmt.yml
vendored
28
.github/workflows/clippy-fmt.yml
vendored
@@ -1,34 +1,42 @@
|
|||||||
|
name: Lint
|
||||||
|
|
||||||
on:
|
on:
|
||||||
pull_request:
|
pull_request:
|
||||||
types: [opened, synchronize, reopened]
|
types: [opened, synchronize, reopened]
|
||||||
|
|
||||||
name: Clippy and rustfmt Check
|
|
||||||
jobs:
|
jobs:
|
||||||
clippy_check:
|
fmt:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
|
|
||||||
- uses: actions-rs/toolchain@v1
|
- name: Install Rust
|
||||||
|
uses: actions-rs/toolchain@v1
|
||||||
with:
|
with:
|
||||||
toolchain: stable
|
toolchain: stable
|
||||||
components: rustfmt
|
|
||||||
profile: minimal
|
profile: minimal
|
||||||
|
components: rustfmt
|
||||||
override: true
|
override: true
|
||||||
- name: Check with rustfmt
|
- name: Rustfmt Check
|
||||||
uses: actions-rs/cargo@v1
|
uses: actions-rs/cargo@v1
|
||||||
with:
|
with:
|
||||||
command: fmt
|
command: fmt
|
||||||
args: --all -- --check
|
args: --all -- --check
|
||||||
|
|
||||||
- uses: actions-rs/toolchain@v1
|
clippy:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
|
||||||
|
- name: Install Rust
|
||||||
|
uses: actions-rs/toolchain@v1
|
||||||
with:
|
with:
|
||||||
toolchain: nightly
|
toolchain: stable
|
||||||
components: clippy
|
|
||||||
profile: minimal
|
profile: minimal
|
||||||
|
components: clippy
|
||||||
override: true
|
override: true
|
||||||
- name: Check with Clippy
|
- name: Clippy Check
|
||||||
uses: actions-rs/clippy-check@v1
|
uses: actions-rs/clippy-check@v1
|
||||||
with:
|
with:
|
||||||
token: ${{ secrets.GITHUB_TOKEN }}
|
token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
args: --workspace --tests
|
args: --workspace --tests --all-features
|
||||||
|
82
.github/workflows/linux.yml
vendored
82
.github/workflows/linux.yml
vendored
@@ -1,82 +0,0 @@
|
|||||||
name: CI (Linux)
|
|
||||||
|
|
||||||
on:
|
|
||||||
pull_request:
|
|
||||||
types: [opened, synchronize, reopened]
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- master
|
|
||||||
- '1.0'
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
build_and_test:
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
version:
|
|
||||||
- 1.46.0
|
|
||||||
- stable
|
|
||||||
- nightly
|
|
||||||
|
|
||||||
name: ${{ matrix.version }} - x86_64-unknown-linux-gnu
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v2
|
|
||||||
|
|
||||||
- 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 dirs
|
|
||||||
uses: actions/cache@v2
|
|
||||||
with:
|
|
||||||
path:
|
|
||||||
~/.cargo/registry
|
|
||||||
~/.cargo/git
|
|
||||||
~/.cargo/bin
|
|
||||||
key: ${{ matrix.version }}-x86_64-unknown-linux-gnu-cargo-trimmed-${{ hashFiles('**/Cargo.lock') }}
|
|
||||||
- name: Cache cargo build
|
|
||||||
uses: actions/cache@v2
|
|
||||||
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: --workspace --bins --examples --tests
|
|
||||||
|
|
||||||
- name: tests
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
timeout-minutes: 40
|
|
||||||
with:
|
|
||||||
command: test
|
|
||||||
args: --workspace --exclude=actix-tls --no-fail-fast -- --nocapture
|
|
||||||
|
|
||||||
- name: Generate coverage file
|
|
||||||
if: matrix.version == 'stable' && (github.ref == 'refs/heads/master' || github.event_name == 'pull_request')
|
|
||||||
run: |
|
|
||||||
cargo install cargo-tarpaulin
|
|
||||||
cargo tarpaulin --out Xml --workspace
|
|
||||||
|
|
||||||
- name: Upload to Codecov
|
|
||||||
if: matrix.version == 'stable' && (github.ref == 'refs/heads/master' || github.event_name == 'pull_request')
|
|
||||||
uses: codecov/codecov-action@v1
|
|
||||||
with:
|
|
||||||
file: cobertura.xml
|
|
||||||
|
|
||||||
- name: Clear the cargo caches
|
|
||||||
run: |
|
|
||||||
rustup update stable
|
|
||||||
rustup override set stable
|
|
||||||
cargo install cargo-cache --no-default-features --features ci-autoclean
|
|
||||||
cargo-cache
|
|
43
.github/workflows/macos.yml
vendored
43
.github/workflows/macos.yml
vendored
@@ -1,43 +0,0 @@
|
|||||||
name: CI (macOS)
|
|
||||||
|
|
||||||
on:
|
|
||||||
pull_request:
|
|
||||||
types: [opened, synchronize, reopened]
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- master
|
|
||||||
- '1.0'
|
|
||||||
|
|
||||||
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@v2
|
|
||||||
|
|
||||||
- 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: --workspace --bins --examples --tests
|
|
||||||
|
|
||||||
- name: tests
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: test
|
|
||||||
args: --workspace --exclude=actix-tls --no-fail-fast -- --nocapture
|
|
35
.github/workflows/upload-doc.yml
vendored
Normal file
35
.github/workflows/upload-doc.yml
vendored
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
name: Upload documentation
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [master]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
|
||||||
|
- name: Install Rust
|
||||||
|
uses: actions-rs/toolchain@v1
|
||||||
|
with:
|
||||||
|
toolchain: nightly-x86_64-unknown-linux-gnu
|
||||||
|
profile: minimal
|
||||||
|
override: true
|
||||||
|
|
||||||
|
- name: Build Docs
|
||||||
|
uses: actions-rs/cargo@v1
|
||||||
|
with:
|
||||||
|
command: doc
|
||||||
|
args: --workspace --all-features --no-deps
|
||||||
|
|
||||||
|
- name: Tweak HTML
|
||||||
|
run: echo '<meta http-equiv="refresh" content="0;url=actix_server/index.html">' > target/doc/index.html
|
||||||
|
|
||||||
|
- name: Deploy to GitHub Pages
|
||||||
|
uses: JamesIves/github-pages-deploy-action@3.7.1
|
||||||
|
with:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
BRANCH: gh-pages
|
||||||
|
FOLDER: target/doc
|
45
.github/workflows/windows-mingw.yml
vendored
45
.github/workflows/windows-mingw.yml
vendored
@@ -1,45 +0,0 @@
|
|||||||
name: CI (Windows-mingw)
|
|
||||||
|
|
||||||
on:
|
|
||||||
pull_request:
|
|
||||||
types: [opened, synchronize, reopened]
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- master
|
|
||||||
- '1.0'
|
|
||||||
|
|
||||||
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@v2
|
|
||||||
|
|
||||||
- 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: msys2/setup-msys2@v2
|
|
||||||
|
|
||||||
- name: Install packages
|
|
||||||
run: |
|
|
||||||
msys2 -c 'pacman -Sy --noconfirm pacman'
|
|
||||||
msys2 -c 'pacman --noconfirm -S base-devel pkg-config'
|
|
||||||
|
|
||||||
- name: check build
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: check
|
|
||||||
args: --workspace --bins --examples --tests
|
|
69
.github/workflows/windows.yml
vendored
69
.github/workflows/windows.yml
vendored
@@ -1,69 +0,0 @@
|
|||||||
name: CI (Windows)
|
|
||||||
|
|
||||||
on:
|
|
||||||
pull_request:
|
|
||||||
types: [opened, synchronize, reopened]
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- master
|
|
||||||
- '1.0'
|
|
||||||
|
|
||||||
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@v2
|
|
||||||
|
|
||||||
- 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: --workspace --bins --examples --tests
|
|
||||||
|
|
||||||
- name: tests
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: test
|
|
||||||
args: --workspace --exclude=actix-tls --no-fail-fast -- --nocapture
|
|
@@ -235,7 +235,7 @@ impl<T, U> Framed<T, U> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Flush write buffer to underlying I/O stream.
|
/// Flush write buffer to underlying I/O stream.
|
||||||
pub fn flush<I>(
|
pub fn poll_flush<I>(
|
||||||
mut self: Pin<&mut Self>,
|
mut self: Pin<&mut Self>,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Poll<Result<(), U::Error>>
|
) -> Poll<Result<(), U::Error>>
|
||||||
@@ -271,7 +271,7 @@ impl<T, U> Framed<T, U> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Flush write buffer and shutdown underlying I/O stream.
|
/// Flush write buffer and shutdown underlying I/O stream.
|
||||||
pub fn close<I>(
|
pub fn poll_close<I>(
|
||||||
mut self: Pin<&mut Self>,
|
mut self: Pin<&mut Self>,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Poll<Result<(), U::Error>>
|
) -> Poll<Result<(), U::Error>>
|
||||||
@@ -319,11 +319,11 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||||
self.flush(cx)
|
self.poll_flush(cx)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||||
self.close(cx)
|
self.poll_close(cx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -1,6 +1,9 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
## Unreleased - 2021-xx-xx
|
## Unreleased - 2021-xx-xx
|
||||||
|
|
||||||
|
|
||||||
|
## 0.2.7 - 2021-02-06
|
||||||
* Add `Router::recognize_checked` [#247]
|
* Add `Router::recognize_checked` [#247]
|
||||||
|
|
||||||
[#247]: https://github.com/actix/actix-net/pull/247
|
[#247]: https://github.com/actix/actix-net/pull/247
|
||||||
|
@@ -1,9 +1,9 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-router"
|
name = "actix-router"
|
||||||
version = "0.2.6"
|
version = "0.2.7"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Resource path matching library"
|
description = "Resource path matching library"
|
||||||
keywords = ["actix"]
|
keywords = ["actix", "router", "routing"]
|
||||||
homepage = "https://actix.rs"
|
homepage = "https://actix.rs"
|
||||||
repository = "https://github.com/actix/actix-net.git"
|
repository = "https://github.com/actix/actix-net.git"
|
||||||
documentation = "https://docs.rs/actix-router"
|
documentation = "https://docs.rs/actix-router"
|
||||||
|
@@ -670,8 +670,6 @@ pub(crate) fn insert_slash(path: &str) -> String {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use http::Uri;
|
|
||||||
use std::convert::TryFrom;
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_parse_static() {
|
fn test_parse_static() {
|
||||||
@@ -833,8 +831,11 @@ mod tests {
|
|||||||
assert!(re.is_match("/user/2345/sdg"));
|
assert!(re.is_match("/user/2345/sdg"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "http")]
|
||||||
#[test]
|
#[test]
|
||||||
fn test_parse_urlencoded_param() {
|
fn test_parse_urlencoded_param() {
|
||||||
|
use std::convert::TryFrom;
|
||||||
|
|
||||||
let re = ResourceDef::new("/user/{id}/test");
|
let re = ResourceDef::new("/user/{id}/test");
|
||||||
|
|
||||||
let mut path = Path::new("/user/2345/test");
|
let mut path = Path::new("/user/2345/test");
|
||||||
@@ -845,7 +846,7 @@ mod tests {
|
|||||||
assert!(re.match_path(&mut path));
|
assert!(re.match_path(&mut path));
|
||||||
assert_eq!(path.get("id").unwrap(), "qwe%25");
|
assert_eq!(path.get("id").unwrap(), "qwe%25");
|
||||||
|
|
||||||
let uri = Uri::try_from("/user/qwe%25/test").unwrap();
|
let uri = http::Uri::try_from("/user/qwe%25/test").unwrap();
|
||||||
let mut path = Path::new(uri);
|
let mut path = Path::new(uri);
|
||||||
assert!(re.match_path(&mut path));
|
assert!(re.match_path(&mut path));
|
||||||
assert_eq!(path.get("id").unwrap(), "qwe%25");
|
assert_eq!(path.get("id").unwrap(), "qwe%25");
|
||||||
|
@@ -1,6 +1,19 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
## Unreleased - 2021-xx-xx
|
## Unreleased - 2021-xx-xx
|
||||||
|
* Add `ActixStream` extension trait to include readiness methods. [#276]
|
||||||
|
* Re-export `tokio::net::TcpSocket` in `net` module [#282]
|
||||||
|
|
||||||
|
[#276]: https://github.com/actix/actix-net/pull/276
|
||||||
|
[#282]: https://github.com/actix/actix-net/pull/282
|
||||||
|
|
||||||
|
|
||||||
|
## 2.0.2 - 2021-02-06
|
||||||
|
* Add `Arbiter::handle` to get a handle of an owned Arbiter. [#274]
|
||||||
|
* Add `System::try_current` for situations where actix may or may not be running a System. [#275]
|
||||||
|
|
||||||
|
[#274]: https://github.com/actix/actix-net/pull/274
|
||||||
|
[#275]: https://github.com/actix/actix-net/pull/275
|
||||||
|
|
||||||
|
|
||||||
## 2.0.1 - 2021-02-06
|
## 2.0.1 - 2021-02-06
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-rt"
|
name = "actix-rt"
|
||||||
version = "2.0.1"
|
version = "2.0.2"
|
||||||
authors = [
|
authors = [
|
||||||
"Nikolay Kim <fafhrd91@gmail.com>",
|
"Nikolay Kim <fafhrd91@gmail.com>",
|
||||||
"Rob Ede <robjtede@icloud.com>",
|
"Rob Ede <robjtede@icloud.com>",
|
||||||
|
@@ -172,13 +172,18 @@ impl Arbiter {
|
|||||||
hnd
|
hnd
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Return a handle to the this Arbiter's message sender.
|
||||||
|
pub fn handle(&self) -> ArbiterHandle {
|
||||||
|
ArbiterHandle::new(self.tx.clone())
|
||||||
|
}
|
||||||
|
|
||||||
/// Return a handle to the current thread's Arbiter's message sender.
|
/// Return a handle to the current thread's Arbiter's message sender.
|
||||||
///
|
///
|
||||||
/// # Panics
|
/// # Panics
|
||||||
/// Panics if no Arbiter is running on the current thread.
|
/// Panics if no Arbiter is running on the current thread.
|
||||||
pub fn current() -> ArbiterHandle {
|
pub fn current() -> ArbiterHandle {
|
||||||
HANDLE.with(|cell| match *cell.borrow() {
|
HANDLE.with(|cell| match *cell.borrow() {
|
||||||
Some(ref addr) => addr.clone(),
|
Some(ref hnd) => hnd.clone(),
|
||||||
None => panic!("Arbiter is not running."),
|
None => panic!("Arbiter is not running."),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
@@ -70,13 +70,50 @@ pub mod signal {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub mod net {
|
pub mod net {
|
||||||
//! TCP/UDP/Unix bindings (Tokio re-exports).
|
//! TCP/UDP/Unix bindings (mostly Tokio re-exports).
|
||||||
|
|
||||||
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
|
use tokio::io::{AsyncRead, AsyncWrite};
|
||||||
pub use tokio::net::UdpSocket;
|
pub use tokio::net::UdpSocket;
|
||||||
pub use tokio::net::{TcpListener, TcpStream};
|
pub use tokio::net::{TcpListener, TcpSocket, TcpStream};
|
||||||
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
pub use tokio::net::{UnixDatagram, UnixListener, UnixStream};
|
pub use tokio::net::{UnixDatagram, UnixListener, UnixStream};
|
||||||
|
|
||||||
|
/// Extension trait over async read+write types that can also signal readiness.
|
||||||
|
pub trait ActixStream: AsyncRead + AsyncWrite + Unpin + 'static {
|
||||||
|
/// Poll stream and check read readiness of Self.
|
||||||
|
///
|
||||||
|
/// See [tokio::net::TcpStream::poll_read_ready] for detail on intended use.
|
||||||
|
fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<std::io::Result<()>>;
|
||||||
|
|
||||||
|
/// Poll stream and check write readiness of Self.
|
||||||
|
///
|
||||||
|
/// See [tokio::net::TcpStream::poll_write_ready] for detail on intended use.
|
||||||
|
fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<std::io::Result<()>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ActixStream for TcpStream {
|
||||||
|
fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||||
|
TcpStream::poll_read_ready(self, cx)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||||
|
TcpStream::poll_write_ready(self, cx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
impl ActixStream for UnixStream {
|
||||||
|
fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||||
|
UnixStream::poll_read_ready(self, cx)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||||
|
UnixStream::poll_write_ready(self, cx)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub mod time {
|
pub mod time {
|
||||||
|
@@ -100,6 +100,15 @@ impl System {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Try to get current running system.
|
||||||
|
///
|
||||||
|
/// Returns `None` if no System has been started.
|
||||||
|
///
|
||||||
|
/// Contrary to `current`, this never panics.
|
||||||
|
pub fn try_current() -> Option<System> {
|
||||||
|
CURRENT.with(|cell| cell.borrow().clone())
|
||||||
|
}
|
||||||
|
|
||||||
/// Get handle to a the System's initial [Arbiter].
|
/// Get handle to a the System's initial [Arbiter].
|
||||||
pub fn arbiter(&self) -> &ArbiterHandle {
|
pub fn arbiter(&self) -> &ArbiterHandle {
|
||||||
&self.arbiter_handle
|
&self.arbiter_handle
|
||||||
|
@@ -122,6 +122,28 @@ fn arbiter_spawn_fn_runs() {
|
|||||||
arbiter.join().unwrap();
|
arbiter.join().unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn arbiter_handle_spawn_fn_runs() {
|
||||||
|
let sys = System::new();
|
||||||
|
|
||||||
|
let (tx, rx) = channel::<u32>();
|
||||||
|
|
||||||
|
let arbiter = Arbiter::new();
|
||||||
|
let handle = arbiter.handle();
|
||||||
|
drop(arbiter);
|
||||||
|
|
||||||
|
handle.spawn_fn(move || {
|
||||||
|
tx.send(42).unwrap();
|
||||||
|
System::current().stop()
|
||||||
|
});
|
||||||
|
|
||||||
|
let num = rx.recv_timeout(Duration::from_secs(2)).unwrap();
|
||||||
|
assert_eq!(num, 42);
|
||||||
|
|
||||||
|
handle.stop();
|
||||||
|
sys.run().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn arbiter_drop_no_panic_fn() {
|
fn arbiter_drop_no_panic_fn() {
|
||||||
let _ = System::new();
|
let _ = System::new();
|
||||||
@@ -266,3 +288,13 @@ fn new_arbiter_with_tokio() {
|
|||||||
|
|
||||||
assert_eq!(false, counter.load(Ordering::SeqCst));
|
assert_eq!(false, counter.load(Ordering::SeqCst));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn try_current_no_system() {
|
||||||
|
assert!(System::try_current().is_none())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn try_current_with_system() {
|
||||||
|
System::new().block_on(async { assert!(System::try_current().is_some()) });
|
||||||
|
}
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-server"
|
name = "actix-server"
|
||||||
version = "2.0.0-beta.2"
|
version = "2.0.0-beta.3"
|
||||||
authors = [
|
authors = [
|
||||||
"Nikolay Kim <fafhrd91@gmail.com>",
|
"Nikolay Kim <fafhrd91@gmail.com>",
|
||||||
"fakeshadow <24548779@qq.com>",
|
"fakeshadow <24548779@qq.com>",
|
||||||
@@ -12,7 +12,6 @@ repository = "https://github.com/actix/actix-net.git"
|
|||||||
documentation = "https://docs.rs/actix-server"
|
documentation = "https://docs.rs/actix-server"
|
||||||
categories = ["network-programming", "asynchronous"]
|
categories = ["network-programming", "asynchronous"]
|
||||||
license = "MIT OR Apache-2.0"
|
license = "MIT OR Apache-2.0"
|
||||||
exclude = [".gitignore", ".cargo/config"]
|
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
@@ -33,7 +32,7 @@ log = "0.4"
|
|||||||
mio = { version = "0.7.6", features = ["os-poll", "net"] }
|
mio = { version = "0.7.6", features = ["os-poll", "net"] }
|
||||||
num_cpus = "1.13"
|
num_cpus = "1.13"
|
||||||
slab = "0.4"
|
slab = "0.4"
|
||||||
tokio = { version = "1", features = ["sync"] }
|
tokio = { version = "1.2", features = ["sync"] }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-rt = "2.0.0"
|
actix-rt = "2.0.0"
|
||||||
|
@@ -8,7 +8,7 @@ use mio::{Registry, Token as MioToken, Waker};
|
|||||||
|
|
||||||
use crate::worker::WorkerHandle;
|
use crate::worker::WorkerHandle;
|
||||||
|
|
||||||
/// waker token for `mio::Poll` instance
|
/// Waker token for `mio::Poll` instance.
|
||||||
pub(crate) const WAKER_TOKEN: MioToken = MioToken(usize::MAX);
|
pub(crate) const WAKER_TOKEN: MioToken = MioToken(usize::MAX);
|
||||||
|
|
||||||
/// `mio::Waker` with a queue for waking up the `Accept`'s `Poll` and contains the `WakerInterest`
|
/// `mio::Waker` with a queue for waking up the `Accept`'s `Poll` and contains the `WakerInterest`
|
||||||
@@ -30,7 +30,7 @@ impl Deref for WakerQueue {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl WakerQueue {
|
impl WakerQueue {
|
||||||
/// construct a waker queue with given `Poll`'s `Registry` and capacity.
|
/// Construct a waker queue with given `Poll`'s `Registry` and capacity.
|
||||||
///
|
///
|
||||||
/// A fixed `WAKER_TOKEN` is used to identify the wake interest and the `Poll` needs to match
|
/// A fixed `WAKER_TOKEN` is used to identify the wake interest and the `Poll` needs to match
|
||||||
/// event's token for it to properly handle `WakerInterest`.
|
/// event's token for it to properly handle `WakerInterest`.
|
||||||
@@ -41,7 +41,7 @@ impl WakerQueue {
|
|||||||
Ok(Self(Arc::new((waker, queue))))
|
Ok(Self(Arc::new((waker, queue))))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// push a new interest to the queue and wake up the accept poll afterwards.
|
/// Push a new interest to the queue and wake up the accept poll afterwards.
|
||||||
pub(crate) fn wake(&self, interest: WakerInterest) {
|
pub(crate) fn wake(&self, interest: WakerInterest) {
|
||||||
let (waker, queue) = self.deref();
|
let (waker, queue) = self.deref();
|
||||||
|
|
||||||
@@ -55,20 +55,20 @@ impl WakerQueue {
|
|||||||
.unwrap_or_else(|e| panic!("can not wake up Accept Poll: {}", e));
|
.unwrap_or_else(|e| panic!("can not wake up Accept Poll: {}", e));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// get a MutexGuard of the waker queue.
|
/// Get a MutexGuard of the waker queue.
|
||||||
pub(crate) fn guard(&self) -> MutexGuard<'_, VecDeque<WakerInterest>> {
|
pub(crate) fn guard(&self) -> MutexGuard<'_, VecDeque<WakerInterest>> {
|
||||||
self.deref().1.lock().expect("Failed to lock WakerQueue")
|
self.deref().1.lock().expect("Failed to lock WakerQueue")
|
||||||
}
|
}
|
||||||
|
|
||||||
/// reset the waker queue so it does not grow infinitely.
|
/// Reset the waker queue so it does not grow infinitely.
|
||||||
pub(crate) fn reset(queue: &mut VecDeque<WakerInterest>) {
|
pub(crate) fn reset(queue: &mut VecDeque<WakerInterest>) {
|
||||||
std::mem::swap(&mut VecDeque::<WakerInterest>::with_capacity(16), queue);
|
std::mem::swap(&mut VecDeque::<WakerInterest>::with_capacity(16), queue);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// types of interests we would look into when `Accept`'s `Poll` is waked up by waker.
|
/// Types of interests we would look into when `Accept`'s `Poll` is waked up by waker.
|
||||||
///
|
///
|
||||||
/// *. These interests should not be confused with `mio::Interest` and mostly not I/O related
|
/// These interests should not be confused with `mio::Interest` and mostly not I/O related
|
||||||
pub(crate) enum WakerInterest {
|
pub(crate) enum WakerInterest {
|
||||||
/// `WorkerAvailable` is an interest from `Worker` notifying `Accept` there is a worker
|
/// `WorkerAvailable` is an interest from `Worker` notifying `Accept` there is a worker
|
||||||
/// available and can accept new tasks.
|
/// available and can accept new tasks.
|
||||||
|
@@ -102,8 +102,8 @@ pub trait Service<Req> {
|
|||||||
/// call and the next invocation of `call` results in an error.
|
/// call and the next invocation of `call` results in an error.
|
||||||
///
|
///
|
||||||
/// # Notes
|
/// # Notes
|
||||||
/// 1. `.poll_ready()` might be called on different task from actual service call.
|
/// 1. `poll_ready` might be called on a different task to `call`.
|
||||||
/// 1. In case of chained services, `.poll_ready()` get called for all services at once.
|
/// 1. In cases of chained services, `.poll_ready()` is called for all services at once.
|
||||||
fn poll_ready(&self, ctx: &mut task::Context<'_>) -> Poll<Result<(), Self::Error>>;
|
fn poll_ready(&self, ctx: &mut task::Context<'_>) -> Poll<Result<(), Self::Error>>;
|
||||||
|
|
||||||
/// Process the request and return the response asynchronously.
|
/// Process the request and return the response asynchronously.
|
||||||
|
@@ -1,6 +1,11 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
## Unreleased - 2021-xx-xx
|
## Unreleased - 2021-xx-xx
|
||||||
|
* Rename `accept::openssl::{SslStream => TlsStream}`.
|
||||||
|
* Add `connect::Connect::set_local_addr` to attach local `Ipaddr`. [#282]
|
||||||
|
* `connector::TcpConnector` service would try to bind to local_addr of `IpAddr` when given [#282]
|
||||||
|
|
||||||
|
[#282]: https://github.com/actix/actix-net/pull/282
|
||||||
|
|
||||||
|
|
||||||
## 3.0.0-beta.3 - 2021-02-06
|
## 3.0.0-beta.3 - 2021-02-06
|
||||||
|
@@ -52,7 +52,7 @@ log = "0.4"
|
|||||||
tokio-util = { version = "0.6.3", default-features = false }
|
tokio-util = { version = "0.6.3", default-features = false }
|
||||||
|
|
||||||
# openssl
|
# openssl
|
||||||
tls-openssl = { package = "openssl", version = "0.10", optional = true }
|
tls-openssl = { package = "openssl", version = "0.10.9", optional = true }
|
||||||
tokio-openssl = { version = "0.6", optional = true }
|
tokio-openssl = { version = "0.6", optional = true }
|
||||||
|
|
||||||
# rustls
|
# rustls
|
||||||
@@ -62,9 +62,15 @@ webpki-roots = { version = "0.21", optional = true }
|
|||||||
# native-tls
|
# native-tls
|
||||||
tokio-native-tls = { version = "0.3", optional = true }
|
tokio-native-tls = { version = "0.3", optional = true }
|
||||||
|
|
||||||
|
[target.'cfg(windows)'.dependencies.tls-openssl]
|
||||||
|
version = "0.10.9"
|
||||||
|
package = "openssl"
|
||||||
|
features = ["vendored"]
|
||||||
|
optional = true
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-rt = "2.0.0"
|
actix-rt = "2.0.0"
|
||||||
actix-server = "2.0.0-beta.2"
|
actix-server = "2.0.0-beta.3"
|
||||||
bytes = "1"
|
bytes = "1"
|
||||||
env_logger = "0.8"
|
env_logger = "0.8"
|
||||||
futures-util = { version = "0.3.7", default-features = false, features = ["sink"] }
|
futures-util = { version = "0.3.7", default-features = false, features = ["sink"] }
|
||||||
|
@@ -29,9 +29,10 @@ use std::{
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
use actix_rt::net::TcpStream;
|
||||||
use actix_server::Server;
|
use actix_server::Server;
|
||||||
use actix_service::pipeline_factory;
|
use actix_service::pipeline_factory;
|
||||||
use actix_tls::accept::rustls::Acceptor as RustlsAcceptor;
|
use actix_tls::accept::rustls::{Acceptor as RustlsAcceptor, TlsStream};
|
||||||
use futures_util::future::ok;
|
use futures_util::future::ok;
|
||||||
use log::info;
|
use log::info;
|
||||||
use rustls::{
|
use rustls::{
|
||||||
@@ -74,9 +75,9 @@ async fn main() -> io::Result<()> {
|
|||||||
// Set up TLS service factory
|
// Set up TLS service factory
|
||||||
pipeline_factory(tls_acceptor.clone())
|
pipeline_factory(tls_acceptor.clone())
|
||||||
.map_err(|err| println!("Rustls error: {:?}", err))
|
.map_err(|err| println!("Rustls error: {:?}", err))
|
||||||
.and_then(move |stream| {
|
.and_then(move |stream: TlsStream<TcpStream>| {
|
||||||
let num = count.fetch_add(1, Ordering::Relaxed);
|
let num = count.fetch_add(1, Ordering::Relaxed);
|
||||||
info!("[{}] Got TLS connection: {:?}", num, stream);
|
info!("[{}] Got TLS connection: {:?}", num, &*stream);
|
||||||
ok(())
|
ok(())
|
||||||
})
|
})
|
||||||
})?
|
})?
|
||||||
|
@@ -1,15 +1,94 @@
|
|||||||
use std::task::{Context, Poll};
|
use std::{
|
||||||
|
io::{self, IoSlice},
|
||||||
|
ops::{Deref, DerefMut},
|
||||||
|
pin::Pin,
|
||||||
|
task::{Context, Poll},
|
||||||
|
};
|
||||||
|
|
||||||
use actix_codec::{AsyncRead, AsyncWrite};
|
use actix_codec::{AsyncRead, AsyncWrite, ReadBuf};
|
||||||
|
use actix_rt::net::ActixStream;
|
||||||
use actix_service::{Service, ServiceFactory};
|
use actix_service::{Service, ServiceFactory};
|
||||||
use actix_utils::counter::Counter;
|
use actix_utils::counter::Counter;
|
||||||
use futures_core::future::LocalBoxFuture;
|
use futures_core::future::LocalBoxFuture;
|
||||||
|
|
||||||
pub use tokio_native_tls::native_tls::Error;
|
pub use tokio_native_tls::native_tls::Error;
|
||||||
pub use tokio_native_tls::{TlsAcceptor, TlsStream};
|
pub use tokio_native_tls::TlsAcceptor;
|
||||||
|
|
||||||
use super::MAX_CONN_COUNTER;
|
use super::MAX_CONN_COUNTER;
|
||||||
|
|
||||||
|
/// Wrapper type for `tokio_native_tls::TlsStream` in order to impl `ActixStream` trait.
|
||||||
|
pub struct TlsStream<T>(tokio_native_tls::TlsStream<T>);
|
||||||
|
|
||||||
|
impl<T> From<tokio_native_tls::TlsStream<T>> for TlsStream<T> {
|
||||||
|
fn from(stream: tokio_native_tls::TlsStream<T>) -> Self {
|
||||||
|
Self(stream)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: ActixStream> Deref for TlsStream<T> {
|
||||||
|
type Target = tokio_native_tls::TlsStream<T>;
|
||||||
|
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
&self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: ActixStream> DerefMut for TlsStream<T> {
|
||||||
|
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||||
|
&mut self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: ActixStream> AsyncRead for TlsStream<T> {
|
||||||
|
fn poll_read(
|
||||||
|
self: Pin<&mut Self>,
|
||||||
|
cx: &mut Context<'_>,
|
||||||
|
buf: &mut ReadBuf<'_>,
|
||||||
|
) -> Poll<io::Result<()>> {
|
||||||
|
Pin::new(&mut **self.get_mut()).poll_read(cx, buf)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: ActixStream> AsyncWrite for TlsStream<T> {
|
||||||
|
fn poll_write(
|
||||||
|
self: Pin<&mut Self>,
|
||||||
|
cx: &mut Context<'_>,
|
||||||
|
buf: &[u8],
|
||||||
|
) -> Poll<io::Result<usize>> {
|
||||||
|
Pin::new(&mut **self.get_mut()).poll_write(cx, buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||||
|
Pin::new(&mut **self.get_mut()).poll_flush(cx)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||||
|
Pin::new(&mut **self.get_mut()).poll_shutdown(cx)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_write_vectored(
|
||||||
|
self: Pin<&mut Self>,
|
||||||
|
cx: &mut Context<'_>,
|
||||||
|
bufs: &[IoSlice<'_>],
|
||||||
|
) -> Poll<io::Result<usize>> {
|
||||||
|
Pin::new(&mut **self.get_mut()).poll_write_vectored(cx, bufs)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_write_vectored(&self) -> bool {
|
||||||
|
(&**self).is_write_vectored()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: ActixStream> ActixStream for TlsStream<T> {
|
||||||
|
fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||||
|
T::poll_read_ready((&**self).get_ref().get_ref().get_ref(), cx)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||||
|
T::poll_write_ready((&**self).get_ref().get_ref().get_ref(), cx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Accept TLS connections via `native-tls` package.
|
/// Accept TLS connections via `native-tls` package.
|
||||||
///
|
///
|
||||||
/// `native-tls` feature enables this `Acceptor` type.
|
/// `native-tls` feature enables this `Acceptor` type.
|
||||||
@@ -34,10 +113,7 @@ impl Clone for Acceptor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> ServiceFactory<T> for Acceptor
|
impl<T: ActixStream> ServiceFactory<T> for Acceptor {
|
||||||
where
|
|
||||||
T: AsyncRead + AsyncWrite + Unpin + 'static,
|
|
||||||
{
|
|
||||||
type Response = TlsStream<T>;
|
type Response = TlsStream<T>;
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
type Config = ();
|
type Config = ();
|
||||||
@@ -71,10 +147,7 @@ impl Clone for NativeTlsAcceptorService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> Service<T> for NativeTlsAcceptorService
|
impl<T: ActixStream> Service<T> for NativeTlsAcceptorService {
|
||||||
where
|
|
||||||
T: AsyncRead + AsyncWrite + Unpin + 'static,
|
|
||||||
{
|
|
||||||
type Response = TlsStream<T>;
|
type Response = TlsStream<T>;
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
type Future = LocalBoxFuture<'static, Result<TlsStream<T>, Error>>;
|
type Future = LocalBoxFuture<'static, Result<TlsStream<T>, Error>>;
|
||||||
@@ -93,7 +166,7 @@ where
|
|||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
let io = this.acceptor.accept(io).await;
|
let io = this.acceptor.accept(io).await;
|
||||||
drop(guard);
|
drop(guard);
|
||||||
io
|
io.map(Into::into)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,10 +1,13 @@
|
|||||||
use std::{
|
use std::{
|
||||||
future::Future,
|
future::Future,
|
||||||
|
io::{self, IoSlice},
|
||||||
|
ops::{Deref, DerefMut},
|
||||||
pin::Pin,
|
pin::Pin,
|
||||||
task::{Context, Poll},
|
task::{Context, Poll},
|
||||||
};
|
};
|
||||||
|
|
||||||
use actix_codec::{AsyncRead, AsyncWrite};
|
use actix_codec::{AsyncRead, AsyncWrite, ReadBuf};
|
||||||
|
use actix_rt::net::ActixStream;
|
||||||
use actix_service::{Service, ServiceFactory};
|
use actix_service::{Service, ServiceFactory};
|
||||||
use actix_utils::counter::{Counter, CounterGuard};
|
use actix_utils::counter::{Counter, CounterGuard};
|
||||||
use futures_core::{future::LocalBoxFuture, ready};
|
use futures_core::{future::LocalBoxFuture, ready};
|
||||||
@@ -12,10 +15,82 @@ use futures_core::{future::LocalBoxFuture, ready};
|
|||||||
pub use openssl::ssl::{
|
pub use openssl::ssl::{
|
||||||
AlpnError, Error as SslError, HandshakeError, Ssl, SslAcceptor, SslAcceptorBuilder,
|
AlpnError, Error as SslError, HandshakeError, Ssl, SslAcceptor, SslAcceptorBuilder,
|
||||||
};
|
};
|
||||||
pub use tokio_openssl::SslStream;
|
|
||||||
|
|
||||||
use super::MAX_CONN_COUNTER;
|
use super::MAX_CONN_COUNTER;
|
||||||
|
|
||||||
|
/// Wrapper type for `tokio_openssl::SslStream` in order to impl `ActixStream` trait.
|
||||||
|
pub struct TlsStream<T>(tokio_openssl::SslStream<T>);
|
||||||
|
|
||||||
|
impl<T> From<tokio_openssl::SslStream<T>> for TlsStream<T> {
|
||||||
|
fn from(stream: tokio_openssl::SslStream<T>) -> Self {
|
||||||
|
Self(stream)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Deref for TlsStream<T> {
|
||||||
|
type Target = tokio_openssl::SslStream<T>;
|
||||||
|
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
&self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> DerefMut for TlsStream<T> {
|
||||||
|
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||||
|
&mut self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: ActixStream> AsyncRead for TlsStream<T> {
|
||||||
|
fn poll_read(
|
||||||
|
self: Pin<&mut Self>,
|
||||||
|
cx: &mut Context<'_>,
|
||||||
|
buf: &mut ReadBuf<'_>,
|
||||||
|
) -> Poll<io::Result<()>> {
|
||||||
|
Pin::new(&mut **self.get_mut()).poll_read(cx, buf)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: ActixStream> AsyncWrite for TlsStream<T> {
|
||||||
|
fn poll_write(
|
||||||
|
self: Pin<&mut Self>,
|
||||||
|
cx: &mut Context<'_>,
|
||||||
|
buf: &[u8],
|
||||||
|
) -> Poll<io::Result<usize>> {
|
||||||
|
Pin::new(&mut **self.get_mut()).poll_write(cx, buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||||
|
Pin::new(&mut **self.get_mut()).poll_flush(cx)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||||
|
Pin::new(&mut **self.get_mut()).poll_shutdown(cx)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_write_vectored(
|
||||||
|
self: Pin<&mut Self>,
|
||||||
|
cx: &mut Context<'_>,
|
||||||
|
bufs: &[IoSlice<'_>],
|
||||||
|
) -> Poll<io::Result<usize>> {
|
||||||
|
Pin::new(&mut **self.get_mut()).poll_write_vectored(cx, bufs)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_write_vectored(&self) -> bool {
|
||||||
|
(&**self).is_write_vectored()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: ActixStream> ActixStream for TlsStream<T> {
|
||||||
|
fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||||
|
T::poll_read_ready((&**self).get_ref(), cx)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||||
|
T::poll_write_ready((&**self).get_ref(), cx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Accept TLS connections via `openssl` package.
|
/// Accept TLS connections via `openssl` package.
|
||||||
///
|
///
|
||||||
/// `openssl` feature enables this `Acceptor` type.
|
/// `openssl` feature enables this `Acceptor` type.
|
||||||
@@ -40,11 +115,8 @@ impl Clone for Acceptor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> ServiceFactory<T> for Acceptor
|
impl<T: ActixStream> ServiceFactory<T> for Acceptor {
|
||||||
where
|
type Response = TlsStream<T>;
|
||||||
T: AsyncRead + AsyncWrite + Unpin + 'static,
|
|
||||||
{
|
|
||||||
type Response = SslStream<T>;
|
|
||||||
type Error = SslError;
|
type Error = SslError;
|
||||||
type Config = ();
|
type Config = ();
|
||||||
type Service = AcceptorService;
|
type Service = AcceptorService;
|
||||||
@@ -67,11 +139,8 @@ pub struct AcceptorService {
|
|||||||
conns: Counter,
|
conns: Counter,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> Service<T> for AcceptorService
|
impl<T: ActixStream> Service<T> for AcceptorService {
|
||||||
where
|
type Response = TlsStream<T>;
|
||||||
T: AsyncRead + AsyncWrite + Unpin + 'static,
|
|
||||||
{
|
|
||||||
type Response = SslStream<T>;
|
|
||||||
type Error = SslError;
|
type Error = SslError;
|
||||||
type Future = AcceptorServiceResponse<T>;
|
type Future = AcceptorServiceResponse<T>;
|
||||||
|
|
||||||
@@ -88,24 +157,25 @@ where
|
|||||||
let ssl = Ssl::new(ssl_ctx).expect("Provided SSL acceptor was invalid.");
|
let ssl = Ssl::new(ssl_ctx).expect("Provided SSL acceptor was invalid.");
|
||||||
AcceptorServiceResponse {
|
AcceptorServiceResponse {
|
||||||
_guard: self.conns.get(),
|
_guard: self.conns.get(),
|
||||||
stream: Some(SslStream::new(ssl, io).unwrap()),
|
stream: Some(tokio_openssl::SslStream::new(ssl, io).unwrap()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct AcceptorServiceResponse<T>
|
pub struct AcceptorServiceResponse<T: ActixStream> {
|
||||||
where
|
stream: Option<tokio_openssl::SslStream<T>>,
|
||||||
T: AsyncRead + AsyncWrite,
|
|
||||||
{
|
|
||||||
stream: Option<SslStream<T>>,
|
|
||||||
_guard: CounterGuard,
|
_guard: CounterGuard,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: AsyncRead + AsyncWrite + Unpin> Future for AcceptorServiceResponse<T> {
|
impl<T: ActixStream> Future for AcceptorServiceResponse<T> {
|
||||||
type Output = Result<SslStream<T>, SslError>;
|
type Output = Result<TlsStream<T>, SslError>;
|
||||||
|
|
||||||
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> {
|
||||||
ready!(Pin::new(self.stream.as_mut().unwrap()).poll_accept(cx))?;
|
ready!(Pin::new(self.stream.as_mut().unwrap()).poll_accept(cx))?;
|
||||||
Poll::Ready(Ok(self.stream.take().expect("SSL connect has resolved.")))
|
Poll::Ready(Ok(self
|
||||||
|
.stream
|
||||||
|
.take()
|
||||||
|
.expect("SSL connect has resolved.")
|
||||||
|
.into()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,22 +1,96 @@
|
|||||||
use std::{
|
use std::{
|
||||||
future::Future,
|
future::Future,
|
||||||
io,
|
io::{self, IoSlice},
|
||||||
|
ops::{Deref, DerefMut},
|
||||||
pin::Pin,
|
pin::Pin,
|
||||||
sync::Arc,
|
sync::Arc,
|
||||||
task::{Context, Poll},
|
task::{Context, Poll},
|
||||||
};
|
};
|
||||||
|
|
||||||
use actix_codec::{AsyncRead, AsyncWrite};
|
use actix_codec::{AsyncRead, AsyncWrite, ReadBuf};
|
||||||
|
use actix_rt::net::ActixStream;
|
||||||
use actix_service::{Service, ServiceFactory};
|
use actix_service::{Service, ServiceFactory};
|
||||||
use actix_utils::counter::{Counter, CounterGuard};
|
use actix_utils::counter::{Counter, CounterGuard};
|
||||||
use futures_core::future::LocalBoxFuture;
|
use futures_core::future::LocalBoxFuture;
|
||||||
use tokio_rustls::{Accept, TlsAcceptor};
|
use tokio_rustls::{Accept, TlsAcceptor};
|
||||||
|
|
||||||
pub use tokio_rustls::rustls::{ServerConfig, Session};
|
pub use tokio_rustls::rustls::{ServerConfig, Session};
|
||||||
pub use tokio_rustls::server::TlsStream;
|
|
||||||
|
|
||||||
use super::MAX_CONN_COUNTER;
|
use super::MAX_CONN_COUNTER;
|
||||||
|
|
||||||
|
/// Wrapper type for `tokio_openssl::SslStream` in order to impl `ActixStream` trait.
|
||||||
|
pub struct TlsStream<T>(tokio_rustls::server::TlsStream<T>);
|
||||||
|
|
||||||
|
impl<T> From<tokio_rustls::server::TlsStream<T>> for TlsStream<T> {
|
||||||
|
fn from(stream: tokio_rustls::server::TlsStream<T>) -> Self {
|
||||||
|
Self(stream)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Deref for TlsStream<T> {
|
||||||
|
type Target = tokio_rustls::server::TlsStream<T>;
|
||||||
|
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
&self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> DerefMut for TlsStream<T> {
|
||||||
|
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||||
|
&mut self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: ActixStream> AsyncRead for TlsStream<T> {
|
||||||
|
fn poll_read(
|
||||||
|
self: Pin<&mut Self>,
|
||||||
|
cx: &mut Context<'_>,
|
||||||
|
buf: &mut ReadBuf<'_>,
|
||||||
|
) -> Poll<io::Result<()>> {
|
||||||
|
Pin::new(&mut **self.get_mut()).poll_read(cx, buf)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: ActixStream> AsyncWrite for TlsStream<T> {
|
||||||
|
fn poll_write(
|
||||||
|
self: Pin<&mut Self>,
|
||||||
|
cx: &mut Context<'_>,
|
||||||
|
buf: &[u8],
|
||||||
|
) -> Poll<io::Result<usize>> {
|
||||||
|
Pin::new(&mut **self.get_mut()).poll_write(cx, buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||||
|
Pin::new(&mut **self.get_mut()).poll_flush(cx)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||||
|
Pin::new(&mut **self.get_mut()).poll_shutdown(cx)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_write_vectored(
|
||||||
|
self: Pin<&mut Self>,
|
||||||
|
cx: &mut Context<'_>,
|
||||||
|
bufs: &[IoSlice<'_>],
|
||||||
|
) -> Poll<io::Result<usize>> {
|
||||||
|
Pin::new(&mut **self.get_mut()).poll_write_vectored(cx, bufs)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_write_vectored(&self) -> bool {
|
||||||
|
(&**self).is_write_vectored()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: ActixStream> ActixStream for TlsStream<T> {
|
||||||
|
fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||||
|
T::poll_read_ready((&**self).get_ref().0, cx)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||||
|
T::poll_write_ready((&**self).get_ref().0, cx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Accept TLS connections via `rustls` package.
|
/// Accept TLS connections via `rustls` package.
|
||||||
///
|
///
|
||||||
/// `rustls` feature enables this `Acceptor` type.
|
/// `rustls` feature enables this `Acceptor` type.
|
||||||
@@ -43,10 +117,7 @@ impl Clone for Acceptor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> ServiceFactory<T> for Acceptor
|
impl<T: ActixStream> ServiceFactory<T> for Acceptor {
|
||||||
where
|
|
||||||
T: AsyncRead + AsyncWrite + Unpin,
|
|
||||||
{
|
|
||||||
type Response = TlsStream<T>;
|
type Response = TlsStream<T>;
|
||||||
type Error = io::Error;
|
type Error = io::Error;
|
||||||
type Config = ();
|
type Config = ();
|
||||||
@@ -72,10 +143,7 @@ pub struct AcceptorService {
|
|||||||
conns: Counter,
|
conns: Counter,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> Service<T> for AcceptorService
|
impl<T: ActixStream> Service<T> for AcceptorService {
|
||||||
where
|
|
||||||
T: AsyncRead + AsyncWrite + Unpin,
|
|
||||||
{
|
|
||||||
type Response = TlsStream<T>;
|
type Response = TlsStream<T>;
|
||||||
type Error = io::Error;
|
type Error = io::Error;
|
||||||
type Future = AcceptorServiceFut<T>;
|
type Future = AcceptorServiceFut<T>;
|
||||||
@@ -96,22 +164,16 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct AcceptorServiceFut<T>
|
pub struct AcceptorServiceFut<T: ActixStream> {
|
||||||
where
|
|
||||||
T: AsyncRead + AsyncWrite + Unpin,
|
|
||||||
{
|
|
||||||
fut: Accept<T>,
|
fut: Accept<T>,
|
||||||
_guard: CounterGuard,
|
_guard: CounterGuard,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> Future for AcceptorServiceFut<T>
|
impl<T: ActixStream> Future for AcceptorServiceFut<T> {
|
||||||
where
|
|
||||||
T: AsyncRead + AsyncWrite + Unpin,
|
|
||||||
{
|
|
||||||
type Output = Result<TlsStream<T>, io::Error>;
|
type Output = Result<TlsStream<T>, io::Error>;
|
||||||
|
|
||||||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||||
let this = self.get_mut();
|
let this = self.get_mut();
|
||||||
Pin::new(&mut this.fut).poll(cx)
|
Pin::new(&mut this.fut).poll(cx).map_ok(TlsStream)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -3,7 +3,7 @@ use std::{
|
|||||||
fmt,
|
fmt,
|
||||||
iter::{self, FromIterator as _},
|
iter::{self, FromIterator as _},
|
||||||
mem,
|
mem,
|
||||||
net::SocketAddr,
|
net::{IpAddr, SocketAddr},
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Parse a host into parts (hostname and port).
|
/// Parse a host into parts (hostname and port).
|
||||||
@@ -67,6 +67,7 @@ pub struct Connect<T> {
|
|||||||
pub(crate) req: T,
|
pub(crate) req: T,
|
||||||
pub(crate) port: u16,
|
pub(crate) port: u16,
|
||||||
pub(crate) addr: ConnectAddrs,
|
pub(crate) addr: ConnectAddrs,
|
||||||
|
pub(crate) local_addr: Option<IpAddr>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: Address> Connect<T> {
|
impl<T: Address> Connect<T> {
|
||||||
@@ -78,6 +79,7 @@ impl<T: Address> Connect<T> {
|
|||||||
req,
|
req,
|
||||||
port: port.unwrap_or(0),
|
port: port.unwrap_or(0),
|
||||||
addr: ConnectAddrs::None,
|
addr: ConnectAddrs::None,
|
||||||
|
local_addr: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -88,6 +90,7 @@ impl<T: Address> Connect<T> {
|
|||||||
req,
|
req,
|
||||||
port: 0,
|
port: 0,
|
||||||
addr: ConnectAddrs::One(addr),
|
addr: ConnectAddrs::One(addr),
|
||||||
|
local_addr: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -119,6 +122,12 @@ impl<T: Address> Connect<T> {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Set local_addr of connect.
|
||||||
|
pub fn set_local_addr(mut self, addr: impl Into<IpAddr>) -> Self {
|
||||||
|
self.local_addr = Some(addr.into());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
/// Get hostname.
|
/// Get hostname.
|
||||||
pub fn hostname(&self) -> &str {
|
pub fn hostname(&self) -> &str {
|
||||||
self.req.hostname()
|
self.req.hostname()
|
||||||
@@ -285,7 +294,7 @@ fn parse_host(host: &str) -> (&str, Option<u16>) {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use std::net::{IpAddr, Ipv4Addr};
|
use std::net::Ipv4Addr;
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
@@ -329,4 +338,13 @@ mod tests {
|
|||||||
let mut iter = ConnectAddrsIter::None;
|
let mut iter = ConnectAddrsIter::None;
|
||||||
assert_eq!(iter.next(), None);
|
assert_eq!(iter.next(), None);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_local_addr() {
|
||||||
|
let conn = Connect::new("hello").set_local_addr([127, 0, 0, 1]);
|
||||||
|
assert_eq!(
|
||||||
|
conn.local_addr.unwrap(),
|
||||||
|
IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1))
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@@ -2,12 +2,12 @@ use std::{
|
|||||||
collections::VecDeque,
|
collections::VecDeque,
|
||||||
future::Future,
|
future::Future,
|
||||||
io,
|
io,
|
||||||
net::SocketAddr,
|
net::{IpAddr, SocketAddr, SocketAddrV4, SocketAddrV6},
|
||||||
pin::Pin,
|
pin::Pin,
|
||||||
task::{Context, Poll},
|
task::{Context, Poll},
|
||||||
};
|
};
|
||||||
|
|
||||||
use actix_rt::net::TcpStream;
|
use actix_rt::net::{TcpSocket, TcpStream};
|
||||||
use actix_service::{Service, ServiceFactory};
|
use actix_service::{Service, ServiceFactory};
|
||||||
use futures_core::{future::LocalBoxFuture, ready};
|
use futures_core::{future::LocalBoxFuture, ready};
|
||||||
use log::{error, trace};
|
use log::{error, trace};
|
||||||
@@ -54,9 +54,14 @@ impl<T: Address> Service<Connect<T>> for TcpConnector {
|
|||||||
|
|
||||||
fn call(&self, req: Connect<T>) -> Self::Future {
|
fn call(&self, req: Connect<T>) -> Self::Future {
|
||||||
let port = req.port();
|
let port = req.port();
|
||||||
let Connect { req, addr, .. } = req;
|
let Connect {
|
||||||
|
req,
|
||||||
|
addr,
|
||||||
|
local_addr,
|
||||||
|
..
|
||||||
|
} = req;
|
||||||
|
|
||||||
TcpConnectorResponse::new(req, port, addr)
|
TcpConnectorResponse::new(req, port, local_addr, addr)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -65,6 +70,7 @@ pub enum TcpConnectorResponse<T> {
|
|||||||
Response {
|
Response {
|
||||||
req: Option<T>,
|
req: Option<T>,
|
||||||
port: u16,
|
port: u16,
|
||||||
|
local_addr: Option<IpAddr>,
|
||||||
addrs: Option<VecDeque<SocketAddr>>,
|
addrs: Option<VecDeque<SocketAddr>>,
|
||||||
stream: Option<ReusableBoxFuture<Result<TcpStream, io::Error>>>,
|
stream: Option<ReusableBoxFuture<Result<TcpStream, io::Error>>>,
|
||||||
},
|
},
|
||||||
@@ -72,7 +78,12 @@ pub enum TcpConnectorResponse<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<T: Address> TcpConnectorResponse<T> {
|
impl<T: Address> TcpConnectorResponse<T> {
|
||||||
pub(crate) fn new(req: T, port: u16, addr: ConnectAddrs) -> TcpConnectorResponse<T> {
|
pub(crate) fn new(
|
||||||
|
req: T,
|
||||||
|
port: u16,
|
||||||
|
local_addr: Option<IpAddr>,
|
||||||
|
addr: ConnectAddrs,
|
||||||
|
) -> TcpConnectorResponse<T> {
|
||||||
if addr.is_none() {
|
if addr.is_none() {
|
||||||
error!("TCP connector: unresolved connection address");
|
error!("TCP connector: unresolved connection address");
|
||||||
return TcpConnectorResponse::Error(Some(ConnectError::Unresolved));
|
return TcpConnectorResponse::Error(Some(ConnectError::Unresolved));
|
||||||
@@ -90,8 +101,9 @@ impl<T: Address> TcpConnectorResponse<T> {
|
|||||||
ConnectAddrs::One(addr) => TcpConnectorResponse::Response {
|
ConnectAddrs::One(addr) => TcpConnectorResponse::Response {
|
||||||
req: Some(req),
|
req: Some(req),
|
||||||
port,
|
port,
|
||||||
|
local_addr,
|
||||||
addrs: None,
|
addrs: None,
|
||||||
stream: Some(ReusableBoxFuture::new(TcpStream::connect(addr))),
|
stream: Some(ReusableBoxFuture::new(connect(addr, local_addr))),
|
||||||
},
|
},
|
||||||
|
|
||||||
// when resolver returns multiple socket addr for request they would be popped from
|
// when resolver returns multiple socket addr for request they would be popped from
|
||||||
@@ -99,6 +111,7 @@ impl<T: Address> TcpConnectorResponse<T> {
|
|||||||
ConnectAddrs::Multi(addrs) => TcpConnectorResponse::Response {
|
ConnectAddrs::Multi(addrs) => TcpConnectorResponse::Response {
|
||||||
req: Some(req),
|
req: Some(req),
|
||||||
port,
|
port,
|
||||||
|
local_addr,
|
||||||
addrs: Some(addrs),
|
addrs: Some(addrs),
|
||||||
stream: None,
|
stream: None,
|
||||||
},
|
},
|
||||||
@@ -116,6 +129,7 @@ impl<T: Address> Future for TcpConnectorResponse<T> {
|
|||||||
TcpConnectorResponse::Response {
|
TcpConnectorResponse::Response {
|
||||||
req,
|
req,
|
||||||
port,
|
port,
|
||||||
|
local_addr,
|
||||||
addrs,
|
addrs,
|
||||||
stream,
|
stream,
|
||||||
} => loop {
|
} => loop {
|
||||||
@@ -148,11 +162,38 @@ impl<T: Address> Future for TcpConnectorResponse<T> {
|
|||||||
// try to connect
|
// try to connect
|
||||||
let addr = addrs.as_mut().unwrap().pop_front().unwrap();
|
let addr = addrs.as_mut().unwrap().pop_front().unwrap();
|
||||||
|
|
||||||
|
let fut = connect(addr, *local_addr);
|
||||||
match stream {
|
match stream {
|
||||||
Some(rbf) => rbf.set(TcpStream::connect(addr)),
|
Some(rbf) => rbf.set(fut),
|
||||||
None => *stream = Some(ReusableBoxFuture::new(TcpStream::connect(addr))),
|
None => *stream = Some(ReusableBoxFuture::new(fut)),
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn connect(addr: SocketAddr, local_addr: Option<IpAddr>) -> io::Result<TcpStream> {
|
||||||
|
// use local addr if connect asks for it.
|
||||||
|
match local_addr {
|
||||||
|
Some(ip_addr) => {
|
||||||
|
let socket = match ip_addr {
|
||||||
|
IpAddr::V4(ip_addr) => {
|
||||||
|
let socket = TcpSocket::new_v4()?;
|
||||||
|
let addr = SocketAddr::V4(SocketAddrV4::new(ip_addr, 0));
|
||||||
|
socket.bind(addr)?;
|
||||||
|
socket
|
||||||
|
}
|
||||||
|
IpAddr::V6(ip_addr) => {
|
||||||
|
let socket = TcpSocket::new_v6()?;
|
||||||
|
let addr = SocketAddr::V6(SocketAddrV6::new(ip_addr, 0, 0, 0));
|
||||||
|
socket.bind(addr)?;
|
||||||
|
socket
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
socket.connect(addr).await
|
||||||
|
}
|
||||||
|
|
||||||
|
None => TcpStream::connect(addr).await,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@@ -1,4 +1,9 @@
|
|||||||
use std::io;
|
#![cfg(feature = "connect")]
|
||||||
|
|
||||||
|
use std::{
|
||||||
|
io,
|
||||||
|
net::{IpAddr, Ipv4Addr},
|
||||||
|
};
|
||||||
|
|
||||||
use actix_codec::{BytesCodec, Framed};
|
use actix_codec::{BytesCodec, Framed};
|
||||||
use actix_rt::net::TcpStream;
|
use actix_rt::net::TcpStream;
|
||||||
@@ -9,7 +14,7 @@ use futures_util::sink::SinkExt;
|
|||||||
|
|
||||||
use actix_tls::connect::{self as actix_connect, Connect};
|
use actix_tls::connect::{self as actix_connect, Connect};
|
||||||
|
|
||||||
#[cfg(all(feature = "connect", feature = "openssl"))]
|
#[cfg(feature = "openssl")]
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_string() {
|
async fn test_string() {
|
||||||
let srv = TestServer::with(|| {
|
let srv = TestServer::with(|| {
|
||||||
@@ -125,3 +130,25 @@ async fn test_rustls_uri() {
|
|||||||
let con = conn.call(addr.into()).await.unwrap();
|
let con = conn.call(addr.into()).await.unwrap();
|
||||||
assert_eq!(con.peer_addr().unwrap(), srv.addr());
|
assert_eq!(con.peer_addr().unwrap(), srv.addr());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[actix_rt::test]
|
||||||
|
async fn test_local_addr() {
|
||||||
|
let srv = TestServer::with(|| {
|
||||||
|
fn_service(|io: TcpStream| async {
|
||||||
|
let mut framed = Framed::new(io, BytesCodec);
|
||||||
|
framed.send(Bytes::from_static(b"test")).await?;
|
||||||
|
Ok::<_, io::Error>(())
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
let conn = actix_connect::default_connector();
|
||||||
|
let local = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 3));
|
||||||
|
|
||||||
|
let (con, _) = conn
|
||||||
|
.call(Connect::with_addr("10", srv.addr()).set_local_addr(local))
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.into_parts();
|
||||||
|
|
||||||
|
assert_eq!(con.local_addr().unwrap().ip(), local)
|
||||||
|
}
|
||||||
|
@@ -1,3 +1,5 @@
|
|||||||
|
#![cfg(feature = "connect")]
|
||||||
|
|
||||||
use std::{
|
use std::{
|
||||||
io,
|
io,
|
||||||
net::{Ipv4Addr, SocketAddr},
|
net::{Ipv4Addr, SocketAddr},
|
||||||
|
@@ -24,6 +24,7 @@ futures-core = { version = "0.3.7", default-features = false }
|
|||||||
futures-sink = { version = "0.3.7", default-features = false }
|
futures-sink = { version = "0.3.7", default-features = false }
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
pin-project-lite = "0.2.0"
|
pin-project-lite = "0.2.0"
|
||||||
|
tokio = { version = "1", features = ["sync"] }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-rt = "2.0.0"
|
actix-rt = "2.0.0"
|
||||||
|
@@ -1,21 +1,20 @@
|
|||||||
//! Framed dispatcher service and related utilities.
|
//! Framed dispatcher service and related utilities.
|
||||||
|
|
||||||
#![allow(type_alias_bounds)]
|
use core::{
|
||||||
|
fmt,
|
||||||
use core::future::Future;
|
future::Future,
|
||||||
use core::pin::Pin;
|
mem,
|
||||||
use core::task::{Context, Poll};
|
pin::Pin,
|
||||||
use core::{fmt, mem};
|
task::{Context, Poll},
|
||||||
|
};
|
||||||
|
|
||||||
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
|
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
|
||||||
use actix_service::{IntoService, Service};
|
use actix_service::{IntoService, Service};
|
||||||
use futures_core::stream::Stream;
|
|
||||||
use log::debug;
|
use log::debug;
|
||||||
use pin_project_lite::pin_project;
|
use pin_project_lite::pin_project;
|
||||||
|
use tokio::sync::mpsc;
|
||||||
|
|
||||||
use crate::mpsc;
|
/// Framed transport errors.
|
||||||
|
|
||||||
/// Framed transport errors
|
|
||||||
pub enum DispatcherError<E, U: Encoder<I> + Decoder, I> {
|
pub enum DispatcherError<E, U: Encoder<I> + Decoder, I> {
|
||||||
Service(E),
|
Service(E),
|
||||||
Encoder(<U as Encoder<I>>::Error),
|
Encoder(<U as Encoder<I>>::Error),
|
||||||
@@ -64,8 +63,7 @@ pub enum Message<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pin_project! {
|
pin_project! {
|
||||||
/// Dispatcher is a future that reads frames from Framed object
|
/// Dispatcher is a future that reads frames from Framed object and passes them to the service.
|
||||||
/// and passes them to the service.
|
|
||||||
pub struct Dispatcher<S, T, U, I>
|
pub struct Dispatcher<S, T, U, I>
|
||||||
where
|
where
|
||||||
S: Service<<U as Decoder>::Item, Response = I>,
|
S: Service<<U as Decoder>::Item, Response = I>,
|
||||||
@@ -82,8 +80,8 @@ pin_project! {
|
|||||||
state: State<S, U, I>,
|
state: State<S, U, I>,
|
||||||
#[pin]
|
#[pin]
|
||||||
framed: Framed<T, U>,
|
framed: Framed<T, U>,
|
||||||
rx: mpsc::Receiver<Result<Message<I>, S::Error>>,
|
rx: mpsc::UnboundedReceiver<Result<Message<I>, S::Error>>,
|
||||||
tx: mpsc::Sender<Result<Message<I>, S::Error>>,
|
tx: mpsc::UnboundedSender<Result<Message<I>, S::Error>>,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,26 +132,7 @@ where
|
|||||||
where
|
where
|
||||||
F: IntoService<S, <U as Decoder>::Item>,
|
F: IntoService<S, <U as Decoder>::Item>,
|
||||||
{
|
{
|
||||||
let (tx, rx) = mpsc::channel();
|
let (tx, rx) = mpsc::unbounded_channel();
|
||||||
Dispatcher {
|
|
||||||
framed,
|
|
||||||
rx,
|
|
||||||
tx,
|
|
||||||
service: service.into_service(),
|
|
||||||
state: State::Processing,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Construct new `Dispatcher` instance with customer `mpsc::Receiver`
|
|
||||||
pub fn with_rx<F>(
|
|
||||||
framed: Framed<T, U>,
|
|
||||||
service: F,
|
|
||||||
rx: mpsc::Receiver<Result<Message<I>, S::Error>>,
|
|
||||||
) -> Self
|
|
||||||
where
|
|
||||||
F: IntoService<S, <U as Decoder>::Item>,
|
|
||||||
{
|
|
||||||
let tx = rx.sender();
|
|
||||||
Dispatcher {
|
Dispatcher {
|
||||||
framed,
|
framed,
|
||||||
rx,
|
rx,
|
||||||
@@ -164,28 +143,28 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Get sink
|
/// Get sink
|
||||||
pub fn get_sink(&self) -> mpsc::Sender<Result<Message<I>, S::Error>> {
|
pub fn tx(&self) -> mpsc::UnboundedSender<Result<Message<I>, S::Error>> {
|
||||||
self.tx.clone()
|
self.tx.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get reference to a service wrapped by `Dispatcher` instance.
|
/// Get reference to a service wrapped by `Dispatcher` instance.
|
||||||
pub fn get_ref(&self) -> &S {
|
pub fn service(&self) -> &S {
|
||||||
&self.service
|
&self.service
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get mutable reference to a service wrapped by `Dispatcher` instance.
|
/// Get mutable reference to a service wrapped by `Dispatcher` instance.
|
||||||
pub fn get_mut(&mut self) -> &mut S {
|
pub fn service_mut(&mut self) -> &mut S {
|
||||||
&mut self.service
|
&mut self.service
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get reference to a framed instance wrapped by `Dispatcher`
|
/// Get reference to a framed instance wrapped by `Dispatcher`
|
||||||
/// instance.
|
/// instance.
|
||||||
pub fn get_framed(&self) -> &Framed<T, U> {
|
pub fn framed(&self) -> &Framed<T, U> {
|
||||||
&self.framed
|
&self.framed
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get mutable reference to a framed instance wrapped by `Dispatcher` instance.
|
/// Get mutable reference to a framed instance wrapped by `Dispatcher` instance.
|
||||||
pub fn get_framed_mut(&mut self) -> &mut Framed<T, U> {
|
pub fn framed_mut(&mut self) -> &mut Framed<T, U> {
|
||||||
&mut self.framed
|
&mut self.framed
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -246,7 +225,7 @@ where
|
|||||||
loop {
|
loop {
|
||||||
let mut this = self.as_mut().project();
|
let mut this = self.as_mut().project();
|
||||||
while !this.framed.is_write_buf_full() {
|
while !this.framed.is_write_buf_full() {
|
||||||
match Pin::new(&mut this.rx).poll_next(cx) {
|
match this.rx.poll_recv(cx) {
|
||||||
Poll::Ready(Some(Ok(Message::Item(msg)))) => {
|
Poll::Ready(Some(Ok(Message::Item(msg)))) => {
|
||||||
if let Err(err) = this.framed.as_mut().write(msg) {
|
if let Err(err) = this.framed.as_mut().write(msg) {
|
||||||
*this.state = State::FramedError(DispatcherError::Encoder(err));
|
*this.state = State::FramedError(DispatcherError::Encoder(err));
|
||||||
@@ -266,7 +245,7 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
if !this.framed.is_write_buf_empty() {
|
if !this.framed.is_write_buf_empty() {
|
||||||
match this.framed.flush(cx) {
|
match this.framed.poll_flush(cx) {
|
||||||
Poll::Pending => break,
|
Poll::Pending => break,
|
||||||
Poll::Ready(Ok(_)) => (),
|
Poll::Ready(Ok(_)) => (),
|
||||||
Poll::Ready(Err(err)) => {
|
Poll::Ready(Err(err)) => {
|
||||||
@@ -298,41 +277,43 @@ where
|
|||||||
type Output = Result<(), DispatcherError<S::Error, U, I>>;
|
type Output = Result<(), DispatcherError<S::Error, U, I>>;
|
||||||
|
|
||||||
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||||
loop {
|
|
||||||
let this = self.as_mut().project();
|
let this = self.as_mut().project();
|
||||||
|
|
||||||
return match this.state {
|
match this.state {
|
||||||
State::Processing => {
|
State::Processing => {
|
||||||
if self.as_mut().poll_read(cx) || self.as_mut().poll_write(cx) {
|
if self.as_mut().poll_read(cx) || self.as_mut().poll_write(cx) {
|
||||||
continue;
|
self.poll(cx)
|
||||||
} else {
|
} else {
|
||||||
Poll::Pending
|
Poll::Pending
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
State::Error(_) => {
|
State::Error(_) => {
|
||||||
// flush write buffer
|
// flush write buffer
|
||||||
if !this.framed.is_write_buf_empty() && this.framed.flush(cx).is_pending() {
|
if !this.framed.is_write_buf_empty() && this.framed.poll_flush(cx).is_pending()
|
||||||
|
{
|
||||||
return Poll::Pending;
|
return Poll::Pending;
|
||||||
}
|
}
|
||||||
|
|
||||||
Poll::Ready(Err(this.state.take_error()))
|
Poll::Ready(Err(this.state.take_error()))
|
||||||
}
|
}
|
||||||
|
|
||||||
State::FlushAndStop => {
|
State::FlushAndStop => {
|
||||||
if !this.framed.is_write_buf_empty() {
|
if !this.framed.is_write_buf_empty() {
|
||||||
match this.framed.flush(cx) {
|
this.framed.poll_flush(cx).map(|res| {
|
||||||
Poll::Ready(Err(err)) => {
|
if let Err(err) = res {
|
||||||
debug!("Error sending data: {:?}", err);
|
debug!("Error sending data: {:?}", err);
|
||||||
Poll::Ready(Ok(()))
|
|
||||||
}
|
|
||||||
Poll::Pending => Poll::Pending,
|
|
||||||
Poll::Ready(Ok(_)) => Poll::Ready(Ok(())),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
} else {
|
} else {
|
||||||
Poll::Ready(Ok(()))
|
Poll::Ready(Ok(()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
State::FramedError(_) => Poll::Ready(Err(this.state.take_framed_error())),
|
State::FramedError(_) => Poll::Ready(Err(this.state.take_framed_error())),
|
||||||
State::Stopping => Poll::Ready(Ok(())),
|
State::Stopping => Poll::Ready(Ok(())),
|
||||||
};
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -7,6 +7,5 @@
|
|||||||
|
|
||||||
pub mod counter;
|
pub mod counter;
|
||||||
pub mod dispatcher;
|
pub mod dispatcher;
|
||||||
pub mod mpsc;
|
|
||||||
pub mod task;
|
pub mod task;
|
||||||
pub mod timeout;
|
pub mod timeout;
|
||||||
|
@@ -1,224 +0,0 @@
|
|||||||
//! A multi-producer, single-consumer, futures-aware, FIFO queue.
|
|
||||||
|
|
||||||
use core::any::Any;
|
|
||||||
use core::cell::RefCell;
|
|
||||||
use core::fmt;
|
|
||||||
use core::pin::Pin;
|
|
||||||
use core::task::{Context, Poll};
|
|
||||||
|
|
||||||
use std::collections::VecDeque;
|
|
||||||
use std::error::Error;
|
|
||||||
use std::rc::Rc;
|
|
||||||
|
|
||||||
use futures_core::stream::Stream;
|
|
||||||
use futures_sink::Sink;
|
|
||||||
|
|
||||||
use crate::task::LocalWaker;
|
|
||||||
|
|
||||||
/// Creates a unbounded in-memory channel with buffered storage.
|
|
||||||
pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
|
|
||||||
let shared = Rc::new(RefCell::new(Shared {
|
|
||||||
has_receiver: true,
|
|
||||||
buffer: VecDeque::new(),
|
|
||||||
blocked_recv: LocalWaker::new(),
|
|
||||||
}));
|
|
||||||
let sender = Sender {
|
|
||||||
shared: shared.clone(),
|
|
||||||
};
|
|
||||||
let receiver = Receiver { shared };
|
|
||||||
(sender, receiver)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
struct Shared<T> {
|
|
||||||
buffer: VecDeque<T>,
|
|
||||||
blocked_recv: LocalWaker,
|
|
||||||
has_receiver: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The transmission end of a channel.
|
|
||||||
///
|
|
||||||
/// This is created by the `channel` function.
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct Sender<T> {
|
|
||||||
shared: Rc<RefCell<Shared<T>>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> Unpin for Sender<T> {}
|
|
||||||
|
|
||||||
impl<T> Sender<T> {
|
|
||||||
/// Sends the provided message along this channel.
|
|
||||||
pub fn send(&self, item: T) -> Result<(), SendError<T>> {
|
|
||||||
let mut shared = self.shared.borrow_mut();
|
|
||||||
if !shared.has_receiver {
|
|
||||||
return Err(SendError(item)); // receiver was dropped
|
|
||||||
};
|
|
||||||
shared.buffer.push_back(item);
|
|
||||||
shared.blocked_recv.wake();
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Closes the sender half
|
|
||||||
///
|
|
||||||
/// This prevents any further messages from being sent on the channel while
|
|
||||||
/// still enabling the receiver to drain messages that are buffered.
|
|
||||||
pub fn close(&mut self) {
|
|
||||||
self.shared.borrow_mut().has_receiver = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> Clone for Sender<T> {
|
|
||||||
fn clone(&self) -> Self {
|
|
||||||
Sender {
|
|
||||||
shared: self.shared.clone(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> Sink<T> for Sender<T> {
|
|
||||||
type Error = SendError<T>;
|
|
||||||
|
|
||||||
fn poll_ready(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
|
||||||
Poll::Ready(Ok(()))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn start_send(self: Pin<&mut Self>, item: T) -> Result<(), SendError<T>> {
|
|
||||||
self.send(item)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), SendError<T>>> {
|
|
||||||
Poll::Ready(Ok(()))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
|
||||||
Poll::Ready(Ok(()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> Drop for Sender<T> {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
let count = Rc::strong_count(&self.shared);
|
|
||||||
let shared = self.shared.borrow_mut();
|
|
||||||
|
|
||||||
// check is last sender is about to drop
|
|
||||||
if shared.has_receiver && count == 2 {
|
|
||||||
// Wake up receiver as its stream has ended
|
|
||||||
shared.blocked_recv.wake();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The receiving end of a channel which implements the `Stream` trait.
|
|
||||||
///
|
|
||||||
/// This is created by the `channel` function.
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct Receiver<T> {
|
|
||||||
shared: Rc<RefCell<Shared<T>>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> Receiver<T> {
|
|
||||||
/// Create Sender
|
|
||||||
pub fn sender(&self) -> Sender<T> {
|
|
||||||
Sender {
|
|
||||||
shared: self.shared.clone(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> Unpin for Receiver<T> {}
|
|
||||||
|
|
||||||
impl<T> Stream for Receiver<T> {
|
|
||||||
type Item = T;
|
|
||||||
|
|
||||||
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
|
||||||
let mut shared = self.shared.borrow_mut();
|
|
||||||
if Rc::strong_count(&self.shared) == 1 {
|
|
||||||
// All senders have been dropped, so drain the buffer and end the
|
|
||||||
// stream.
|
|
||||||
Poll::Ready(shared.buffer.pop_front())
|
|
||||||
} else if let Some(msg) = shared.buffer.pop_front() {
|
|
||||||
Poll::Ready(Some(msg))
|
|
||||||
} else {
|
|
||||||
shared.blocked_recv.register(cx.waker());
|
|
||||||
Poll::Pending
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> Drop for Receiver<T> {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
let mut shared = self.shared.borrow_mut();
|
|
||||||
shared.buffer.clear();
|
|
||||||
shared.has_receiver = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Error type for sending, used when the receiving end of a channel is
|
|
||||||
/// dropped
|
|
||||||
pub struct SendError<T>(T);
|
|
||||||
|
|
||||||
impl<T> fmt::Debug for SendError<T> {
|
|
||||||
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
fmt.debug_tuple("SendError").field(&"...").finish()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> fmt::Display for SendError<T> {
|
|
||||||
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
write!(fmt, "send failed because receiver is gone")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: Any> Error for SendError<T> {
|
|
||||||
fn description(&self) -> &str {
|
|
||||||
"send failed because receiver is gone"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> SendError<T> {
|
|
||||||
/// Returns the message that was attempted to be sent but failed.
|
|
||||||
pub fn into_inner(self) -> T {
|
|
||||||
self.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use futures_util::future::lazy;
|
|
||||||
use futures_util::{stream::Stream, StreamExt};
|
|
||||||
|
|
||||||
#[actix_rt::test]
|
|
||||||
async fn test_mpsc() {
|
|
||||||
let (tx, mut rx) = channel();
|
|
||||||
tx.send("test").unwrap();
|
|
||||||
assert_eq!(rx.next().await.unwrap(), "test");
|
|
||||||
|
|
||||||
let tx2 = tx.clone();
|
|
||||||
tx2.send("test2").unwrap();
|
|
||||||
assert_eq!(rx.next().await.unwrap(), "test2");
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
lazy(|cx| Pin::new(&mut rx).poll_next(cx)).await,
|
|
||||||
Poll::Pending
|
|
||||||
);
|
|
||||||
drop(tx2);
|
|
||||||
assert_eq!(
|
|
||||||
lazy(|cx| Pin::new(&mut rx).poll_next(cx)).await,
|
|
||||||
Poll::Pending
|
|
||||||
);
|
|
||||||
drop(tx);
|
|
||||||
assert_eq!(rx.next().await, None);
|
|
||||||
|
|
||||||
let (tx, rx) = channel();
|
|
||||||
tx.send("test").unwrap();
|
|
||||||
drop(rx);
|
|
||||||
assert!(tx.send("test").is_err());
|
|
||||||
|
|
||||||
let (mut tx, _) = channel();
|
|
||||||
let tx2 = tx.clone();
|
|
||||||
tx.close();
|
|
||||||
assert!(tx.send("test").is_err());
|
|
||||||
assert!(tx2.send("test").is_err());
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,49 +1,30 @@
|
|||||||
use core::cell::UnsafeCell;
|
use core::{cell::Cell, fmt, marker::PhantomData, task::Waker};
|
||||||
use core::fmt;
|
|
||||||
use core::marker::PhantomData;
|
|
||||||
use core::task::Waker;
|
|
||||||
|
|
||||||
/// A synchronization primitive for task wakeup.
|
/// A synchronization primitive for task wakeup.
|
||||||
///
|
///
|
||||||
/// Sometimes the task interested in a given event will change over time.
|
/// Sometimes the task interested in a given event will change over time. A `LocalWaker` can
|
||||||
/// An `LocalWaker` can coordinate concurrent notifications with the consumer
|
/// coordinate concurrent notifications with the consumer, potentially "updating" the underlying
|
||||||
/// potentially "updating" the underlying task to wake up. This is useful in
|
/// task to wake up. This is useful in scenarios where a computation completes in another task and
|
||||||
/// scenarios where a computation completes in another task and wants to
|
/// wants to notify the consumer, but the consumer is in the process of being migrated to a new
|
||||||
/// notify the consumer, but the consumer is in the process of being migrated to
|
/// logical task.
|
||||||
/// a new logical task.
|
|
||||||
///
|
///
|
||||||
/// Consumers should call `register` before checking the result of a computation
|
/// Consumers should call [`register`] before checking the result of a computation and producers
|
||||||
/// and producers should call `wake` after producing the computation (this
|
/// should call `wake` after producing the computation (this differs from the usual `thread::park`
|
||||||
/// differs from the usual `thread::park` pattern). It is also permitted for
|
/// pattern). It is also permitted for [`wake`] to be called _before_ [`register`]. This results in
|
||||||
/// `wake` to be called **before** `register`. This results in a no-op.
|
/// a no-op.
|
||||||
///
|
///
|
||||||
/// A single `AtomicWaker` may be reused for any number of calls to `register` or
|
/// A single `LocalWaker` may be reused for any number of calls to [`register`] or [`wake`].
|
||||||
/// `wake`.
|
|
||||||
// TODO: Refactor to Cell when remove deprecated methods (@botika)
|
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub struct LocalWaker {
|
pub struct LocalWaker {
|
||||||
pub(crate) waker: UnsafeCell<Option<Waker>>,
|
pub(crate) waker: Cell<Option<Waker>>,
|
||||||
// mark LocalWaker as a !Send type.
|
// mark LocalWaker as a !Send type.
|
||||||
_t: PhantomData<*const ()>,
|
_phantom: PhantomData<*const ()>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl LocalWaker {
|
impl LocalWaker {
|
||||||
/// Create an `LocalWaker`.
|
/// Creates a new, empty `LocalWaker`.
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
LocalWaker {
|
LocalWaker::default()
|
||||||
waker: UnsafeCell::new(None),
|
|
||||||
_t: PhantomData,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[deprecated(
|
|
||||||
since = "2.1.0",
|
|
||||||
note = "In favor of `wake`. State of the register doesn't matter at `wake` up"
|
|
||||||
)]
|
|
||||||
/// Check if waker has been registered.
|
|
||||||
#[inline]
|
|
||||||
pub fn is_registered(&self) -> bool {
|
|
||||||
unsafe { (*self.waker.get()).is_some() }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Registers the waker to be notified on calls to `wake`.
|
/// Registers the waker to be notified on calls to `wake`.
|
||||||
@@ -51,12 +32,9 @@ impl LocalWaker {
|
|||||||
/// Returns `true` if waker was registered before.
|
/// Returns `true` if waker was registered before.
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn register(&self, waker: &Waker) -> bool {
|
pub fn register(&self, waker: &Waker) -> bool {
|
||||||
unsafe {
|
let last_waker = self.waker.replace(Some(waker.clone()));
|
||||||
let w = self.waker.get();
|
|
||||||
let last_waker = w.replace(Some(waker.clone()));
|
|
||||||
last_waker.is_some()
|
last_waker.is_some()
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/// Calls `wake` on the last `Waker` passed to `register`.
|
/// Calls `wake` on the last `Waker` passed to `register`.
|
||||||
///
|
///
|
||||||
@@ -73,7 +51,7 @@ impl LocalWaker {
|
|||||||
/// If a waker has not been registered, this returns `None`.
|
/// If a waker has not been registered, this returns `None`.
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn take(&self) -> Option<Waker> {
|
pub fn take(&self) -> Option<Waker> {
|
||||||
unsafe { (*self.waker.get()).take() }
|
self.waker.take()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user