mirror of
https://github.com/fafhrd91/actix-web
synced 2025-07-03 01:34:32 +02:00
Compare commits
12 Commits
files-v0.6
...
http-v3.0.
Author | SHA1 | Date | |
---|---|---|---|
e045418038 | |||
a978b417f3 | |||
fa82b698b7 | |||
fc4cdf81eb | |||
654dc64a09 | |||
cf54388534 | |||
39243095b5 | |||
89c6d62656 | |||
52bbbd1d73 | |||
3e6e9779dc | |||
9bdd334bb4 | |||
bcbbc115aa |
8
.github/workflows/ci.yml
vendored
8
.github/workflows/ci.yml
vendored
@ -159,7 +159,7 @@ jobs:
|
||||
with: { file: cobertura.xml }
|
||||
|
||||
rustdoc:
|
||||
name: rustdoc
|
||||
name: doc tests
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
@ -177,12 +177,6 @@ jobs:
|
||||
- name: Cache Dependencies
|
||||
uses: Swatinem/rust-cache@v1.3.0
|
||||
|
||||
# - name: Install cargo-hack
|
||||
# uses: actions-rs/cargo@v1
|
||||
# with:
|
||||
# command: install
|
||||
# args: cargo-hack
|
||||
|
||||
- name: doc tests
|
||||
uses: actions-rs/cargo@v1
|
||||
timeout-minutes: 60
|
||||
|
@ -3,6 +3,13 @@
|
||||
## Unreleased - 2021-xx-xx
|
||||
|
||||
|
||||
## 4.0.0-beta.13 - 2021-11-30
|
||||
### Changed
|
||||
* Update `actix-tls` to `3.0.0-rc.1`. [#2474]
|
||||
|
||||
[#2474]: https://github.com/actix/actix-web/pull/2474
|
||||
|
||||
|
||||
## 4.0.0-beta.12 - 2021-11-22
|
||||
### Changed
|
||||
* Compress middleware's response type is now `AnyBody<Encoder<B>>`. [#2448]
|
||||
|
17
Cargo.toml
17
Cargo.toml
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-web"
|
||||
version = "4.0.0-beta.12"
|
||||
version = "4.0.0-beta.13"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix Web is a powerful, pragmatic, and extremely fast web framework for Rust"
|
||||
keywords = ["actix", "http", "web", "framework", "async"]
|
||||
@ -75,9 +75,9 @@ actix-rt = "2.3"
|
||||
actix-server = "2.0.0-beta.9"
|
||||
actix-service = "2.0.0"
|
||||
actix-utils = "3.0.0"
|
||||
actix-tls = { version = "3.0.0-beta.9", default-features = false, optional = true }
|
||||
actix-tls = { version = "3.0.0-rc.1", default-features = false, optional = true }
|
||||
|
||||
actix-http = "3.0.0-beta.13"
|
||||
actix-http = "3.0.0-beta.14"
|
||||
actix-router = "0.5.0-beta.2"
|
||||
actix-web-codegen = "0.5.0-beta.5"
|
||||
|
||||
@ -96,7 +96,7 @@ once_cell = "1.5"
|
||||
log = "0.4"
|
||||
mime = "0.3"
|
||||
paste = "1"
|
||||
pin-project = "1.0.0"
|
||||
pin-project-lite = "0.2.7"
|
||||
regex = "1.4"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
@ -143,6 +143,15 @@ actix-web-actors = { path = "actix-web-actors" }
|
||||
actix-web-codegen = { path = "actix-web-codegen" }
|
||||
awc = { path = "awc" }
|
||||
|
||||
# uncomment for quick testing against local actix-net repo
|
||||
# actix-service = { path = "../actix-net/actix-service" }
|
||||
# actix-macros = { path = "../actix-net/actix-macros" }
|
||||
# actix-rt = { path = "../actix-net/actix-rt" }
|
||||
# actix-codec = { path = "../actix-net/actix-codec" }
|
||||
# actix-utils = { path = "../actix-net/actix-utils" }
|
||||
# actix-tls = { path = "../actix-net/actix-tls" }
|
||||
# actix-server = { path = "../actix-net/actix-server" }
|
||||
|
||||
[[test]]
|
||||
name = "test_server"
|
||||
required-features = ["compress-brotli", "compress-gzip", "compress-zstd", "cookies"]
|
||||
|
@ -6,10 +6,10 @@
|
||||
<p>
|
||||
|
||||
[](https://crates.io/crates/actix-web)
|
||||
[](https://docs.rs/actix-web/4.0.0-beta.12)
|
||||
[](https://docs.rs/actix-web/4.0.0-beta.13)
|
||||
[](https://blog.rust-lang.org/2021/05/06/Rust-1.52.0.html)
|
||||

|
||||
[](https://deps.rs/crate/actix-web/4.0.0-beta.12)
|
||||
[](https://deps.rs/crate/actix-web/4.0.0-beta.13)
|
||||
<br />
|
||||
[](https://github.com/actix/actix-web/actions)
|
||||
[](https://codecov.io/gh/actix/actix-web)
|
||||
|
@ -23,8 +23,9 @@ experimental-io-uring = ["actix-web/experimental-io-uring", "tokio-uring"]
|
||||
|
||||
[dependencies]
|
||||
actix-web = { version = "4.0.0-beta.11", default-features = false }
|
||||
actix-http = "3.0.0-beta.13"
|
||||
actix-service = "2.0.0"
|
||||
actix-http = "3.0.0-beta.14"
|
||||
actix-service = "2"
|
||||
actix-utils = "3"
|
||||
|
||||
askama_escape = "0.10"
|
||||
bitflags = "1"
|
||||
|
@ -1,9 +1,9 @@
|
||||
use std::{
|
||||
future::{ready, Ready},
|
||||
path::{Path, PathBuf},
|
||||
str::FromStr,
|
||||
};
|
||||
|
||||
use actix_utils::future::{ready, Ready};
|
||||
use actix_web::{dev::Payload, FromRequest, HttpRequest};
|
||||
|
||||
use crate::error::UriSegmentError;
|
||||
|
@ -3,6 +3,12 @@
|
||||
## Unreleased - 2021-xx-xx
|
||||
|
||||
|
||||
## 3.0.0-beta.8 - 2021-11-30
|
||||
* Update `actix-tls` to `3.0.0-rc.1`. [#2474]
|
||||
|
||||
[#2474]: https://github.com/actix/actix-web/pull/2474
|
||||
|
||||
|
||||
## 3.0.0-beta.7 - 2021-11-22
|
||||
* Fix compatibility with experimental `io-uring` feature of `actix-rt`. [#2408]
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-http-test"
|
||||
version = "3.0.0-beta.7"
|
||||
version = "3.0.0-beta.8"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Various helpers for Actix applications to use during testing"
|
||||
keywords = ["http", "web", "framework", "async", "futures"]
|
||||
@ -31,7 +31,7 @@ openssl = ["tls-openssl", "awc/openssl"]
|
||||
[dependencies]
|
||||
actix-service = "2.0.0"
|
||||
actix-codec = "0.4.1"
|
||||
actix-tls = "3.0.0-beta.9"
|
||||
actix-tls = "3.0.0-rc.1"
|
||||
actix-utils = "3.0.0"
|
||||
actix-rt = "2.2"
|
||||
actix-server = "2.0.0-beta.9"
|
||||
@ -52,4 +52,4 @@ tokio = { version = "1.2", features = ["sync"] }
|
||||
|
||||
[dev-dependencies]
|
||||
actix-web = { version = "4.0.0-beta.11", default-features = false, features = ["cookies"] }
|
||||
actix-http = "3.0.0-beta.13"
|
||||
actix-http = "3.0.0-beta.14"
|
||||
|
@ -3,11 +3,11 @@
|
||||
> Various helpers for Actix applications to use during testing.
|
||||
|
||||
[](https://crates.io/crates/actix-http-test)
|
||||
[](https://docs.rs/actix-http-test/3.0.0-beta.7)
|
||||
[](https://docs.rs/actix-http-test/3.0.0-beta.8)
|
||||
[](https://blog.rust-lang.org/2021/05/06/Rust-1.52.0.html)
|
||||

|
||||
<br>
|
||||
[](https://deps.rs/crate/actix-http-test/3.0.0-beta.7)
|
||||
[](https://deps.rs/crate/actix-http-test/3.0.0-beta.8)
|
||||
[](https://crates.io/crates/actix-http-test)
|
||||
[](https://discord.gg/NWpN5mmg3x)
|
||||
|
||||
|
@ -3,6 +3,18 @@
|
||||
## Unreleased - 2021-xx-xx
|
||||
|
||||
|
||||
## 3.0.0-beta.14 - 2021-11-30
|
||||
### Changed
|
||||
* Guarantee ordering of `header::GetAll` iterator to be same as insertion order. [#2467]
|
||||
* Expose `header::map` module. [#2467]
|
||||
* Implement `ExactSizeIterator` and `FusedIterator` for all `HeaderMap` iterators. [#2470]
|
||||
* Update `actix-tls` to `3.0.0-rc.1`. [#2474]
|
||||
|
||||
[#2467]: https://github.com/actix/actix-web/pull/2467
|
||||
[#2470]: https://github.com/actix/actix-web/pull/2470
|
||||
[#2474]: https://github.com/actix/actix-web/pull/2474
|
||||
|
||||
|
||||
## 3.0.0-beta.13 - 2021-11-22
|
||||
### Added
|
||||
* `body::AnyBody::empty` for quickly creating an empty body. [#2446]
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-http"
|
||||
version = "3.0.0-beta.13"
|
||||
version = "3.0.0-beta.14"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "HTTP primitives for the Actix ecosystem"
|
||||
keywords = ["actix", "http", "framework", "async", "futures"]
|
||||
@ -73,7 +73,7 @@ sha-1 = "0.9"
|
||||
smallvec = "1.6.1"
|
||||
|
||||
# tls
|
||||
actix-tls = { version = "3.0.0-beta.9", default-features = false, optional = true }
|
||||
actix-tls = { version = "3.0.0-rc.1", default-features = false, optional = true }
|
||||
|
||||
# compression
|
||||
brotli2 = { version="0.3.2", optional = true }
|
||||
@ -83,7 +83,7 @@ zstd = { version = "0.9", optional = true }
|
||||
[dev-dependencies]
|
||||
actix-server = "2.0.0-beta.9"
|
||||
actix-http-test = { version = "3.0.0-beta.7", features = ["openssl"] }
|
||||
actix-tls = { version = "3.0.0-beta.9", features = ["openssl"] }
|
||||
actix-tls = { version = "3.0.0-rc.1", features = ["openssl"] }
|
||||
async-stream = "0.3"
|
||||
criterion = { version = "0.3", features = ["html_reports"] }
|
||||
env_logger = "0.9"
|
||||
|
@ -3,11 +3,11 @@
|
||||
> HTTP primitives for the Actix ecosystem.
|
||||
|
||||
[](https://crates.io/crates/actix-http)
|
||||
[](https://docs.rs/actix-http/3.0.0-beta.13)
|
||||
[](https://docs.rs/actix-http/3.0.0-beta.14)
|
||||
[](https://blog.rust-lang.org/2021/05/06/Rust-1.52.0.html)
|
||||

|
||||
<br />
|
||||
[](https://deps.rs/crate/actix-http/3.0.0-beta.13)
|
||||
[](https://deps.rs/crate/actix-http/3.0.0-beta.14)
|
||||
[](https://crates.io/crates/actix-http)
|
||||
[](https://discord.gg/NWpN5mmg3x)
|
||||
|
||||
|
@ -103,7 +103,10 @@ mod openssl {
|
||||
use super::*;
|
||||
|
||||
use actix_tls::accept::{
|
||||
openssl::{Acceptor, SslAcceptor, SslError, TlsStream},
|
||||
openssl::{
|
||||
reexports::{Error as SslError, SslAcceptor},
|
||||
Acceptor, TlsStream,
|
||||
},
|
||||
TlsError,
|
||||
};
|
||||
|
||||
@ -164,7 +167,7 @@ mod rustls {
|
||||
|
||||
use actix_service::ServiceFactoryExt as _;
|
||||
use actix_tls::accept::{
|
||||
rustls::{Acceptor, ServerConfig, TlsStream},
|
||||
rustls::{reexports::ServerConfig, Acceptor, TlsStream},
|
||||
TlsError,
|
||||
};
|
||||
|
||||
|
@ -103,7 +103,10 @@ where
|
||||
mod openssl {
|
||||
use actix_service::ServiceFactoryExt as _;
|
||||
use actix_tls::accept::{
|
||||
openssl::{Acceptor, SslAcceptor, SslError, TlsStream},
|
||||
openssl::{
|
||||
reexports::{Error as SslError, SslAcceptor},
|
||||
Acceptor, TlsStream,
|
||||
},
|
||||
TlsError,
|
||||
};
|
||||
|
||||
@ -151,7 +154,7 @@ mod rustls {
|
||||
|
||||
use actix_service::ServiceFactoryExt as _;
|
||||
use actix_tls::accept::{
|
||||
rustls::{Acceptor, ServerConfig, TlsStream},
|
||||
rustls::{reexports::ServerConfig, Acceptor, TlsStream},
|
||||
TlsError,
|
||||
};
|
||||
|
||||
|
@ -1,11 +1,12 @@
|
||||
//! Helper trait for types that can be effectively borrowed as a [HeaderValue].
|
||||
//!
|
||||
//! [HeaderValue]: crate::http::HeaderValue
|
||||
//! Sealed [`AsHeaderName`] trait and implementations.
|
||||
|
||||
use std::{borrow::Cow, str::FromStr};
|
||||
use std::{borrow::Cow, str::FromStr as _};
|
||||
|
||||
use http::header::{HeaderName, InvalidHeaderName};
|
||||
|
||||
/// Sealed trait implemented for types that can be effectively borrowed as a [`HeaderValue`].
|
||||
///
|
||||
/// [`HeaderValue`]: crate::http::HeaderValue
|
||||
pub trait AsHeaderName: Sealed {}
|
||||
|
||||
pub struct Seal;
|
||||
|
@ -1,4 +1,6 @@
|
||||
use std::convert::TryFrom;
|
||||
//! [`IntoHeaderPair`] trait and implementations.
|
||||
|
||||
use std::convert::TryFrom as _;
|
||||
|
||||
use http::{
|
||||
header::{HeaderName, InvalidHeaderName, InvalidHeaderValue},
|
||||
@ -7,7 +9,10 @@ use http::{
|
||||
|
||||
use super::{Header, IntoHeaderValue};
|
||||
|
||||
/// Transforms structures into header K/V pairs for inserting into `HeaderMap`s.
|
||||
/// An interface for types that can be converted into a [`HeaderName`]/[`HeaderValue`] pair for
|
||||
/// insertion into a [`HeaderMap`].
|
||||
///
|
||||
/// [`HeaderMap`]: crate::http::HeaderMap
|
||||
pub trait IntoHeaderPair: Sized {
|
||||
type Error: Into<HttpError>;
|
||||
|
||||
|
@ -1,10 +1,12 @@
|
||||
use std::convert::TryFrom;
|
||||
//! [`IntoHeaderValue`] trait and implementations.
|
||||
|
||||
use std::convert::TryFrom as _;
|
||||
|
||||
use bytes::Bytes;
|
||||
use http::{header::InvalidHeaderValue, Error as HttpError, HeaderValue};
|
||||
use mime::Mime;
|
||||
|
||||
/// A trait for any object that can be Converted to a `HeaderValue`
|
||||
/// An interface for types that can be converted into a [`HeaderValue`].
|
||||
pub trait IntoHeaderValue: Sized {
|
||||
/// The type returned in the event of a conversion error.
|
||||
type Error: Into<HttpError>;
|
||||
|
@ -1,6 +1,6 @@
|
||||
//! A multi-value [`HeaderMap`] and its iterators.
|
||||
|
||||
use std::{borrow::Cow, collections::hash_map, ops};
|
||||
use std::{borrow::Cow, collections::hash_map, iter, ops};
|
||||
|
||||
use ahash::AHashMap;
|
||||
use http::header::{HeaderName, HeaderValue};
|
||||
@ -288,7 +288,7 @@ impl HeaderMap {
|
||||
/// Returns an iterator over all values associated with a header name.
|
||||
///
|
||||
/// The returned iterator does not incur any allocations and will yield no items if there are no
|
||||
/// values associated with the key. Iteration order is **not** guaranteed to be the same as
|
||||
/// values associated with the key. Iteration order is guaranteed to be the same as
|
||||
/// insertion order.
|
||||
///
|
||||
/// # Examples
|
||||
@ -355,6 +355,19 @@ impl HeaderMap {
|
||||
///
|
||||
/// assert_eq!(map.len(), 1);
|
||||
/// ```
|
||||
///
|
||||
/// A convenience method is provided on the returned iterator to check if the insertion replaced
|
||||
/// any values.
|
||||
/// ```
|
||||
/// # use actix_http::http::{header, HeaderMap, HeaderValue};
|
||||
/// let mut map = HeaderMap::new();
|
||||
///
|
||||
/// let removed = map.insert(header::ACCEPT, HeaderValue::from_static("text/plain"));
|
||||
/// assert!(removed.is_empty());
|
||||
///
|
||||
/// let removed = map.insert(header::ACCEPT, HeaderValue::from_static("text/html"));
|
||||
/// assert!(!removed.is_empty());
|
||||
/// ```
|
||||
pub fn insert(&mut self, key: HeaderName, val: HeaderValue) -> Removed {
|
||||
let value = self.inner.insert(key, Value::one(val));
|
||||
Removed::new(value)
|
||||
@ -393,6 +406,9 @@ impl HeaderMap {
|
||||
|
||||
/// Removes all headers for a particular header name from the map.
|
||||
///
|
||||
/// Providing an invalid header names (as a string argument) will have no effect and return
|
||||
/// without error.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// # use actix_http::http::{header, HeaderMap, HeaderValue};
|
||||
@ -409,6 +425,21 @@ impl HeaderMap {
|
||||
/// assert!(removed.next().is_none());
|
||||
///
|
||||
/// assert!(map.is_empty());
|
||||
/// ```
|
||||
///
|
||||
/// A convenience method is provided on the returned iterator to check if the `remove` call
|
||||
/// actually removed any values.
|
||||
/// ```
|
||||
/// # use actix_http::http::{header, HeaderMap, HeaderValue};
|
||||
/// let mut map = HeaderMap::new();
|
||||
///
|
||||
/// let removed = map.remove("accept");
|
||||
/// assert!(removed.is_empty());
|
||||
///
|
||||
/// map.insert(header::ACCEPT, HeaderValue::from_static("text/html"));
|
||||
/// let removed = map.remove("accept");
|
||||
/// assert!(!removed.is_empty());
|
||||
/// ```
|
||||
pub fn remove(&mut self, key: impl AsHeaderName) -> Removed {
|
||||
let value = match key.try_as_name(super::as_name::Seal) {
|
||||
Ok(Cow::Borrowed(name)) => self.inner.remove(name),
|
||||
@ -550,7 +581,8 @@ impl HeaderMap {
|
||||
}
|
||||
}
|
||||
|
||||
/// Note that this implementation will clone a [HeaderName] for each value.
|
||||
/// Note that this implementation will clone a [HeaderName] for each value. Consider using
|
||||
/// [`drain`](Self::drain) to control header name cloning.
|
||||
impl IntoIterator for HeaderMap {
|
||||
type Item = (HeaderName, HeaderValue);
|
||||
type IntoIter = IntoIter;
|
||||
@ -571,7 +603,7 @@ impl<'a> IntoIterator for &'a HeaderMap {
|
||||
}
|
||||
}
|
||||
|
||||
/// Iterator for all values with the same header name.
|
||||
/// Iterator over borrowed values with the same associated name.
|
||||
///
|
||||
/// See [`HeaderMap::get_all`].
|
||||
#[derive(Debug)]
|
||||
@ -613,18 +645,36 @@ impl<'a> Iterator for GetAll<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Iterator for owned [`HeaderValue`]s with the same associated [`HeaderName`] returned from methods
|
||||
/// on [`HeaderMap`] that remove or replace items.
|
||||
impl ExactSizeIterator for GetAll<'_> {}
|
||||
|
||||
impl iter::FusedIterator for GetAll<'_> {}
|
||||
|
||||
/// Iterator over removed, owned values with the same associated name.
|
||||
///
|
||||
/// Returned from methods that remove or replace items. See [`HeaderMap::insert`]
|
||||
/// and [`HeaderMap::remove`].
|
||||
#[derive(Debug)]
|
||||
pub struct Removed {
|
||||
inner: Option<smallvec::IntoIter<[HeaderValue; 4]>>,
|
||||
}
|
||||
|
||||
impl<'a> Removed {
|
||||
impl Removed {
|
||||
fn new(value: Option<Value>) -> Self {
|
||||
let inner = value.map(|value| value.inner.into_iter());
|
||||
Self { inner }
|
||||
}
|
||||
|
||||
/// Returns true if iterator contains no elements, without consuming it.
|
||||
///
|
||||
/// If called immediately after [`HeaderMap::insert`] or [`HeaderMap::remove`], it will indicate
|
||||
/// wether any items were actually replaced or removed, respectively.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
match self.inner {
|
||||
// size hint lower bound of smallvec is the correct length
|
||||
Some(ref iter) => iter.size_hint().0 == 0,
|
||||
None => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Iterator for Removed {
|
||||
@ -644,7 +694,11 @@ impl Iterator for Removed {
|
||||
}
|
||||
}
|
||||
|
||||
/// Iterator over all [`HeaderName`]s in the map.
|
||||
impl ExactSizeIterator for Removed {}
|
||||
|
||||
impl iter::FusedIterator for Removed {}
|
||||
|
||||
/// Iterator over all names in the map.
|
||||
#[derive(Debug)]
|
||||
pub struct Keys<'a>(hash_map::Keys<'a, HeaderName, Value>);
|
||||
|
||||
@ -662,6 +716,11 @@ impl<'a> Iterator for Keys<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
impl ExactSizeIterator for Keys<'_> {}
|
||||
|
||||
impl iter::FusedIterator for Keys<'_> {}
|
||||
|
||||
/// Iterator over borrowed name-value pairs.
|
||||
#[derive(Debug)]
|
||||
pub struct Iter<'a> {
|
||||
inner: hash_map::Iter<'a, HeaderName, Value>,
|
||||
@ -713,6 +772,10 @@ impl<'a> Iterator for Iter<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
impl ExactSizeIterator for Iter<'_> {}
|
||||
|
||||
impl iter::FusedIterator for Iter<'_> {}
|
||||
|
||||
/// Iterator over drained name-value pairs.
|
||||
///
|
||||
/// Iterator items are `(Option<HeaderName>, HeaderValue)` to avoid cloning.
|
||||
@ -764,6 +827,10 @@ impl<'a> Iterator for Drain<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
impl ExactSizeIterator for Drain<'_> {}
|
||||
|
||||
impl iter::FusedIterator for Drain<'_> {}
|
||||
|
||||
/// Iterator over owned name-value pairs.
|
||||
///
|
||||
/// Implementation necessarily clones header names for each value.
|
||||
@ -814,12 +881,27 @@ impl Iterator for IntoIter {
|
||||
}
|
||||
}
|
||||
|
||||
impl ExactSizeIterator for IntoIter {}
|
||||
|
||||
impl iter::FusedIterator for IntoIter {}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::iter::FusedIterator;
|
||||
|
||||
use http::header;
|
||||
use static_assertions::assert_impl_all;
|
||||
|
||||
use super::*;
|
||||
|
||||
assert_impl_all!(HeaderMap: IntoIterator);
|
||||
assert_impl_all!(Keys<'_>: Iterator, ExactSizeIterator, FusedIterator);
|
||||
assert_impl_all!(GetAll<'_>: Iterator, ExactSizeIterator, FusedIterator);
|
||||
assert_impl_all!(Removed: Iterator, ExactSizeIterator, FusedIterator);
|
||||
assert_impl_all!(Iter<'_>: Iterator, ExactSizeIterator, FusedIterator);
|
||||
assert_impl_all!(IntoIter: Iterator, ExactSizeIterator, FusedIterator);
|
||||
assert_impl_all!(Drain<'_>: Iterator, ExactSizeIterator, FusedIterator);
|
||||
|
||||
#[test]
|
||||
fn create() {
|
||||
let map = HeaderMap::new();
|
||||
@ -945,6 +1027,56 @@ mod tests {
|
||||
assert_eq!(vals.next(), removed.next().as_ref());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_all_iteration_order_matches_insertion_order() {
|
||||
let mut map = HeaderMap::new();
|
||||
|
||||
let mut vals = map.get_all(header::COOKIE);
|
||||
assert!(vals.next().is_none());
|
||||
|
||||
map.append(header::COOKIE, HeaderValue::from_static("1"));
|
||||
let mut vals = map.get_all(header::COOKIE);
|
||||
assert_eq!(vals.next().unwrap().as_bytes(), b"1");
|
||||
assert!(vals.next().is_none());
|
||||
|
||||
map.append(header::COOKIE, HeaderValue::from_static("2"));
|
||||
let mut vals = map.get_all(header::COOKIE);
|
||||
assert_eq!(vals.next().unwrap().as_bytes(), b"1");
|
||||
assert_eq!(vals.next().unwrap().as_bytes(), b"2");
|
||||
assert!(vals.next().is_none());
|
||||
|
||||
map.append(header::COOKIE, HeaderValue::from_static("3"));
|
||||
map.append(header::COOKIE, HeaderValue::from_static("4"));
|
||||
map.append(header::COOKIE, HeaderValue::from_static("5"));
|
||||
let mut vals = map.get_all(header::COOKIE);
|
||||
assert_eq!(vals.next().unwrap().as_bytes(), b"1");
|
||||
assert_eq!(vals.next().unwrap().as_bytes(), b"2");
|
||||
assert_eq!(vals.next().unwrap().as_bytes(), b"3");
|
||||
assert_eq!(vals.next().unwrap().as_bytes(), b"4");
|
||||
assert_eq!(vals.next().unwrap().as_bytes(), b"5");
|
||||
assert!(vals.next().is_none());
|
||||
|
||||
let _ = map.insert(header::COOKIE, HeaderValue::from_static("6"));
|
||||
let mut vals = map.get_all(header::COOKIE);
|
||||
assert_eq!(vals.next().unwrap().as_bytes(), b"6");
|
||||
assert!(vals.next().is_none());
|
||||
|
||||
let _ = map.insert(header::COOKIE, HeaderValue::from_static("7"));
|
||||
let _ = map.insert(header::COOKIE, HeaderValue::from_static("8"));
|
||||
let mut vals = map.get_all(header::COOKIE);
|
||||
assert_eq!(vals.next().unwrap().as_bytes(), b"8");
|
||||
assert!(vals.next().is_none());
|
||||
|
||||
map.append(header::COOKIE, HeaderValue::from_static("9"));
|
||||
let mut vals = map.get_all(header::COOKIE);
|
||||
assert_eq!(vals.next().unwrap().as_bytes(), b"8");
|
||||
assert_eq!(vals.next().unwrap().as_bytes(), b"9");
|
||||
assert!(vals.next().is_none());
|
||||
|
||||
// check for fused-ness
|
||||
assert!(vals.next().is_none());
|
||||
}
|
||||
|
||||
fn owned_pair<'a>(
|
||||
(name, val): (&'a HeaderName, &'a HeaderValue),
|
||||
) -> (HeaderName, HeaderValue) {
|
||||
|
@ -29,16 +29,14 @@ pub use http::header::{
|
||||
X_FRAME_OPTIONS, X_XSS_PROTECTION,
|
||||
};
|
||||
|
||||
use crate::error::ParseError;
|
||||
use crate::HttpMessage;
|
||||
use crate::{error::ParseError, HttpMessage};
|
||||
|
||||
mod as_name;
|
||||
mod into_pair;
|
||||
mod into_value;
|
||||
mod utils;
|
||||
|
||||
pub(crate) mod map;
|
||||
pub mod map;
|
||||
mod shared;
|
||||
mod utils;
|
||||
|
||||
#[doc(hidden)]
|
||||
pub use self::shared::*;
|
||||
@ -46,12 +44,12 @@ pub use self::shared::*;
|
||||
pub use self::as_name::AsHeaderName;
|
||||
pub use self::into_pair::IntoHeaderPair;
|
||||
pub use self::into_value::IntoHeaderValue;
|
||||
#[doc(hidden)]
|
||||
pub use self::map::GetAll;
|
||||
pub use self::map::HeaderMap;
|
||||
pub use self::utils::*;
|
||||
pub use self::utils::{
|
||||
fmt_comma_delimited, from_comma_delimited, from_one_raw_str, http_percent_encode,
|
||||
};
|
||||
|
||||
/// A trait for any object that already represents a valid header field and value.
|
||||
/// An interface for types that already represent a valid header.
|
||||
pub trait Header: IntoHeaderValue {
|
||||
/// Returns the name of the header field
|
||||
fn name() -> HeaderName;
|
||||
@ -68,7 +66,7 @@ impl From<http::HeaderMap> for HeaderMap {
|
||||
}
|
||||
|
||||
/// This encode set is used for HTTP header values and is defined at
|
||||
/// https://tools.ietf.org/html/rfc5987#section-3.2.
|
||||
/// <https://tools.ietf.org/html/rfc5987#section-3.2>.
|
||||
pub(crate) const HTTP_VALUE: &AsciiSet = &CONTROLS
|
||||
.add(b' ')
|
||||
.add(b'"')
|
||||
|
@ -88,7 +88,7 @@ impl Charset {
|
||||
Iso_8859_8_E => "ISO-8859-8-E",
|
||||
Iso_8859_8_I => "ISO-8859-8-I",
|
||||
Gb2312 => "GB2312",
|
||||
Big5 => "big5",
|
||||
Big5 => "Big5",
|
||||
Koi8_R => "KOI8-R",
|
||||
Ext(ref s) => s,
|
||||
}
|
||||
@ -128,7 +128,7 @@ impl FromStr for Charset {
|
||||
"ISO-8859-8-E" => Iso_8859_8_E,
|
||||
"ISO-8859-8-I" => Iso_8859_8_I,
|
||||
"GB2312" => Gb2312,
|
||||
"big5" => Big5,
|
||||
"BIG5" => Big5,
|
||||
"KOI8-R" => Koi8_R,
|
||||
s => Ext(s.to_owned()),
|
||||
})
|
||||
|
@ -9,14 +9,17 @@ use crate::{
|
||||
HttpMessage,
|
||||
};
|
||||
|
||||
/// Error return when a content encoding is unknown.
|
||||
///
|
||||
/// Example: 'compress'
|
||||
/// Error returned when a content encoding is unknown.
|
||||
#[derive(Debug, Display, Error)]
|
||||
#[display(fmt = "unsupported content encoding")]
|
||||
pub struct ContentEncodingParseError;
|
||||
|
||||
/// Represents a supported content encoding.
|
||||
///
|
||||
/// Includes a commonly-used subset of media types appropriate for use as HTTP content encodings.
|
||||
/// See [IANA HTTP Content Coding Registry].
|
||||
///
|
||||
/// [IANA HTTP Content Coding Registry]: https://www.iana.org/assignments/http-parameters/http-parameters.xhtml
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub enum ContentEncoding {
|
||||
@ -32,7 +35,7 @@ pub enum ContentEncoding {
|
||||
/// Gzip algorithm.
|
||||
Gzip,
|
||||
|
||||
// Zstd algorithm.
|
||||
/// Zstd algorithm.
|
||||
Zstd,
|
||||
|
||||
/// Indicates the identity function (i.e. no compression, nor modification).
|
||||
|
@ -1,3 +1,5 @@
|
||||
//! Header parsing utilities.
|
||||
|
||||
use std::{fmt, str::FromStr};
|
||||
|
||||
use super::HeaderValue;
|
||||
@ -56,6 +58,7 @@ where
|
||||
|
||||
/// Percent encode a sequence of bytes with a character set defined in
|
||||
/// <https://tools.ietf.org/html/rfc5987#section-3.2>
|
||||
#[inline]
|
||||
pub fn http_percent_encode(f: &mut fmt::Formatter<'_>, bytes: &[u8]) -> fmt::Result {
|
||||
let encoded = percent_encoding::percent_encode(bytes, HTTP_VALUE);
|
||||
fmt::Display::fmt(&encoded, f)
|
||||
|
@ -197,7 +197,10 @@ where
|
||||
mod openssl {
|
||||
use actix_service::ServiceFactoryExt as _;
|
||||
use actix_tls::accept::{
|
||||
openssl::{Acceptor, SslAcceptor, SslError, TlsStream},
|
||||
openssl::{
|
||||
reexports::{Error as SslError, SslAcceptor},
|
||||
Acceptor, TlsStream,
|
||||
},
|
||||
TlsError,
|
||||
};
|
||||
|
||||
@ -270,7 +273,7 @@ mod rustls {
|
||||
|
||||
use actix_service::ServiceFactoryExt as _;
|
||||
use actix_tls::accept::{
|
||||
rustls::{Acceptor, ServerConfig, TlsStream},
|
||||
rustls::{reexports::ServerConfig, Acceptor, TlsStream},
|
||||
TlsError,
|
||||
};
|
||||
|
||||
|
@ -220,7 +220,7 @@ impl<T: Into<String>> From<(CloseCode, T)> for CloseReason {
|
||||
}
|
||||
}
|
||||
|
||||
/// The WebSocket GUID as stated in the spec. See https://tools.ietf.org/html/rfc6455#section-1.3.
|
||||
/// The WebSocket GUID as stated in the spec. See <https://tools.ietf.org/html/rfc6455#section-1.3>.
|
||||
static WS_GUID: &[u8] = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
|
||||
|
||||
/// Hashes the `Sec-WebSocket-Key` header according to the WebSocket spec.
|
||||
|
@ -20,7 +20,7 @@ use actix_http::{
|
||||
};
|
||||
use actix_http_test::test_server;
|
||||
use actix_service::{fn_factory_with_config, fn_service};
|
||||
use actix_tls::connect::tls::rustls::webpki_roots_cert_store;
|
||||
use actix_tls::connect::rustls::webpki_roots_cert_store;
|
||||
use actix_utils::future::{err, ok};
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use derive_more::{Display, Error};
|
||||
|
@ -10,8 +10,10 @@
|
||||
* Added `Field::name` method for getting the field name. [#2451]
|
||||
* `MultipartError` now marks variants with inner errors as the source. [#2451]
|
||||
* `MultipartError` is now marked as non-exhaustive. [#2451]
|
||||
* Polling `Field` after dropping `Multipart` now fails immediately instead of hanging forever. [#2463]
|
||||
|
||||
[#2451]: https://github.com/actix/actix-web/pull/2451
|
||||
[#2463]: https://github.com/actix/actix-web/pull/2463
|
||||
|
||||
|
||||
## 0.4.0-beta.7 - 2021-10-20
|
||||
|
@ -20,7 +20,6 @@ actix-utils = "3.0.0"
|
||||
bytes = "1"
|
||||
derive_more = "0.99.5"
|
||||
futures-core = { version = "0.3.7", default-features = false, features = ["alloc"] }
|
||||
futures-util = { version = "0.3.7", default-features = false, features = ["alloc"] }
|
||||
httparse = "1.3"
|
||||
local-waker = "0.1"
|
||||
log = "0.4"
|
||||
@ -29,6 +28,7 @@ twoway = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "2.2"
|
||||
actix-http = "3.0.0-beta.13"
|
||||
actix-http = "3.0.0-beta.14"
|
||||
futures-util = { version = "0.3.7", default-features = false, features = ["alloc"] }
|
||||
tokio = { version = "1", features = ["sync"] }
|
||||
tokio-stream = "0.1"
|
||||
|
@ -17,7 +17,6 @@ use actix_web::{
|
||||
};
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use futures_core::stream::{LocalBoxStream, Stream};
|
||||
use futures_util::stream::StreamExt as _;
|
||||
use local_waker::LocalWaker;
|
||||
|
||||
use crate::error::MultipartError;
|
||||
@ -33,7 +32,7 @@ const MAX_HEADERS: usize = 32;
|
||||
pub struct Multipart {
|
||||
safety: Safety,
|
||||
error: Option<MultipartError>,
|
||||
inner: Option<Rc<RefCell<InnerMultipart>>>,
|
||||
inner: Option<InnerMultipart>,
|
||||
}
|
||||
|
||||
enum InnerMultipartItem {
|
||||
@ -67,7 +66,7 @@ impl Multipart {
|
||||
/// Create multipart instance for boundary.
|
||||
pub fn new<S>(headers: &HeaderMap, stream: S) -> Multipart
|
||||
where
|
||||
S: Stream<Item = Result<Bytes, PayloadError>> + Unpin + 'static,
|
||||
S: Stream<Item = Result<Bytes, PayloadError>> + 'static,
|
||||
{
|
||||
match Self::boundary(headers) {
|
||||
Ok(boundary) => Multipart::from_boundary(boundary, stream),
|
||||
@ -77,39 +76,32 @@ impl Multipart {
|
||||
|
||||
/// Extract boundary info from headers.
|
||||
pub(crate) fn boundary(headers: &HeaderMap) -> Result<String, MultipartError> {
|
||||
if let Some(content_type) = headers.get(&header::CONTENT_TYPE) {
|
||||
if let Ok(content_type) = content_type.to_str() {
|
||||
if let Ok(ct) = content_type.parse::<mime::Mime>() {
|
||||
if let Some(boundary) = ct.get_param(mime::BOUNDARY) {
|
||||
Ok(boundary.as_str().to_owned())
|
||||
} else {
|
||||
Err(MultipartError::Boundary)
|
||||
}
|
||||
} else {
|
||||
Err(MultipartError::ParseContentType)
|
||||
}
|
||||
} else {
|
||||
Err(MultipartError::ParseContentType)
|
||||
}
|
||||
} else {
|
||||
Err(MultipartError::NoContentType)
|
||||
}
|
||||
headers
|
||||
.get(&header::CONTENT_TYPE)
|
||||
.ok_or(MultipartError::NoContentType)?
|
||||
.to_str()
|
||||
.ok()
|
||||
.and_then(|content_type| content_type.parse::<mime::Mime>().ok())
|
||||
.ok_or(MultipartError::ParseContentType)?
|
||||
.get_param(mime::BOUNDARY)
|
||||
.map(|boundary| boundary.as_str().to_owned())
|
||||
.ok_or(MultipartError::Boundary)
|
||||
}
|
||||
|
||||
/// Create multipart instance for given boundary and stream
|
||||
pub(crate) fn from_boundary<S>(boundary: String, stream: S) -> Multipart
|
||||
where
|
||||
S: Stream<Item = Result<Bytes, PayloadError>> + Unpin + 'static,
|
||||
S: Stream<Item = Result<Bytes, PayloadError>> + 'static,
|
||||
{
|
||||
Multipart {
|
||||
error: None,
|
||||
safety: Safety::new(),
|
||||
inner: Some(Rc::new(RefCell::new(InnerMultipart {
|
||||
inner: Some(InnerMultipart {
|
||||
boundary,
|
||||
payload: PayloadRef::new(PayloadBuffer::new(Box::new(stream))),
|
||||
payload: PayloadRef::new(PayloadBuffer::new(stream)),
|
||||
state: InnerState::FirstBoundary,
|
||||
item: InnerMultipartItem::None,
|
||||
}))),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
@ -126,20 +118,27 @@ impl Multipart {
|
||||
impl Stream for Multipart {
|
||||
type Item = Result<Field, MultipartError>;
|
||||
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
if let Some(err) = self.error.take() {
|
||||
Poll::Ready(Some(Err(err)))
|
||||
} else if self.safety.current() {
|
||||
let this = self.get_mut();
|
||||
let mut inner = this.inner.as_mut().unwrap().borrow_mut();
|
||||
if let Some(mut payload) = inner.payload.get_mut(&this.safety) {
|
||||
payload.poll_stream(cx)?;
|
||||
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
let this = self.get_mut();
|
||||
|
||||
match this.inner.as_mut() {
|
||||
Some(inner) => {
|
||||
if let Some(mut buffer) = inner.payload.get_mut(&this.safety) {
|
||||
// check safety and poll read payload to buffer.
|
||||
buffer.poll_stream(cx)?;
|
||||
} else if !this.safety.is_clean() {
|
||||
// safety violation
|
||||
return Poll::Ready(Some(Err(MultipartError::NotConsumed)));
|
||||
} else {
|
||||
return Poll::Pending;
|
||||
}
|
||||
|
||||
inner.poll(&this.safety, cx)
|
||||
}
|
||||
inner.poll(&this.safety, cx)
|
||||
} else if !self.safety.is_clean() {
|
||||
Poll::Ready(Some(Err(MultipartError::NotConsumed)))
|
||||
} else {
|
||||
Poll::Pending
|
||||
None => Poll::Ready(Some(Err(this
|
||||
.error
|
||||
.take()
|
||||
.expect("Multipart polled after finish")))),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -160,17 +159,15 @@ impl InnerMultipart {
|
||||
Ok(httparse::Status::Complete((_, hdrs))) => {
|
||||
// convert headers
|
||||
let mut headers = HeaderMap::with_capacity(hdrs.len());
|
||||
|
||||
for h in hdrs {
|
||||
if let Ok(name) = HeaderName::try_from(h.name) {
|
||||
if let Ok(value) = HeaderValue::try_from(h.value) {
|
||||
headers.append(name, value);
|
||||
} else {
|
||||
return Err(ParseError::Header.into());
|
||||
}
|
||||
} else {
|
||||
return Err(ParseError::Header.into());
|
||||
}
|
||||
let name =
|
||||
HeaderName::try_from(h.name).map_err(|_| ParseError::Header)?;
|
||||
let value = HeaderValue::try_from(h.value)
|
||||
.map_err(|_| ParseError::Header)?;
|
||||
headers.append(name, value);
|
||||
}
|
||||
|
||||
Ok(Some(headers))
|
||||
}
|
||||
Ok(httparse::Status::Partial) => Err(ParseError::Header.into()),
|
||||
@ -466,17 +463,19 @@ impl Stream for Field {
|
||||
type Item = Result<Bytes, MultipartError>;
|
||||
|
||||
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
if self.safety.current() {
|
||||
let mut inner = self.inner.borrow_mut();
|
||||
if let Some(mut payload) = inner.payload.as_ref().unwrap().get_mut(&self.safety) {
|
||||
payload.poll_stream(cx)?;
|
||||
}
|
||||
inner.poll(&self.safety)
|
||||
} else if !self.safety.is_clean() {
|
||||
Poll::Ready(Some(Err(MultipartError::NotConsumed)))
|
||||
let this = self.get_mut();
|
||||
let mut inner = this.inner.borrow_mut();
|
||||
if let Some(mut buffer) = inner.payload.as_ref().unwrap().get_mut(&this.safety) {
|
||||
// check safety and poll read payload to buffer.
|
||||
buffer.poll_stream(cx)?;
|
||||
} else if !this.safety.is_clean() {
|
||||
// safety violation
|
||||
return Poll::Ready(Some(Err(MultipartError::NotConsumed)));
|
||||
} else {
|
||||
Poll::Pending
|
||||
return Poll::Pending;
|
||||
}
|
||||
|
||||
inner.poll(&this.safety)
|
||||
}
|
||||
}
|
||||
|
||||
@ -690,10 +689,7 @@ impl PayloadRef {
|
||||
}
|
||||
}
|
||||
|
||||
fn get_mut<'a, 'b>(&'a self, s: &'b Safety) -> Option<RefMut<'a, PayloadBuffer>>
|
||||
where
|
||||
'a: 'b,
|
||||
{
|
||||
fn get_mut(&self, s: &Safety) -> Option<RefMut<'_, PayloadBuffer>> {
|
||||
if s.current() {
|
||||
Some(self.payload.borrow_mut())
|
||||
} else {
|
||||
@ -710,8 +706,11 @@ impl Clone for PayloadRef {
|
||||
}
|
||||
}
|
||||
|
||||
/// Counter. It tracks of number of clones of payloads and give access to payload only to top most
|
||||
/// task panics if Safety get destroyed and it not top most task.
|
||||
/// Counter. It tracks of number of clones of payloads and give access to payload only to top most.
|
||||
/// * When dropped, parent task is awakened. This is to support the case where Field is
|
||||
/// dropped in a separate task than Multipart.
|
||||
/// * Assumes that parent owners don't move to different tasks; only the top-most is allowed to.
|
||||
/// * If dropped and is not top most owner, is_clean flag is set to false.
|
||||
#[derive(Debug)]
|
||||
struct Safety {
|
||||
task: LocalWaker,
|
||||
@ -754,9 +753,9 @@ impl Safety {
|
||||
|
||||
impl Drop for Safety {
|
||||
fn drop(&mut self) {
|
||||
// parent task is dead
|
||||
if Rc::strong_count(&self.payload) != self.level {
|
||||
self.clean.set(true);
|
||||
// Multipart dropped leaving a Field
|
||||
self.clean.set(false);
|
||||
}
|
||||
|
||||
self.task.wake();
|
||||
@ -779,7 +778,7 @@ impl PayloadBuffer {
|
||||
PayloadBuffer {
|
||||
eof: false,
|
||||
buf: BytesMut::new(),
|
||||
stream: stream.boxed_local(),
|
||||
stream: Box::pin(stream),
|
||||
}
|
||||
}
|
||||
|
||||
@ -857,10 +856,12 @@ mod tests {
|
||||
|
||||
use actix_http::h1::Payload;
|
||||
use actix_web::http::header::{DispositionParam, DispositionType};
|
||||
use actix_web::rt;
|
||||
use actix_web::test::TestRequest;
|
||||
use actix_web::FromRequest;
|
||||
use bytes::Bytes;
|
||||
use futures_util::future::lazy;
|
||||
use futures_util::{future::lazy, StreamExt};
|
||||
use std::time::Duration;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio_stream::wrappers::UnboundedReceiverStream;
|
||||
|
||||
@ -1290,4 +1291,44 @@ mod tests {
|
||||
MultipartError::NoContentDisposition,
|
||||
));
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_drop_multipart_dont_hang() {
|
||||
let (sender, payload) = create_stream();
|
||||
let (bytes, headers) = create_simple_request_with_header();
|
||||
sender.send(Ok(bytes)).unwrap();
|
||||
drop(sender); // eof
|
||||
|
||||
let mut multipart = Multipart::new(&headers, payload);
|
||||
let mut field = multipart.next().await.unwrap().unwrap();
|
||||
|
||||
drop(multipart);
|
||||
|
||||
// should fail immediately
|
||||
match field.next().await {
|
||||
Some(Err(MultipartError::NotConsumed)) => {}
|
||||
_ => panic!(),
|
||||
};
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_drop_field_awaken_multipart() {
|
||||
let (sender, payload) = create_stream();
|
||||
let (bytes, headers) = create_simple_request_with_header();
|
||||
sender.send(Ok(bytes)).unwrap();
|
||||
drop(sender); // eof
|
||||
|
||||
let mut multipart = Multipart::new(&headers, payload);
|
||||
let mut field = multipart.next().await.unwrap().unwrap();
|
||||
|
||||
let task = rt::spawn(async move {
|
||||
rt::time::sleep(Duration::from_secs(1)).await;
|
||||
assert_eq!(field.next().await.unwrap().unwrap(), "test");
|
||||
drop(field);
|
||||
});
|
||||
|
||||
// dropping field should awaken current task
|
||||
let _ = multipart.next().await.unwrap().unwrap();
|
||||
task.await.unwrap();
|
||||
}
|
||||
}
|
||||
|
@ -1770,6 +1770,12 @@ mod tests {
|
||||
match_methods_agree!(["/v{v}", "/ver/{v}"] => "", "s/v", "/v1", "/v1/xx", "/ver/i3/5", "/ver/1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn duplicate_segment_name() {
|
||||
ResourceDef::new("/user/{id}/post/{id}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn invalid_dynamic_segment_delimiter() {
|
||||
|
@ -29,7 +29,7 @@ openssl = ["tls-openssl", "actix-http/openssl", "awc/openssl"]
|
||||
|
||||
[dependencies]
|
||||
actix-codec = "0.4.1"
|
||||
actix-http = "3.0.0-beta.13"
|
||||
actix-http = "3.0.0-beta.14"
|
||||
actix-http-test = "3.0.0-beta.7"
|
||||
actix-service = "2.0.0"
|
||||
actix-utils = "3.0.0"
|
||||
|
@ -16,7 +16,7 @@ path = "src/lib.rs"
|
||||
[dependencies]
|
||||
actix = { version = "0.12.0", default-features = false }
|
||||
actix-codec = "0.4.1"
|
||||
actix-http = "3.0.0-beta.13"
|
||||
actix-http = "3.0.0-beta.14"
|
||||
actix-web = { version = "4.0.0-beta.11", default-features = false }
|
||||
|
||||
bytes = "1"
|
||||
|
@ -3,7 +3,14 @@
|
||||
## Unreleased - 2021-xx-xx
|
||||
|
||||
|
||||
## 3.0.0-beta.12 - 2021-11-30
|
||||
* Update `actix-tls` to `3.0.0-rc.1`. [#2474]
|
||||
|
||||
[#2474]: https://github.com/actix/actix-web/pull/2474
|
||||
|
||||
|
||||
## 3.0.0-beta.11 - 2021-11-22
|
||||
* No significant changes from `3.0.0-beta.10`.
|
||||
|
||||
|
||||
## 3.0.0-beta.10 - 2021-11-15
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "awc"
|
||||
version = "3.0.0-beta.11"
|
||||
version = "3.0.0-beta.12"
|
||||
authors = [
|
||||
"Nikolay Kim <fafhrd91@gmail.com>",
|
||||
"fakeshadow <24548779@qq.com>",
|
||||
@ -60,9 +60,9 @@ dangerous-h2c = []
|
||||
[dependencies]
|
||||
actix-codec = "0.4.1"
|
||||
actix-service = "2.0.0"
|
||||
actix-http = "3.0.0-beta.13"
|
||||
actix-http = "3.0.0-beta.14"
|
||||
actix-rt = { version = "2.1", default-features = false }
|
||||
actix-tls = { version = "3.0.0-beta.9", features = ["connect"] }
|
||||
actix-tls = { version = "3.0.0-rc.1", features = ["connect", "uri"] }
|
||||
actix-utils = "3.0.0"
|
||||
|
||||
ahash = "0.7"
|
||||
@ -94,11 +94,11 @@ trust-dns-resolver = { version = "0.20.0", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
actix-web = { version = "4.0.0-beta.11", features = ["openssl"] }
|
||||
actix-http = { version = "3.0.0-beta.13", features = ["openssl"] }
|
||||
actix-http = { version = "3.0.0-beta.14", features = ["openssl"] }
|
||||
actix-http-test = { version = "3.0.0-beta.7", features = ["openssl"] }
|
||||
actix-utils = "3.0.0"
|
||||
actix-server = "2.0.0-beta.9"
|
||||
actix-tls = { version = "3.0.0-beta.9", features = ["openssl", "rustls"] }
|
||||
actix-tls = { version = "3.0.0-rc.1", features = ["openssl", "rustls"] }
|
||||
actix-test = { version = "0.1.0-beta.7", features = ["openssl", "rustls"] }
|
||||
|
||||
brotli2 = "0.3.2"
|
||||
|
@ -3,9 +3,9 @@
|
||||
> Async HTTP and WebSocket client library.
|
||||
|
||||
[](https://crates.io/crates/awc)
|
||||
[](https://docs.rs/awc/3.0.0-beta.11)
|
||||
[](https://docs.rs/awc/3.0.0-beta.12)
|
||||

|
||||
[](https://deps.rs/crate/awc/3.0.0-beta.11)
|
||||
[](https://deps.rs/crate/awc/3.0.0-beta.12)
|
||||
[](https://discord.gg/NWpN5mmg3x)
|
||||
|
||||
## Documentation & Resources
|
||||
|
@ -1,18 +1,16 @@
|
||||
use std::convert::TryFrom;
|
||||
use std::fmt;
|
||||
use std::net::IpAddr;
|
||||
use std::rc::Rc;
|
||||
use std::time::Duration;
|
||||
use std::{convert::TryFrom, fmt, net::IpAddr, rc::Rc, time::Duration};
|
||||
|
||||
use actix_http::http::{self, header, Error as HttpError, HeaderMap, HeaderName, Uri};
|
||||
use actix_rt::net::{ActixStream, TcpStream};
|
||||
use actix_service::{boxed, Service};
|
||||
|
||||
use crate::client::{Connector, ConnectorService, TcpConnect, TcpConnectError, TcpConnection};
|
||||
use crate::connect::DefaultConnector;
|
||||
use crate::error::SendRequestError;
|
||||
use crate::middleware::{NestTransform, Redirect, Transform};
|
||||
use crate::{Client, ClientConfig, ConnectRequest, ConnectResponse};
|
||||
use crate::{
|
||||
client::{ConnectInfo, Connector, ConnectorService, TcpConnectError, TcpConnection},
|
||||
connect::DefaultConnector,
|
||||
error::SendRequestError,
|
||||
middleware::{NestTransform, Redirect, Transform},
|
||||
Client, ClientConfig, ConnectRequest, ConnectResponse,
|
||||
};
|
||||
|
||||
/// An HTTP Client builder
|
||||
///
|
||||
@ -35,7 +33,7 @@ impl ClientBuilder {
|
||||
#[allow(clippy::new_ret_no_self)]
|
||||
pub fn new() -> ClientBuilder<
|
||||
impl Service<
|
||||
TcpConnect<Uri>,
|
||||
ConnectInfo<Uri>,
|
||||
Response = TcpConnection<Uri, TcpStream>,
|
||||
Error = TcpConnectError,
|
||||
> + Clone,
|
||||
@ -58,7 +56,7 @@ impl ClientBuilder {
|
||||
|
||||
impl<S, Io, M> ClientBuilder<S, M>
|
||||
where
|
||||
S: Service<TcpConnect<Uri>, Response = TcpConnection<Uri, Io>, Error = TcpConnectError>
|
||||
S: Service<ConnectInfo<Uri>, Response = TcpConnection<Uri, Io>, Error = TcpConnectError>
|
||||
+ Clone
|
||||
+ 'static,
|
||||
Io: ActixStream + fmt::Debug + 'static,
|
||||
@ -67,7 +65,7 @@ where
|
||||
pub fn connector<S1, Io1>(self, connector: Connector<S1>) -> ClientBuilder<S1, M>
|
||||
where
|
||||
S1: Service<
|
||||
TcpConnect<Uri>,
|
||||
ConnectInfo<Uri>,
|
||||
Response = TcpConnection<Uri, Io1>,
|
||||
Error = TcpConnectError,
|
||||
> + Clone
|
||||
|
@ -15,8 +15,8 @@ use actix_rt::{
|
||||
};
|
||||
use actix_service::Service;
|
||||
use actix_tls::connect::{
|
||||
new_connector, Connect as TcpConnect, ConnectError as TcpConnectError,
|
||||
Connection as TcpConnection, Resolver,
|
||||
ConnectError as TcpConnectError, ConnectInfo, Connection as TcpConnection,
|
||||
Connector as TcpConnector, Resolver,
|
||||
};
|
||||
use futures_core::{future::LocalBoxFuture, ready};
|
||||
use http::Uri;
|
||||
@ -28,13 +28,15 @@ use super::error::ConnectError;
|
||||
use super::pool::ConnectionPool;
|
||||
use super::Connect;
|
||||
|
||||
enum SslConnector {
|
||||
#[allow(dead_code)]
|
||||
enum OurTlsConnector {
|
||||
#[allow(dead_code)] // only dead when no TLS feature is enabled
|
||||
None,
|
||||
|
||||
#[cfg(feature = "openssl")]
|
||||
Openssl(actix_tls::connect::ssl::openssl::SslConnector),
|
||||
Openssl(actix_tls::connect::openssl::reexports::SslConnector),
|
||||
|
||||
#[cfg(feature = "rustls")]
|
||||
Rustls(std::sync::Arc<actix_tls::connect::ssl::rustls::ClientConfig>),
|
||||
Rustls(std::sync::Arc<actix_tls::connect::rustls::reexports::ClientConfig>),
|
||||
}
|
||||
|
||||
/// Manages HTTP client network connectivity.
|
||||
@ -53,21 +55,22 @@ enum SslConnector {
|
||||
pub struct Connector<T> {
|
||||
connector: T,
|
||||
config: ConnectorConfig,
|
||||
#[allow(dead_code)]
|
||||
ssl: SslConnector,
|
||||
|
||||
#[allow(dead_code)] // only dead when no TLS feature is enabled
|
||||
ssl: OurTlsConnector,
|
||||
}
|
||||
|
||||
impl Connector<()> {
|
||||
#[allow(clippy::new_ret_no_self, clippy::let_unit_value)]
|
||||
pub fn new() -> Connector<
|
||||
impl Service<
|
||||
TcpConnect<Uri>,
|
||||
ConnectInfo<Uri>,
|
||||
Response = TcpConnection<Uri, TcpStream>,
|
||||
Error = actix_tls::connect::ConnectError,
|
||||
> + Clone,
|
||||
> {
|
||||
Connector {
|
||||
connector: new_connector(resolver::resolver()),
|
||||
connector: TcpConnector::new(resolver::resolver()).service(),
|
||||
config: ConnectorConfig::default(),
|
||||
ssl: Self::build_ssl(vec![b"h2".to_vec(), b"http/1.1".to_vec()]),
|
||||
}
|
||||
@ -75,16 +78,16 @@ impl Connector<()> {
|
||||
|
||||
/// Provides an empty TLS connector when no TLS feature is enabled.
|
||||
#[cfg(not(any(feature = "openssl", feature = "rustls")))]
|
||||
fn build_ssl(_: Vec<Vec<u8>>) -> SslConnector {
|
||||
SslConnector::None
|
||||
fn build_ssl(_: Vec<Vec<u8>>) -> OurTlsConnector {
|
||||
OurTlsConnector::None
|
||||
}
|
||||
|
||||
/// Build TLS connector with rustls, based on supplied ALPN protocols
|
||||
///
|
||||
/// Note that if both `openssl` and `rustls` features are enabled, rustls will be used.
|
||||
#[cfg(feature = "rustls")]
|
||||
fn build_ssl(protocols: Vec<Vec<u8>>) -> SslConnector {
|
||||
use actix_tls::connect::tls::rustls::{webpki_roots_cert_store, ClientConfig};
|
||||
fn build_ssl(protocols: Vec<Vec<u8>>) -> OurTlsConnector {
|
||||
use actix_tls::connect::rustls::{reexports::ClientConfig, webpki_roots_cert_store};
|
||||
|
||||
let mut config = ClientConfig::builder()
|
||||
.with_safe_defaults()
|
||||
@ -93,13 +96,13 @@ impl Connector<()> {
|
||||
|
||||
config.alpn_protocols = protocols;
|
||||
|
||||
SslConnector::Rustls(std::sync::Arc::new(config))
|
||||
OurTlsConnector::Rustls(std::sync::Arc::new(config))
|
||||
}
|
||||
|
||||
/// Build TLS connector with openssl, based on supplied ALPN protocols
|
||||
#[cfg(all(feature = "openssl", not(feature = "rustls")))]
|
||||
fn build_ssl(protocols: Vec<Vec<u8>>) -> SslConnector {
|
||||
use actix_tls::connect::tls::openssl::{SslConnector as OpensslConnector, SslMethod};
|
||||
fn build_ssl(protocols: Vec<Vec<u8>>) -> OurTlsConnector {
|
||||
use actix_tls::connect::openssl::reexports::{SslConnector, SslMethod};
|
||||
use bytes::{BufMut, BytesMut};
|
||||
|
||||
let mut alpn = BytesMut::with_capacity(20);
|
||||
@ -108,12 +111,12 @@ impl Connector<()> {
|
||||
alpn.put(proto.as_slice());
|
||||
}
|
||||
|
||||
let mut ssl = OpensslConnector::builder(SslMethod::tls()).unwrap();
|
||||
let mut ssl = SslConnector::builder(SslMethod::tls()).unwrap();
|
||||
if let Err(err) = ssl.set_alpn_protos(&alpn) {
|
||||
log::error!("Can not set ALPN protocol: {:?}", err);
|
||||
}
|
||||
|
||||
SslConnector::Openssl(ssl.build())
|
||||
OurTlsConnector::Openssl(ssl.build())
|
||||
}
|
||||
}
|
||||
|
||||
@ -123,7 +126,7 @@ impl<S> Connector<S> {
|
||||
where
|
||||
Io1: ActixStream + fmt::Debug + 'static,
|
||||
S1: Service<
|
||||
TcpConnect<Uri>,
|
||||
ConnectInfo<Uri>,
|
||||
Response = TcpConnection<Uri, Io1>,
|
||||
Error = TcpConnectError,
|
||||
> + Clone,
|
||||
@ -136,7 +139,7 @@ impl<S> Connector<S> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, Io> Connector<S>
|
||||
impl<S, IO> Connector<S>
|
||||
where
|
||||
// Note:
|
||||
// Input Io type is bound to ActixStream trait but internally in client module they
|
||||
@ -145,8 +148,8 @@ where
|
||||
//
|
||||
// This remap is to hide ActixStream's trait methods. They are not meant to be called
|
||||
// from user code.
|
||||
Io: ActixStream + fmt::Debug + 'static,
|
||||
S: Service<TcpConnect<Uri>, Response = TcpConnection<Uri, Io>, Error = TcpConnectError>
|
||||
IO: ActixStream + fmt::Debug + 'static,
|
||||
S: Service<ConnectInfo<Uri>, Response = TcpConnection<Uri, IO>, Error = TcpConnectError>
|
||||
+ Clone
|
||||
+ 'static,
|
||||
{
|
||||
@ -166,18 +169,21 @@ where
|
||||
|
||||
#[cfg(feature = "openssl")]
|
||||
/// Use custom `SslConnector` instance.
|
||||
pub fn ssl(mut self, connector: actix_tls::connect::ssl::openssl::SslConnector) -> Self {
|
||||
self.ssl = SslConnector::Openssl(connector);
|
||||
pub fn ssl(
|
||||
mut self,
|
||||
connector: actix_tls::connect::openssl::reexports::SslConnector,
|
||||
) -> Self {
|
||||
self.ssl = OurTlsConnector::Openssl(connector);
|
||||
self
|
||||
}
|
||||
|
||||
#[cfg(feature = "rustls")]
|
||||
/// Use custom `SslConnector` instance.
|
||||
/// Use custom `ClientConfig` instance.
|
||||
pub fn rustls(
|
||||
mut self,
|
||||
connector: std::sync::Arc<actix_tls::connect::ssl::rustls::ClientConfig>,
|
||||
connector: std::sync::Arc<actix_tls::connect::rustls::reexports::ClientConfig>,
|
||||
) -> Self {
|
||||
self.ssl = SslConnector::Rustls(connector);
|
||||
self.ssl = OurTlsConnector::Rustls(connector);
|
||||
self
|
||||
}
|
||||
|
||||
@ -266,7 +272,7 @@ where
|
||||
/// Finish configuration process and create connector service.
|
||||
/// The Connector builder always concludes by calling `finish()` last in
|
||||
/// its combinator chain.
|
||||
pub fn finish(self) -> ConnectorService<S, Io> {
|
||||
pub fn finish(self) -> ConnectorService<S, IO> {
|
||||
let local_address = self.config.local_address;
|
||||
let timeout = self.config.timeout;
|
||||
|
||||
@ -279,19 +285,18 @@ where
|
||||
};
|
||||
|
||||
let tls_service = match self.ssl {
|
||||
SslConnector::None => {
|
||||
OurTlsConnector::None => {
|
||||
#[cfg(not(feature = "dangerous-h2c"))]
|
||||
{
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(feature = "dangerous-h2c")]
|
||||
{
|
||||
use std::{
|
||||
future::{ready, Ready},
|
||||
io,
|
||||
};
|
||||
use std::io;
|
||||
|
||||
use actix_tls::connect::Connection;
|
||||
use actix_utils::future::{ready, Ready};
|
||||
|
||||
impl IntoConnectionIo for TcpConnection<Uri, Box<dyn ConnectionIo>> {
|
||||
fn into_connection_io(self) -> (Box<dyn ConnectionIo>, Protocol) {
|
||||
@ -307,17 +312,17 @@ where
|
||||
#[derive(Clone)]
|
||||
struct NoOpTlsConnectorService;
|
||||
|
||||
impl<T, U> Service<Connection<T, U>> for NoOpTlsConnectorService
|
||||
impl<R, IO> Service<Connection<R, IO>> for NoOpTlsConnectorService
|
||||
where
|
||||
U: ActixStream + 'static,
|
||||
IO: ActixStream + 'static,
|
||||
{
|
||||
type Response = Connection<T, Box<dyn ConnectionIo>>;
|
||||
type Response = Connection<R, Box<dyn ConnectionIo>>;
|
||||
type Error = io::Error;
|
||||
type Future = Ready<Result<Self::Response, Self::Error>>;
|
||||
|
||||
actix_service::always_ready!();
|
||||
|
||||
fn call(&self, connection: Connection<T, U>) -> Self::Future {
|
||||
fn call(&self, connection: Connection<R, IO>) -> Self::Future {
|
||||
let (io, connection) = connection.replace_io(());
|
||||
let (_, connection) = connection.replace_io(Box::new(io) as _);
|
||||
|
||||
@ -336,13 +341,14 @@ where
|
||||
Some(actix_service::boxed::rc_service(tls_service))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "openssl")]
|
||||
SslConnector::Openssl(tls) => {
|
||||
OurTlsConnector::Openssl(tls) => {
|
||||
const H2: &[u8] = b"h2";
|
||||
|
||||
use actix_tls::connect::ssl::openssl::{OpensslConnector, SslStream};
|
||||
use actix_tls::connect::openssl::{reexports::AsyncSslStream, TlsConnector};
|
||||
|
||||
impl<Io: ConnectionIo> IntoConnectionIo for TcpConnection<Uri, SslStream<Io>> {
|
||||
impl<IO: ConnectionIo> IntoConnectionIo for TcpConnection<Uri, AsyncSslStream<IO>> {
|
||||
fn into_connection_io(self) -> (Box<dyn ConnectionIo>, Protocol) {
|
||||
let sock = self.into_parts().0;
|
||||
let h2 = sock
|
||||
@ -361,19 +367,20 @@ where
|
||||
|
||||
let tls_service = TlsConnectorService {
|
||||
tcp_service: tcp_service_inner,
|
||||
tls_service: OpensslConnector::service(tls),
|
||||
tls_service: TlsConnector::service(tls),
|
||||
timeout: handshake_timeout,
|
||||
};
|
||||
|
||||
Some(actix_service::boxed::rc_service(tls_service))
|
||||
}
|
||||
|
||||
#[cfg(feature = "rustls")]
|
||||
SslConnector::Rustls(tls) => {
|
||||
OurTlsConnector::Rustls(tls) => {
|
||||
const H2: &[u8] = b"h2";
|
||||
|
||||
use actix_tls::connect::ssl::rustls::{RustlsConnector, TlsStream};
|
||||
use actix_tls::connect::rustls::{reexports::AsyncTlsStream, TlsConnector};
|
||||
|
||||
impl<Io: ConnectionIo> IntoConnectionIo for TcpConnection<Uri, TlsStream<Io>> {
|
||||
impl<Io: ConnectionIo> IntoConnectionIo for TcpConnection<Uri, AsyncTlsStream<Io>> {
|
||||
fn into_connection_io(self) -> (Box<dyn ConnectionIo>, Protocol) {
|
||||
let sock = self.into_parts().0;
|
||||
let h2 = sock
|
||||
@ -393,7 +400,7 @@ where
|
||||
|
||||
let tls_service = TlsConnectorService {
|
||||
tcp_service: tcp_service_inner,
|
||||
tls_service: RustlsConnector::service(tls),
|
||||
tls_service: TlsConnector::service(tls),
|
||||
timeout: handshake_timeout,
|
||||
};
|
||||
|
||||
@ -462,26 +469,28 @@ where
|
||||
|
||||
/// service for establish tcp connection and do client tls handshake.
|
||||
/// operation is canceled when timeout limit reached.
|
||||
struct TlsConnectorService<S, St> {
|
||||
/// tcp connection is canceled on `TcpConnectorInnerService`'s timeout setting.
|
||||
tcp_service: S,
|
||||
/// tls connection is canceled on `TlsConnectorService`'s timeout setting.
|
||||
tls_service: St,
|
||||
struct TlsConnectorService<Tcp, Tls> {
|
||||
/// TCP connection is canceled on `TcpConnectorInnerService`'s timeout setting.
|
||||
tcp_service: Tcp,
|
||||
|
||||
/// TLS connection is canceled on `TlsConnectorService`'s timeout setting.
|
||||
tls_service: Tls,
|
||||
|
||||
timeout: Duration,
|
||||
}
|
||||
|
||||
impl<S, St, Io> Service<Connect> for TlsConnectorService<S, St>
|
||||
impl<Tcp, Tls, IO> Service<Connect> for TlsConnectorService<Tcp, Tls>
|
||||
where
|
||||
S: Service<Connect, Response = TcpConnection<Uri, Io>, Error = ConnectError>
|
||||
Tcp: Service<Connect, Response = TcpConnection<Uri, IO>, Error = ConnectError>
|
||||
+ Clone
|
||||
+ 'static,
|
||||
St: Service<TcpConnection<Uri, Io>, Error = std::io::Error> + Clone + 'static,
|
||||
Io: ConnectionIo,
|
||||
St::Response: IntoConnectionIo,
|
||||
Tls: Service<TcpConnection<Uri, IO>, Error = std::io::Error> + Clone + 'static,
|
||||
Tls::Response: IntoConnectionIo,
|
||||
IO: ConnectionIo,
|
||||
{
|
||||
type Response = (Box<dyn ConnectionIo>, Protocol);
|
||||
type Error = ConnectError;
|
||||
type Future = TlsConnectorFuture<St, S::Future, St::Future>;
|
||||
type Future = TlsConnectorFuture<Tls, Tcp::Future, Tls::Future>;
|
||||
|
||||
fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
ready!(self.tcp_service.poll_ready(cx))?;
|
||||
@ -581,7 +590,7 @@ impl<S: Clone> TcpConnectorInnerService<S> {
|
||||
|
||||
impl<S, Io> Service<Connect> for TcpConnectorInnerService<S>
|
||||
where
|
||||
S: Service<TcpConnect<Uri>, Response = TcpConnection<Uri, Io>, Error = TcpConnectError>
|
||||
S: Service<ConnectInfo<Uri>, Response = TcpConnection<Uri, Io>, Error = TcpConnectError>
|
||||
+ Clone
|
||||
+ 'static,
|
||||
{
|
||||
@ -592,7 +601,7 @@ where
|
||||
actix_service::forward_ready!(service);
|
||||
|
||||
fn call(&self, req: Connect) -> Self::Future {
|
||||
let mut req = TcpConnect::new(req.uri).set_addr(req.addr);
|
||||
let mut req = ConnectInfo::new(req.uri).set_addr(req.addr);
|
||||
|
||||
if let Some(local_addr) = self.local_address {
|
||||
req = req.set_local_addr(local_addr);
|
||||
@ -631,8 +640,8 @@ where
|
||||
}
|
||||
|
||||
/// Connector service for pooled Plain/Tls Tcp connections.
|
||||
pub type ConnectorService<S, Io> = ConnectorServicePriv<
|
||||
TcpConnectorService<TcpConnectorInnerService<S>>,
|
||||
pub type ConnectorService<Svc, IO> = ConnectorServicePriv<
|
||||
TcpConnectorService<TcpConnectorInnerService<Svc>>,
|
||||
Rc<
|
||||
dyn Service<
|
||||
Connect,
|
||||
@ -644,7 +653,7 @@ pub type ConnectorService<S, Io> = ConnectorServicePriv<
|
||||
>,
|
||||
>,
|
||||
>,
|
||||
Io,
|
||||
IO,
|
||||
Box<dyn ConnectionIo>,
|
||||
>;
|
||||
|
||||
@ -743,7 +752,7 @@ mod resolver {
|
||||
use super::*;
|
||||
|
||||
pub(super) fn resolver() -> Resolver {
|
||||
Resolver::Default
|
||||
Resolver::default()
|
||||
}
|
||||
}
|
||||
|
||||
@ -785,8 +794,7 @@ mod resolver {
|
||||
}
|
||||
}
|
||||
|
||||
// dns struct is cached in thread local.
|
||||
// so new client constructor can reuse the existing dns resolver.
|
||||
// resolver struct is cached in thread local so new clients can reuse the existing instance
|
||||
thread_local! {
|
||||
static TRUST_DNS_RESOLVER: RefCell<Option<Resolver>> = RefCell::new(None);
|
||||
}
|
||||
@ -794,8 +802,10 @@ mod resolver {
|
||||
// get from thread local or construct a new trust-dns resolver.
|
||||
TRUST_DNS_RESOLVER.with(|local| {
|
||||
let resolver = local.borrow().as_ref().map(Clone::clone);
|
||||
|
||||
match resolver {
|
||||
Some(resolver) => resolver,
|
||||
|
||||
None => {
|
||||
let (cfg, opts) = match read_system_conf() {
|
||||
Ok((cfg, opts)) => (cfg, opts),
|
||||
@ -808,8 +818,9 @@ mod resolver {
|
||||
let resolver = TokioAsyncResolver::tokio(cfg, opts).unwrap();
|
||||
|
||||
// box trust dns resolver and put it in thread local.
|
||||
let resolver = Resolver::new_custom(TrustDnsResolver(resolver));
|
||||
let resolver = Resolver::custom(TrustDnsResolver(resolver));
|
||||
*local.borrow_mut() = Some(resolver.clone());
|
||||
|
||||
resolver
|
||||
}
|
||||
}
|
||||
@ -840,9 +851,9 @@ mod tests {
|
||||
.await;
|
||||
|
||||
let connector = Connector {
|
||||
connector: new_connector(resolver::resolver()),
|
||||
connector: TcpConnector::new(resolver::resolver()).service(),
|
||||
config: ConnectorConfig::default(),
|
||||
ssl: SslConnector::None,
|
||||
ssl: OurTlsConnector::None,
|
||||
};
|
||||
|
||||
let client = Client::builder().connector(connector).finish();
|
||||
|
@ -7,7 +7,7 @@ use actix_http::{
|
||||
http::Error as HttpError,
|
||||
};
|
||||
#[cfg(feature = "openssl")]
|
||||
use actix_tls::accept::openssl::SslError;
|
||||
use actix_tls::accept::openssl::reexports::Error as OpenSslError;
|
||||
|
||||
/// A set of errors that can occur while connecting to an HTTP host
|
||||
#[derive(Debug, Display, From)]
|
||||
@ -20,7 +20,7 @@ pub enum ConnectError {
|
||||
/// SSL error
|
||||
#[cfg(feature = "openssl")]
|
||||
#[display(fmt = "{}", _0)]
|
||||
SslError(SslError),
|
||||
SslError(OpenSslError),
|
||||
|
||||
/// Failed to resolve the hostname
|
||||
#[display(fmt = "Failed resolving hostname: {}", _0)]
|
||||
|
@ -11,7 +11,7 @@ mod h2proto;
|
||||
mod pool;
|
||||
|
||||
pub use actix_tls::connect::{
|
||||
Connect as TcpConnect, ConnectError as TcpConnectError, Connection as TcpConnection,
|
||||
ConnectError as TcpConnectError, ConnectInfo, Connection as TcpConnection,
|
||||
};
|
||||
|
||||
pub use self::connection::{Connection, ConnectionIo};
|
||||
|
@ -137,7 +137,7 @@ use actix_http::{
|
||||
use actix_rt::net::TcpStream;
|
||||
use actix_service::Service;
|
||||
|
||||
use self::client::{TcpConnect, TcpConnectError, TcpConnection};
|
||||
use self::client::{ConnectInfo, TcpConnectError, TcpConnection};
|
||||
|
||||
/// An asynchronous HTTP and WebSocket client.
|
||||
///
|
||||
@ -186,7 +186,7 @@ impl Client {
|
||||
/// This function is equivalent of `ClientBuilder::new()`.
|
||||
pub fn builder() -> ClientBuilder<
|
||||
impl Service<
|
||||
TcpConnect<Uri>,
|
||||
ConnectInfo<Uri>,
|
||||
Response = TcpConnection<Uri, TcpStream>,
|
||||
Error = TcpConnectError,
|
||||
> + Clone,
|
||||
|
@ -127,7 +127,7 @@ async fn test_timeout() {
|
||||
});
|
||||
|
||||
let connector = awc::Connector::new()
|
||||
.connector(actix_tls::connect::default_connector())
|
||||
.connector(actix_tls::connect::ConnectorService::default())
|
||||
.timeout(Duration::from_secs(15));
|
||||
|
||||
let client = awc::Client::builder()
|
||||
|
@ -14,7 +14,7 @@ use std::{
|
||||
use actix_http::HttpService;
|
||||
use actix_http_test::test_server;
|
||||
use actix_service::{fn_service, map_config, ServiceFactoryExt};
|
||||
use actix_tls::connect::tls::rustls::webpki_roots_cert_store;
|
||||
use actix_tls::connect::rustls::webpki_roots_cert_store;
|
||||
use actix_utils::future::ok;
|
||||
use actix_web::{dev::AppConfig, http::Version, web, App, HttpResponse};
|
||||
use rustls::{
|
||||
|
111
scripts/bump
Executable file
111
scripts/bump
Executable file
@ -0,0 +1,111 @@
|
||||
#!/bin/sh
|
||||
|
||||
# developed on macOS and probably doesn't work on Linux yet due to minor
|
||||
# differences in flags on sed
|
||||
|
||||
# requires github cli tool for automatic release draft creation
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
DIR=$1
|
||||
|
||||
LINUX=""
|
||||
MACOS=""
|
||||
|
||||
if [ "$(uname)" = "Darwin" ]; then
|
||||
MACOS="1"
|
||||
fi
|
||||
|
||||
CARGO_MANIFEST=$DIR/Cargo.toml
|
||||
CHANGELOG_FILE=$DIR/CHANGES.md
|
||||
README_FILE=$DIR/README.md
|
||||
|
||||
# get current version
|
||||
PACKAGE_NAME="$(sed -nE 's/^name ?= ?"([^"]+)"$/\1/ p' "$CARGO_MANIFEST" | head -n 1)"
|
||||
CURRENT_VERSION="$(sed -nE 's/^version ?= ?"([^"]+)"$/\1/ p' "$CARGO_MANIFEST")"
|
||||
|
||||
CHANGE_CHUNK_FILE="$(mktemp)"
|
||||
echo saving changelog to $CHANGE_CHUNK_FILE
|
||||
echo
|
||||
|
||||
# get changelog chunk and save to temp file
|
||||
cat "$CHANGELOG_FILE" |
|
||||
# skip up to unreleased heading
|
||||
sed '1,/Unreleased/ d' |
|
||||
# take up to previous version heading
|
||||
sed "/$CURRENT_VERSION/ q" |
|
||||
# drop last line
|
||||
sed '$d' \
|
||||
>"$CHANGE_CHUNK_FILE"
|
||||
|
||||
# if word count of changelog chunk is 0 then insert filler changelog chunk
|
||||
if [ "$(wc -w "$CHANGE_CHUNK_FILE" | awk '{ print $1 }')" = "0" ]; then
|
||||
echo "* No significant changes since \`$CURRENT_VERSION\`." >"$CHANGE_CHUNK_FILE"
|
||||
fi
|
||||
|
||||
if [ -n "${2-}" ]; then
|
||||
NEW_VERSION="$2"
|
||||
else
|
||||
echo
|
||||
echo "--- Changes since $CURRENT_VERSION ----"
|
||||
cat "$CHANGE_CHUNK_FILE"
|
||||
echo
|
||||
read -p "Update version to: " NEW_VERSION
|
||||
fi
|
||||
|
||||
DATE="$(date -u +"%Y-%m-%d")"
|
||||
echo "updating from $CURRENT_VERSION => $NEW_VERSION ($DATE)"
|
||||
|
||||
# update package.version field
|
||||
sed -i.bak -E "s/^version ?= ?\"[^\"]+\"$/version = \"$NEW_VERSION\"/" "$CARGO_MANIFEST"
|
||||
|
||||
# update readme
|
||||
[ -f "$README_FILE" ] && sed -i.bak -E "s#$CURRENT_VERSION([/)])#$NEW_VERSION\1#g" "$README_FILE"
|
||||
|
||||
# update changelog file
|
||||
(
|
||||
sed '/Unreleased/ q' "$CHANGELOG_FILE" # up to unreleased heading
|
||||
echo # blank line
|
||||
echo # blank line
|
||||
echo "## $NEW_VERSION - $DATE" # new version heading
|
||||
cat "$CHANGE_CHUNK_FILE" # previously unreleased changes
|
||||
sed "/$CURRENT_VERSION/ q" "$CHANGELOG_FILE" | tail -n 1 # the previous version heading
|
||||
sed "1,/$CURRENT_VERSION/ d" "$CHANGELOG_FILE" # everything after previous version heading
|
||||
) >"$CHANGELOG_FILE.bak"
|
||||
mv "$CHANGELOG_FILE.bak" "$CHANGELOG_FILE"
|
||||
|
||||
# done; remove backup files
|
||||
rm -f $CARGO_MANIFEST.bak
|
||||
rm -f $CHANGELOG_FILE.bak
|
||||
rm -f $README_FILE.bak
|
||||
|
||||
echo "manifest, changelog, and readme updated"
|
||||
echo
|
||||
echo "check other references:"
|
||||
rg "$PACKAGE_NAME =" || true
|
||||
rg "package = \"$PACKAGE_NAME\"" || true
|
||||
|
||||
if [ $MACOS ]; then
|
||||
printf "prepare $PACKAGE_NAME release $NEW_VERSION" | pbcopy
|
||||
else
|
||||
echo
|
||||
echo "commit message:"
|
||||
echo "prepare $PACKAGE_NAME release $NEW_VERSION"
|
||||
fi
|
||||
|
||||
SHORT_PACKAGE_NAME="$(echo $PACKAGE_NAME | sed 's/^actix-web-//' | sed 's/^actix-//')"
|
||||
GIT_TAG="$(echo $SHORT_PACKAGE_NAME-v$NEW_VERSION)"
|
||||
RELEASE_TITLE="$(echo $PACKAGE_NAME: v$NEW_VERSION)"
|
||||
|
||||
echo
|
||||
echo "GitHub release command:"
|
||||
echo "gh release create \"$GIT_TAG\" --draft --title \"$RELEASE_TITLE\" --notes-file \"$CHANGE_CHUNK_FILE\" --prerelease"
|
||||
|
||||
read -p "Submit draft GH release: (y/N) " GH_RELEASE
|
||||
GH_RELEASE="${GH_RELEASE:-n}"
|
||||
|
||||
if [ "$GH_RELEASE" = 'y' ] || [ "$GH_RELEASE" = 'Y' ]; then
|
||||
gh release create "$GIT_TAG" --draft --title "$RELEASE_TITLE" --notes-file "$CHANGE_CHUNK_FILE" --prerelease
|
||||
fi
|
||||
|
||||
echo
|
16
scripts/ci-test.sh
Executable file
16
scripts/ci-test.sh
Executable file
@ -0,0 +1,16 @@
|
||||
#!/bin/sh
|
||||
|
||||
# run tests matching what CI does for non-linux feature sets
|
||||
|
||||
set -x
|
||||
|
||||
cargo test --lib --tests -p=actix-router --all-features
|
||||
cargo test --lib --tests -p=actix-http --all-features
|
||||
cargo test --lib --tests -p=actix-web --features=rustls,openssl -- --skip=test_reading_deflate_encoding_large_random_rustls
|
||||
cargo test --lib --tests -p=actix-web-codegen --all-features
|
||||
cargo test --lib --tests -p=awc --all-features
|
||||
cargo test --lib --tests -p=actix-http-test --all-features
|
||||
cargo test --lib --tests -p=actix-test --all-features
|
||||
cargo test --lib --tests -p=actix-files
|
||||
cargo test --lib --tests -p=actix-multipart --all-features
|
||||
cargo test --lib --tests -p=actix-web-actors --all-features
|
@ -49,7 +49,7 @@ downcast_dyn!(ResponseError);
|
||||
impl ResponseError for Box<dyn StdError + 'static> {}
|
||||
|
||||
#[cfg(feature = "openssl")]
|
||||
impl ResponseError for actix_tls::accept::openssl::SslError {}
|
||||
impl ResponseError for actix_tls::accept::openssl::reexports::Error {}
|
||||
|
||||
impl ResponseError for serde::de::value::Error {
|
||||
fn status_code(&self) -> StatusCode {
|
||||
|
231
src/extract.rs
231
src/extract.rs
@ -10,6 +10,7 @@ use std::{
|
||||
use actix_http::http::{Method, Uri};
|
||||
use actix_utils::future::{ok, Ready};
|
||||
use futures_core::ready;
|
||||
use pin_project_lite::pin_project;
|
||||
|
||||
use crate::{dev::Payload, Error, HttpRequest};
|
||||
|
||||
@ -139,10 +140,11 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
#[pin_project::pin_project]
|
||||
pub struct FromRequestOptFuture<Fut> {
|
||||
#[pin]
|
||||
fut: Fut,
|
||||
pin_project! {
|
||||
pub struct FromRequestOptFuture<Fut> {
|
||||
#[pin]
|
||||
fut: Fut,
|
||||
}
|
||||
}
|
||||
|
||||
impl<Fut, T, E> Future for FromRequestOptFuture<Fut>
|
||||
@ -226,10 +228,11 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
#[pin_project::pin_project]
|
||||
pub struct FromRequestResFuture<Fut> {
|
||||
#[pin]
|
||||
fut: Fut,
|
||||
pin_project! {
|
||||
pub struct FromRequestResFuture<Fut> {
|
||||
#[pin]
|
||||
fut: Fut,
|
||||
}
|
||||
}
|
||||
|
||||
impl<Fut, T, E> Future for FromRequestResFuture<Fut>
|
||||
@ -297,102 +300,104 @@ impl FromRequest for () {
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! tuple_from_req ({$fut_type:ident, $(($n:tt, $T:ident)),+} => {
|
||||
|
||||
// This module is a trick to get around the inability of
|
||||
// `macro_rules!` macros to make new idents. We want to make
|
||||
// a new `FutWrapper` struct for each distinct invocation of
|
||||
// this macro. Ideally, we would name it something like
|
||||
// `FutWrapper_$fut_type`, but this can't be done in a macro_rules
|
||||
// macro.
|
||||
//
|
||||
// Instead, we put everything in a module named `$fut_type`, thus allowing
|
||||
// us to use the name `FutWrapper` without worrying about conflicts.
|
||||
// This macro only exists to generate trait impls for tuples - these
|
||||
// are inherently global, so users don't have to care about this
|
||||
// weird trick.
|
||||
#[allow(non_snake_case)]
|
||||
mod $fut_type {
|
||||
|
||||
// Bring everything into scope, so we don't need
|
||||
// redundant imports
|
||||
use super::*;
|
||||
|
||||
/// A helper struct to allow us to pin-project through
|
||||
/// to individual fields
|
||||
#[pin_project::pin_project]
|
||||
struct FutWrapper<$($T: FromRequest),+>($(#[pin] $T::Future),+);
|
||||
|
||||
/// FromRequest implementation for tuple
|
||||
#[doc(hidden)]
|
||||
#[allow(unused_parens)]
|
||||
impl<$($T: FromRequest + 'static),+> FromRequest for ($($T,)+)
|
||||
{
|
||||
type Error = Error;
|
||||
type Future = $fut_type<$($T),+>;
|
||||
|
||||
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
|
||||
$fut_type {
|
||||
items: <($(Option<$T>,)+)>::default(),
|
||||
futs: FutWrapper($($T::from_request(req, payload),)+),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
#[pin_project::pin_project]
|
||||
pub struct $fut_type<$($T: FromRequest),+> {
|
||||
items: ($(Option<$T>,)+),
|
||||
#[pin]
|
||||
futs: FutWrapper<$($T,)+>,
|
||||
}
|
||||
|
||||
impl<$($T: FromRequest),+> Future for $fut_type<$($T),+>
|
||||
{
|
||||
type Output = Result<($($T,)+), Error>;
|
||||
|
||||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
let mut this = self.project();
|
||||
|
||||
let mut ready = true;
|
||||
$(
|
||||
if this.items.$n.is_none() {
|
||||
match this.futs.as_mut().project().$n.poll(cx) {
|
||||
Poll::Ready(Ok(item)) => {
|
||||
this.items.$n = Some(item);
|
||||
}
|
||||
Poll::Pending => ready = false,
|
||||
Poll::Ready(Err(e)) => return Poll::Ready(Err(e.into())),
|
||||
}
|
||||
}
|
||||
)+
|
||||
|
||||
if ready {
|
||||
Poll::Ready(Ok(
|
||||
($(this.items.$n.take().unwrap(),)+)
|
||||
))
|
||||
} else {
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
#[rustfmt::skip]
|
||||
mod m {
|
||||
#[doc(hidden)]
|
||||
#[allow(non_snake_case)]
|
||||
mod tuple_from_req {
|
||||
use super::*;
|
||||
|
||||
tuple_from_req!(TupleFromRequest1, (0, A));
|
||||
tuple_from_req!(TupleFromRequest2, (0, A), (1, B));
|
||||
tuple_from_req!(TupleFromRequest3, (0, A), (1, B), (2, C));
|
||||
tuple_from_req!(TupleFromRequest4, (0, A), (1, B), (2, C), (3, D));
|
||||
tuple_from_req!(TupleFromRequest5, (0, A), (1, B), (2, C), (3, D), (4, E));
|
||||
tuple_from_req!(TupleFromRequest6, (0, A), (1, B), (2, C), (3, D), (4, E), (5, F));
|
||||
tuple_from_req!(TupleFromRequest7, (0, A), (1, B), (2, C), (3, D), (4, E), (5, F), (6, G));
|
||||
tuple_from_req!(TupleFromRequest8, (0, A), (1, B), (2, C), (3, D), (4, E), (5, F), (6, G), (7, H));
|
||||
tuple_from_req!(TupleFromRequest9, (0, A), (1, B), (2, C), (3, D), (4, E), (5, F), (6, G), (7, H), (8, I));
|
||||
tuple_from_req!(TupleFromRequest10, (0, A), (1, B), (2, C), (3, D), (4, E), (5, F), (6, G), (7, H), (8, I), (9, J));
|
||||
macro_rules! tuple_from_req {
|
||||
($fut: ident; $($T: ident),*) => {
|
||||
/// FromRequest implementation for tuple
|
||||
#[allow(unused_parens)]
|
||||
impl<$($T: FromRequest + 'static),+> FromRequest for ($($T,)+)
|
||||
{
|
||||
type Error = Error;
|
||||
type Future = $fut<$($T),+>;
|
||||
|
||||
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
|
||||
$fut {
|
||||
$(
|
||||
$T: ExtractFuture::Future {
|
||||
fut: $T::from_request(req, payload)
|
||||
},
|
||||
)+
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pin_project! {
|
||||
pub struct $fut<$($T: FromRequest),+> {
|
||||
$(
|
||||
#[pin]
|
||||
$T: ExtractFuture<$T::Future, $T>,
|
||||
)+
|
||||
}
|
||||
}
|
||||
|
||||
impl<$($T: FromRequest),+> Future for $fut<$($T),+>
|
||||
{
|
||||
type Output = Result<($($T,)+), Error>;
|
||||
|
||||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
let mut this = self.project();
|
||||
|
||||
let mut ready = true;
|
||||
$(
|
||||
match this.$T.as_mut().project() {
|
||||
ExtractProj::Future { fut } => match fut.poll(cx) {
|
||||
Poll::Ready(Ok(output)) => {
|
||||
let _ = this.$T.as_mut().project_replace(ExtractFuture::Done { output });
|
||||
},
|
||||
Poll::Ready(Err(e)) => return Poll::Ready(Err(e.into())),
|
||||
Poll::Pending => ready = false,
|
||||
},
|
||||
ExtractProj::Done { .. } => {},
|
||||
ExtractProj::Empty => unreachable!("FromRequest polled after finished"),
|
||||
}
|
||||
)+
|
||||
|
||||
if ready {
|
||||
Poll::Ready(Ok(
|
||||
($(
|
||||
match this.$T.project_replace(ExtractFuture::Empty) {
|
||||
ExtractReplaceProj::Done { output } => output,
|
||||
_ => unreachable!("FromRequest polled after finished"),
|
||||
},
|
||||
)+)
|
||||
))
|
||||
} else {
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
pin_project! {
|
||||
#[project = ExtractProj]
|
||||
#[project_replace = ExtractReplaceProj]
|
||||
enum ExtractFuture<Fut, Res> {
|
||||
Future {
|
||||
#[pin]
|
||||
fut: Fut
|
||||
},
|
||||
Done {
|
||||
output: Res,
|
||||
},
|
||||
Empty
|
||||
}
|
||||
}
|
||||
|
||||
tuple_from_req! { TupleFromRequest1; A }
|
||||
tuple_from_req! { TupleFromRequest2; A, B }
|
||||
tuple_from_req! { TupleFromRequest3; A, B, C }
|
||||
tuple_from_req! { TupleFromRequest4; A, B, C, D }
|
||||
tuple_from_req! { TupleFromRequest5; A, B, C, D, E }
|
||||
tuple_from_req! { TupleFromRequest6; A, B, C, D, E, F }
|
||||
tuple_from_req! { TupleFromRequest7; A, B, C, D, E, F, G }
|
||||
tuple_from_req! { TupleFromRequest8; A, B, C, D, E, F, G, H }
|
||||
tuple_from_req! { TupleFromRequest9; A, B, C, D, E, F, G, H, I }
|
||||
tuple_from_req! { TupleFromRequest10; A, B, C, D, E, F, G, H, I, J }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@ -494,4 +499,26 @@ mod tests {
|
||||
let method = Method::extract(&req).await.unwrap();
|
||||
assert_eq!(method, Method::GET);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_concurrent() {
|
||||
let (req, mut pl) = TestRequest::default()
|
||||
.uri("/foo/bar")
|
||||
.method(Method::GET)
|
||||
.insert_header((header::CONTENT_TYPE, "application/x-www-form-urlencoded"))
|
||||
.insert_header((header::CONTENT_LENGTH, "11"))
|
||||
.set_payload(Bytes::from_static(b"hello=world"))
|
||||
.to_http_parts();
|
||||
let (method, uri, form) = <(Method, Uri, Form<Info>)>::from_request(&req, &mut pl)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(method, Method::GET);
|
||||
assert_eq!(uri.path(), "/foo/bar");
|
||||
assert_eq!(
|
||||
form,
|
||||
Form(Info {
|
||||
hello: "world".into()
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
@ -10,6 +10,7 @@ use std::{
|
||||
use actix_http::body::{AnyBody, MessageBody};
|
||||
use actix_service::{Service, Transform};
|
||||
use futures_core::{future::LocalBoxFuture, ready};
|
||||
use pin_project_lite::pin_project;
|
||||
|
||||
use crate::{error::Error, service::ServiceResponse};
|
||||
|
||||
@ -89,10 +90,11 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
#[pin_project::pin_project]
|
||||
pub struct CompatMiddlewareFuture<Fut> {
|
||||
#[pin]
|
||||
fut: Fut,
|
||||
pin_project! {
|
||||
pub struct CompatMiddlewareFuture<Fut> {
|
||||
#[pin]
|
||||
fut: Fut,
|
||||
}
|
||||
}
|
||||
|
||||
impl<Fut, T, E> Future for CompatMiddlewareFuture<Fut>
|
||||
|
@ -20,7 +20,7 @@ use actix_utils::future::{ok, Either, Ready};
|
||||
use bytes::Bytes;
|
||||
use futures_core::ready;
|
||||
use once_cell::sync::Lazy;
|
||||
use pin_project::pin_project;
|
||||
use pin_project_lite::pin_project;
|
||||
|
||||
use crate::{
|
||||
dev::BodyEncoding,
|
||||
@ -162,15 +162,16 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
#[pin_project]
|
||||
pub struct CompressResponse<S, B>
|
||||
where
|
||||
S: Service<ServiceRequest>,
|
||||
{
|
||||
#[pin]
|
||||
fut: S::Future,
|
||||
encoding: ContentEncoding,
|
||||
_phantom: PhantomData<B>,
|
||||
pin_project! {
|
||||
pub struct CompressResponse<S, B>
|
||||
where
|
||||
S: Service<ServiceRequest>,
|
||||
{
|
||||
#[pin]
|
||||
fut: S::Future,
|
||||
encoding: ContentEncoding,
|
||||
_phantom: PhantomData<B>,
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, B> Future for CompressResponse<S, B>
|
||||
|
@ -11,6 +11,7 @@ use std::{
|
||||
|
||||
use actix_utils::future::{ready, Ready};
|
||||
use futures_core::ready;
|
||||
use pin_project_lite::pin_project;
|
||||
|
||||
use crate::{
|
||||
dev::{Service, Transform},
|
||||
@ -153,12 +154,13 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
#[pin_project::pin_project]
|
||||
pub struct DefaultHeaderFuture<S: Service<ServiceRequest>, B> {
|
||||
#[pin]
|
||||
fut: S::Future,
|
||||
inner: Rc<Inner>,
|
||||
_body: PhantomData<B>,
|
||||
pin_project! {
|
||||
pub struct DefaultHeaderFuture<S: Service<ServiceRequest>, B> {
|
||||
#[pin]
|
||||
fut: S::Future,
|
||||
inner: Rc<Inner>,
|
||||
_body: PhantomData<B>,
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, B> Future for DefaultHeaderFuture<S, B>
|
||||
|
@ -10,6 +10,7 @@ use std::{
|
||||
use actix_service::{Service, Transform};
|
||||
use ahash::AHashMap;
|
||||
use futures_core::{future::LocalBoxFuture, ready};
|
||||
use pin_project_lite::pin_project;
|
||||
|
||||
use crate::{
|
||||
dev::{ServiceRequest, ServiceResponse},
|
||||
@ -130,19 +131,21 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
#[pin_project::pin_project(project = ErrorHandlersProj)]
|
||||
pub enum ErrorHandlersFuture<Fut, B>
|
||||
where
|
||||
Fut: Future,
|
||||
{
|
||||
ServiceFuture {
|
||||
#[pin]
|
||||
fut: Fut,
|
||||
handlers: Handlers<B>,
|
||||
},
|
||||
HandlerFuture {
|
||||
fut: LocalBoxFuture<'static, Fut::Output>,
|
||||
},
|
||||
pin_project! {
|
||||
#[project = ErrorHandlersProj]
|
||||
pub enum ErrorHandlersFuture<Fut, B>
|
||||
where
|
||||
Fut: Future,
|
||||
{
|
||||
ServiceFuture {
|
||||
#[pin]
|
||||
fut: Fut,
|
||||
handlers: Handlers<B>,
|
||||
},
|
||||
HandlerFuture {
|
||||
fut: LocalBoxFuture<'static, Fut::Output>,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
impl<Fut, B> Future for ErrorHandlersFuture<Fut, B>
|
||||
|
@ -13,10 +13,11 @@ use std::{
|
||||
};
|
||||
|
||||
use actix_service::{Service, Transform};
|
||||
use actix_utils::future::{ok, Ready};
|
||||
use actix_utils::future::{ready, Ready};
|
||||
use bytes::Bytes;
|
||||
use futures_core::ready;
|
||||
use log::{debug, warn};
|
||||
use pin_project_lite::pin_project;
|
||||
use regex::{Regex, RegexSet};
|
||||
use time::{format_description::well_known::Rfc3339, OffsetDateTime};
|
||||
|
||||
@ -180,8 +181,8 @@ where
|
||||
{
|
||||
type Response = ServiceResponse<StreamLog<B>>;
|
||||
type Error = Error;
|
||||
type InitError = ();
|
||||
type Transform = LoggerMiddleware<S>;
|
||||
type InitError = ();
|
||||
type Future = Ready<Result<Self::Transform, Self::InitError>>;
|
||||
|
||||
fn new_transform(&self, service: S) -> Self::Future {
|
||||
@ -195,10 +196,10 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
ok(LoggerMiddleware {
|
||||
ready(Ok(LoggerMiddleware {
|
||||
service,
|
||||
inner: self.0.clone(),
|
||||
})
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
@ -246,17 +247,18 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
#[pin_project::pin_project]
|
||||
pub struct LoggerResponse<S, B>
|
||||
where
|
||||
B: MessageBody,
|
||||
S: Service<ServiceRequest>,
|
||||
{
|
||||
#[pin]
|
||||
fut: S::Future,
|
||||
time: OffsetDateTime,
|
||||
format: Option<Format>,
|
||||
_phantom: PhantomData<B>,
|
||||
pin_project! {
|
||||
pub struct LoggerResponse<S, B>
|
||||
where
|
||||
B: MessageBody,
|
||||
S: Service<ServiceRequest>,
|
||||
{
|
||||
#[pin]
|
||||
fut: S::Future,
|
||||
time: OffsetDateTime,
|
||||
format: Option<Format>,
|
||||
_phantom: PhantomData<B>,
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, B> Future for LoggerResponse<S, B>
|
||||
@ -296,28 +298,25 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
use pin_project::{pin_project, pinned_drop};
|
||||
|
||||
#[pin_project(PinnedDrop)]
|
||||
pub struct StreamLog<B> {
|
||||
#[pin]
|
||||
body: B,
|
||||
format: Option<Format>,
|
||||
size: usize,
|
||||
time: OffsetDateTime,
|
||||
}
|
||||
|
||||
#[pinned_drop]
|
||||
impl<B> PinnedDrop for StreamLog<B> {
|
||||
fn drop(self: Pin<&mut Self>) {
|
||||
if let Some(ref format) = self.format {
|
||||
let render = |fmt: &mut fmt::Formatter<'_>| {
|
||||
for unit in &format.0 {
|
||||
unit.render(fmt, self.size, self.time)?;
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
log::info!("{}", FormatDisplay(&render));
|
||||
pin_project! {
|
||||
pub struct StreamLog<B> {
|
||||
#[pin]
|
||||
body: B,
|
||||
format: Option<Format>,
|
||||
size: usize,
|
||||
time: OffsetDateTime,
|
||||
}
|
||||
impl<B> PinnedDrop for StreamLog<B> {
|
||||
fn drop(this: Pin<&mut Self>) {
|
||||
if let Some(ref format) = this.format {
|
||||
let render = |fmt: &mut fmt::Formatter<'_>| {
|
||||
for unit in &format.0 {
|
||||
unit.render(fmt, this.size, this.time)?;
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
log::info!("{}", FormatDisplay(&render));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -296,7 +296,7 @@ impl Future for HttpResponse<AnyBody> {
|
||||
|
||||
#[cfg(feature = "cookies")]
|
||||
pub struct CookieIter<'a> {
|
||||
iter: header::GetAll<'a>,
|
||||
iter: header::map::GetAll<'a>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "cookies")]
|
||||
|
@ -15,9 +15,9 @@ use actix_service::{
|
||||
};
|
||||
|
||||
#[cfg(feature = "openssl")]
|
||||
use actix_tls::accept::openssl::{AlpnError, SslAcceptor, SslAcceptorBuilder};
|
||||
use actix_tls::accept::openssl::reexports::{AlpnError, SslAcceptor, SslAcceptorBuilder};
|
||||
#[cfg(feature = "rustls")]
|
||||
use actix_tls::accept::rustls::ServerConfig as RustlsServerConfig;
|
||||
use actix_tls::accept::rustls::reexports::ServerConfig as RustlsServerConfig;
|
||||
|
||||
use crate::{config::AppConfig, Error};
|
||||
|
||||
@ -108,11 +108,11 @@ where
|
||||
/// [Extensions] container so that request-local data can be passed to middleware and handlers.
|
||||
///
|
||||
/// For example:
|
||||
/// - `actix_tls::openssl::SslStream<actix_web::rt::net::TcpStream>` when using openssl.
|
||||
/// - `actix_tls::rustls::TlsStream<actix_web::rt::net::TcpStream>` when using rustls.
|
||||
/// - `actix_tls::accept::openssl::TlsStream<actix_web::rt::net::TcpStream>` when using openssl.
|
||||
/// - `actix_tls::accept::rustls::TlsStream<actix_web::rt::net::TcpStream>` when using rustls.
|
||||
/// - `actix_web::rt::net::TcpStream` when no encryption is used.
|
||||
///
|
||||
/// See `on_connect` example for additional details.
|
||||
/// See the `on_connect` example for additional details.
|
||||
pub fn on_connect<CB>(self, f: CB) -> HttpServer<F, I, S, B>
|
||||
where
|
||||
CB: Fn(&dyn Any, &mut Extensions) + Send + Sync + 'static,
|
||||
|
@ -9,6 +9,7 @@ use std::{
|
||||
|
||||
use bytes::Bytes;
|
||||
use futures_core::ready;
|
||||
use pin_project_lite::pin_project;
|
||||
|
||||
use crate::{
|
||||
dev,
|
||||
@ -198,37 +199,40 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
#[pin_project::pin_project]
|
||||
pub struct EitherExtractFut<L, R>
|
||||
where
|
||||
R: FromRequest,
|
||||
L: FromRequest,
|
||||
{
|
||||
req: HttpRequest,
|
||||
#[pin]
|
||||
state: EitherExtractState<L, R>,
|
||||
pin_project! {
|
||||
pub struct EitherExtractFut<L, R>
|
||||
where
|
||||
R: FromRequest,
|
||||
L: FromRequest,
|
||||
{
|
||||
req: HttpRequest,
|
||||
#[pin]
|
||||
state: EitherExtractState<L, R>,
|
||||
}
|
||||
}
|
||||
|
||||
#[pin_project::pin_project(project = EitherExtractProj)]
|
||||
pub enum EitherExtractState<L, R>
|
||||
where
|
||||
L: FromRequest,
|
||||
R: FromRequest,
|
||||
{
|
||||
Bytes {
|
||||
#[pin]
|
||||
bytes: <Bytes as FromRequest>::Future,
|
||||
},
|
||||
Left {
|
||||
#[pin]
|
||||
left: L::Future,
|
||||
fallback: Bytes,
|
||||
},
|
||||
Right {
|
||||
#[pin]
|
||||
right: R::Future,
|
||||
left_err: Option<L::Error>,
|
||||
},
|
||||
pin_project! {
|
||||
#[project = EitherExtractProj]
|
||||
pub enum EitherExtractState<L, R>
|
||||
where
|
||||
L: FromRequest,
|
||||
R: FromRequest,
|
||||
{
|
||||
Bytes {
|
||||
#[pin]
|
||||
bytes: <Bytes as FromRequest>::Future,
|
||||
},
|
||||
Left {
|
||||
#[pin]
|
||||
left: L::Future,
|
||||
fallback: Bytes,
|
||||
},
|
||||
Right {
|
||||
#[pin]
|
||||
right: R::Future,
|
||||
left_err: Option<L::Error>,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
impl<R, RF, RE, L, LF, LE> Future for EitherExtractFut<L, R>
|
||||
|
Reference in New Issue
Block a user