1
0
mirror of https://github.com/fafhrd91/actix-web synced 2025-07-05 18:35:22 +02:00

Compare commits

...

26 Commits

Author SHA1 Message Date
48476362a3 update changes 2019-12-20 17:59:34 +06:00
2b4256baab add links to configs 2019-12-20 17:49:05 +06:00
e5a50f423d Make web::Data deref to Arc<T> #1214 2019-12-20 17:45:35 +06:00
8b8a9a995d bump ver 2019-12-20 17:36:48 +06:00
74fa4060c2 fix awc tests 2019-12-20 17:27:32 +06:00
c877840c07 rename App::register_data to App::app_data and HttpRequest::app_data returns Option<&T> instead of Option<&Data<T>> 2019-12-20 17:13:09 +06:00
20248daeda Allow to set peer_addr for TestRequest #1074 2019-12-20 16:11:51 +06:00
a08d8dab70 AppConfig::secure() is always false. #1202 2019-12-20 16:04:51 +06:00
fbbb4a86e9 feat: add access to the session also from immutable references (#1225) 2019-12-20 13:59:07 +06:00
1d12ba9d5f Replace brotli with brotli2 #1224 2019-12-20 13:50:07 +06:00
8c54054844 Use .advance() intead of .split_to() 2019-12-19 09:56:14 +06:00
1732ae8c79 fix Bodyencoding trait usage 2019-12-18 09:30:14 +06:00
3b860ebdc7 Fix poll_ready call for WebSockets upgrade (#1219)
* Fix poll_ready call for WebSockets upgrade

* Poll upgrade service from H1ServiceHandler too
2019-12-17 13:34:25 +06:00
29ac6463e1 Merge branch 'master' of github.com:actix/actix-web 2019-12-16 17:22:49 +06:00
01613f334b Move BodyEncoding to dev module #1220 2019-12-16 17:22:26 +06:00
30dcaf9da0 fix deprecated Error::description (#1218) 2019-12-16 07:43:19 +06:00
b0aa9395da prep actix-web alpha.6 release 2019-12-15 22:51:14 +06:00
a153374b61 migrate actix-web-actors 2019-12-15 22:45:38 +06:00
a791aab418 prep awc release 2019-12-15 13:36:05 +06:00
cb705317b8 compile with default-features off 2019-12-15 13:28:54 +06:00
e8e0f98f96 fix docs.rs features list 2019-12-13 12:41:48 +06:00
c878f66d05 fix docs.rs features list 2019-12-13 12:40:22 +06:00
fac6dec3c9 update deps 2019-12-13 12:36:15 +06:00
232f71b3b5 update changes 2019-12-13 12:18:30 +06:00
8881c13e60 update changes 2019-12-13 12:16:43 +06:00
d006a7b31f update changes 2019-12-13 12:10:45 +06:00
64 changed files with 1061 additions and 748 deletions

View File

@ -1,5 +1,36 @@
# Changes
## [2.0.0-rc] - 2019-12-20
### Changed
* Move `BodyEncoding` to `dev` module #1220
* Allow to set `peer_addr` for TestRequest #1074
* Make web::Data deref to Arc<T> #1214
* Rename `App::register_data()` to `App::app_data()`
* `HttpRequest::app_data<T>()` returns `Option<&T>` instead of `Option<&Data<T>>`
### Fixed
* Fix `AppConfig::secure()` is always false. #1202
## [2.0.0-alpha.6] - 2019-12-15
### Fixed
* Fixed compilation with default features off
## [2.0.0-alpha.5] - 2019-12-13
### Added
* Add test server, `test::start()` and `test::start_with()`
## [2.0.0-alpha.4] - 2019-12-08
### Deleted

View File

@ -1,6 +1,6 @@
[package]
name = "actix-web"
version = "2.0.0-alpha.4"
version = "2.0.0-rc"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix web is a simple, pragmatic and extremely fast web framework for Rust."
readme = "README.md"
@ -12,11 +12,10 @@ categories = ["network-programming", "asynchronous",
"web-programming::http-server",
"web-programming::websocket"]
license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
edition = "2018"
[package.metadata.docs.rs]
features = ["openssl", "compress", "secure-cookies", "client"]
features = ["openssl", "rustls", "compress", "secure-cookies"]
[badges]
travis-ci = { repository = "actix/actix-web", branch = "master" }
@ -71,11 +70,11 @@ actix-macros = "0.1.0"
actix-threadpool = "0.3.0"
actix-tls = "1.0.0"
actix-web-codegen = "0.2.0-alpha.2"
actix-web-codegen = "0.2.0"
actix-http = "1.0.0"
awc = { version = "1.0.0", default-features = false }
awc = { version = "1.0.1", default-features = false }
bytes = "0.5.2"
bytes = "0.5.3"
derive_more = "0.99.2"
encoding_rs = "0.8"
futures = "0.3.1"
@ -94,11 +93,11 @@ open-ssl = { version="0.10", package = "openssl", optional = true }
rust-tls = { version = "0.16.0", package = "rustls", optional = true }
[dev-dependencies]
# actix = "0.8.3"
actix = "0.9.0-alpha.2"
rand = "0.7"
env_logger = "0.6"
serde_derive = "1.0"
brotli = "3.3.0"
brotli2 = "0.3.2"
flate2 = "1.0.13"
[profile.release]

View File

@ -1,5 +1,10 @@
## 2.0.0
* `App::register_data()` renamed to `App::app_data()` and accepts any type `T: 'static`.
Stored data is available via `HttpRequest::app_data()` method at runtime.
* Extractor configuration must be registered with `App::app_data()` instead of `App::data()`
* Sync handlers has been removed. `.to_async()` method has been renamed to `.to()`
replace `fn` with `async fn` to convert sync handler to async

View File

@ -1,5 +1,9 @@
# Changes
## [0.2.0] - 2019-12-20
* Release
## [0.2.0-alpha.3] - 2019-12-07
* Migrate to actix-web 2.0.0

View File

@ -1,6 +1,6 @@
[package]
name = "actix-cors"
version = "0.2.0-alpha.3"
version = "0.2.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Cross-origin resource sharing (CORS) for Actix applications."
readme = "README.md"
@ -17,7 +17,7 @@ name = "actix_cors"
path = "src/lib.rs"
[dependencies]
actix-web = "2.0.0-alpha.3"
actix-web = "2.0.0-rc"
actix-service = "1.0.0"
derive_more = "0.99.2"
futures = "0.3.1"

View File

@ -1,6 +1,10 @@
# Changes
## [0.2.0-alpha.7] - 2019-12-07
## [0.2.0] - 2019-12-20
* Fix BodyEncoding trait import #1220
## [0.2.0-alpha.1] - 2019-12-07
* Migrate to `std::future`

View File

@ -1,6 +1,6 @@
[package]
name = "actix-files"
version = "0.2.0-alpha.3"
version = "0.2.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Static files support for actix web."
readme = "README.md"
@ -18,11 +18,11 @@ name = "actix_files"
path = "src/lib.rs"
[dependencies]
actix-web = { version = "2.0.0-alpha.3", default-features = false }
actix-http = "1.0.0-alpha.3"
actix-web = { version = "2.0.0-rc", default-features = false }
actix-http = "1.0.1"
actix-service = "1.0.0"
bitflags = "1"
bytes = "0.5.2"
bytes = "0.5.3"
futures = "0.3.1"
derive_more = "0.99.2"
log = "0.4"
@ -33,4 +33,4 @@ v_htmlescape = "0.4"
[dev-dependencies]
actix-rt = "1.0.0"
actix-web = { version = "2.0.0-alpha.3", features=["openssl"] }
actix-web = { version = "2.0.0-rc", features=["openssl"] }

View File

@ -12,11 +12,11 @@ use mime;
use mime_guess::from_path;
use actix_http::body::SizedStream;
use actix_web::dev::BodyEncoding;
use actix_web::http::header::{
self, Charset, ContentDisposition, DispositionParam, DispositionType, ExtendedValue,
};
use actix_web::http::{ContentEncoding, StatusCode};
use actix_web::middleware::BodyEncoding;
use actix_web::{Error, HttpMessage, HttpRequest, HttpResponse, Responder};
use futures::future::{ready, Ready};

View File

@ -1,6 +1,6 @@
[package]
name = "actix-framed"
version = "0.3.0-alpha.1"
version = "0.3.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix framed app server"
readme = "README.md"
@ -24,9 +24,9 @@ actix-codec = "0.2.0"
actix-service = "1.0.0"
actix-router = "0.2.0"
actix-rt = "1.0.0"
actix-http = "1.0.0-alpha.3"
actix-http = "1.0.0"
bytes = "0.5.2"
bytes = "0.5.3"
futures = "0.3.1"
pin-project = "0.4.6"
log = "0.4"
@ -34,5 +34,5 @@ log = "0.4"
[dev-dependencies]
actix-server = "1.0.0"
actix-connect = { version = "1.0.0", features=["openssl"] }
actix-http-test = { version = "1.0.0-alpha.3", features=["openssl"] }
actix-utils = "1.0.0"
actix-http-test = { version = "1.0.0", features=["openssl"] }
actix-utils = "1.0.3"

View File

@ -1,5 +1,13 @@
# Changes
## [1.0.1] - 2019-12-20
### Fixed
* Poll upgrade service's readiness from HTTP service handlers
* Replace brotli with brotli2 #1224
## [1.0.0] - 2019-12-13
### Added

View File

@ -1,6 +1,6 @@
[package]
name = "actix-http"
version = "1.0.0"
version = "1.0.1"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix http primitives"
readme = "README.md"
@ -15,7 +15,7 @@ license = "MIT/Apache-2.0"
edition = "2018"
[package.metadata.docs.rs]
features = ["openssl", "rustls", "fail", "compress", "secure-cookies"]
features = ["openssl", "rustls", "failure", "compress", "secure-cookies"]
[lib]
name = "actix_http"
@ -31,7 +31,7 @@ openssl = ["actix-tls/openssl", "actix-connect/openssl"]
rustls = ["actix-tls/rustls", "actix-connect/rustls"]
# enable compressison support
compress = ["flate2", "brotli"]
compress = ["flate2", "brotli2"]
# failure integration. actix does not use failure anymore
failure = ["fail-ure"]
@ -42,7 +42,7 @@ secure-cookies = ["ring"]
[dependencies]
actix-service = "1.0.0"
actix-codec = "0.2.0"
actix-connect = "1.0.0"
actix-connect = "1.0.1"
actix-utils = "1.0.3"
actix-rt = "1.0.0"
actix-threadpool = "0.3.1"
@ -83,7 +83,7 @@ time = "0.1.42"
ring = { version = "0.16.9", optional = true }
# compression
brotli = { version = "3.3.0", optional = true }
brotli2 = { version="0.3.2", optional = true }
flate2 = { version = "1.0.13", optional = true }
# optional deps
@ -92,7 +92,7 @@ fail-ure = { version = "0.1.5", package="failure", optional = true }
[dev-dependencies]
actix-server = "1.0.0"
actix-connect = { version = "1.0.0", features=["openssl"] }
actix-http-test = { version = "1.0.0-alpha.3", features=["openssl"] }
actix-http-test = { version = "1.0.0", features=["openssl"] }
actix-tls = { version = "1.0.0", features=["openssl"] }
futures = "0.3.1"
env_logger = "0.6"

View File

@ -51,11 +51,7 @@ impl From<Utf8Error> for ParseError {
}
}
impl Error for ParseError {
fn description(&self) -> &str {
self.as_str()
}
}
impl Error for ParseError {}
fn indexes_of(needle: &str, haystack: &str) -> Option<(usize, usize)> {
let haystack_start = haystack.as_ptr() as usize;

View File

@ -4,7 +4,7 @@ use std::pin::Pin;
use std::task::{Context, Poll};
use actix_threadpool::{run, CpuFuture};
use brotli::DecompressorWriter;
use brotli2::write::BrotliDecoder;
use bytes::Bytes;
use flate2::write::{GzDecoder, ZlibDecoder};
use futures_core::{ready, Stream};
@ -31,7 +31,7 @@ where
pub fn new(stream: S, encoding: ContentEncoding) -> Decoder<S> {
let decoder = match encoding {
ContentEncoding::Br => Some(ContentDecoder::Br(Box::new(
DecompressorWriter::new(Writer::new(), 0),
BrotliDecoder::new(Writer::new()),
))),
ContentEncoding::Deflate => Some(ContentDecoder::Deflate(Box::new(
ZlibDecoder::new(Writer::new()),
@ -137,7 +137,7 @@ where
enum ContentDecoder {
Deflate(Box<ZlibDecoder<Writer>>),
Gzip(Box<GzDecoder<Writer>>),
Br(Box<DecompressorWriter<Writer>>),
Br(Box<BrotliDecoder<Writer>>),
}
impl ContentDecoder {

View File

@ -5,7 +5,7 @@ use std::pin::Pin;
use std::task::{Context, Poll};
use actix_threadpool::{run, CpuFuture};
use brotli::CompressorWriter;
use brotli2::write::BrotliEncoder;
use bytes::Bytes;
use flate2::write::{GzEncoder, ZlibEncoder};
use futures_core::ready;
@ -17,7 +17,7 @@ use crate::{Error, ResponseHead};
use super::Writer;
const INPLACE: usize = 2049;
const INPLACE: usize = 1024;
pub struct Encoder<B> {
eof: bool,
@ -174,7 +174,7 @@ fn update_head(encoding: ContentEncoding, head: &mut ResponseHead) {
enum ContentEncoder {
Deflate(ZlibEncoder<Writer>),
Gzip(GzEncoder<Writer>),
Br(Box<CompressorWriter<Writer>>),
Br(BrotliEncoder<Writer>),
}
impl ContentEncoder {
@ -188,9 +188,9 @@ impl ContentEncoder {
Writer::new(),
flate2::Compression::fast(),
))),
ContentEncoding::Br => Some(ContentEncoder::Br(Box::new(
CompressorWriter::new(Writer::new(), 0, 3, 0),
))),
ContentEncoding::Br => {
Some(ContentEncoder::Br(BrotliEncoder::new(Writer::new(), 3)))
}
_ => None,
}
}
@ -198,12 +198,7 @@ impl ContentEncoder {
#[inline]
pub(crate) fn take(&mut self) -> Bytes {
match *self {
ContentEncoder::Br(ref mut encoder) => {
let mut encoder_new =
Box::new(CompressorWriter::new(Writer::new(), 0, 3, 0));
std::mem::swap(encoder, &mut encoder_new);
encoder_new.into_inner().freeze()
}
ContentEncoder::Br(ref mut encoder) => encoder.get_mut().take(),
ContentEncoder::Deflate(ref mut encoder) => encoder.get_mut().take(),
ContentEncoder::Gzip(ref mut encoder) => encoder.get_mut().take(),
}
@ -211,7 +206,10 @@ impl ContentEncoder {
fn finish(self) -> Result<Bytes, io::Error> {
match self {
ContentEncoder::Br(encoder) => Ok(encoder.into_inner().buf.freeze()),
ContentEncoder::Br(encoder) => match encoder.finish() {
Ok(writer) => Ok(writer.buf.freeze()),
Err(err) => Err(err),
},
ContentEncoder::Gzip(encoder) => match encoder.finish() {
Ok(writer) => Ok(writer.buf.freeze()),
Err(err) => Err(err),

View File

@ -19,12 +19,10 @@ impl Writer {
buf: BytesMut::with_capacity(8192),
}
}
fn take(&mut self) -> Bytes {
self.buf.split().freeze()
}
fn freeze(self) -> Bytes {
self.buf.freeze()
}
}
impl io::Write for Writer {
@ -32,6 +30,7 @@ impl io::Write for Writer {
self.buf.extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}

View File

@ -6,7 +6,9 @@ use std::str::Utf8Error;
use std::string::FromUtf8Error;
use std::{fmt, io, result};
use actix_codec::{Decoder, Encoder};
pub use actix_threadpool::BlockingError;
use actix_utils::framed::DispatcherError as FramedDispatcherError;
use actix_utils::timeout::TimeoutError;
use bytes::BytesMut;
use derive_more::{Display, From};
@ -114,10 +116,6 @@ impl fmt::Debug for Error {
}
impl std::error::Error for Error {
fn description(&self) -> &str {
"actix-http::Error"
}
fn cause(&self) -> Option<&dyn std::error::Error> {
None
}
@ -467,6 +465,14 @@ impl ResponseError for ContentTypeError {
}
}
impl<E, U: Encoder + Decoder> ResponseError for FramedDispatcherError<E, U>
where
E: fmt::Debug + fmt::Display,
<U as Encoder>::Error: fmt::Debug,
<U as Decoder>::Error: fmt::Debug,
{
}
/// Helper type that can wrap any error and generate custom response.
///
/// In following example any `io::Error` will be converted into "BAD REQUEST"
@ -966,7 +972,6 @@ mod tests {
use super::*;
use http::{Error as HttpError, StatusCode};
use httparse;
use std::error::Error as StdError;
use std::io;
#[test]
@ -995,7 +1000,7 @@ mod tests {
#[test]
fn test_error_cause() {
let orig = io::Error::new(io::ErrorKind::Other, "other");
let desc = orig.description().to_owned();
let desc = orig.to_string();
let e = Error::from(orig);
assert_eq!(format!("{}", e.as_response_error()), desc);
}
@ -1003,7 +1008,7 @@ mod tests {
#[test]
fn test_error_display() {
let orig = io::Error::new(io::ErrorKind::Other, "other");
let desc = orig.description().to_owned();
let desc = orig.to_string();
let e = Error::from(orig);
assert_eq!(format!("{}", e), desc);
}
@ -1045,7 +1050,7 @@ mod tests {
match ParseError::from($from) {
e @ $error => {
let desc = format!("{}", e);
assert_eq!(desc, format!("IO error: {}", $from.description()));
assert_eq!(desc, format!("IO error: {}", $from));
}
_ => unreachable!("{:?}", $from),
}

View File

@ -5,7 +5,7 @@ use std::mem::MaybeUninit;
use std::task::Poll;
use actix_codec::Decoder;
use bytes::{Bytes, BytesMut};
use bytes::{Buf, Bytes, BytesMut};
use http::header::{HeaderName, HeaderValue};
use http::{header, Method, StatusCode, Uri, Version};
use httparse;
@ -477,7 +477,7 @@ macro_rules! byte (
($rdr:ident) => ({
if $rdr.len() > 0 {
let b = $rdr[0];
let _ = $rdr.split_to(1);
$rdr.advance(1);
b
} else {
return Poll::Pending

View File

@ -8,7 +8,7 @@ use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed, FramedParts};
use actix_rt::time::{delay_until, Delay, Instant};
use actix_service::Service;
use bitflags::bitflags;
use bytes::BytesMut;
use bytes::{Buf, BytesMut};
use log::{error, trace};
use crate::body::{Body, BodySize, MessageBody, ResponseBody};
@ -66,7 +66,6 @@ where
U::Error: fmt::Display,
{
Normal(InnerDispatcher<T, S, B, X, U>),
UpgradeReadiness(InnerDispatcher<T, S, B, X, U>, Request),
Upgrade(U::Future),
None,
}
@ -313,7 +312,7 @@ where
}
Poll::Pending => {
if written > 0 {
let _ = self.write_buf.split_to(written);
self.write_buf.advance(written);
}
return Ok(true);
}
@ -323,7 +322,7 @@ where
if written == self.write_buf.len() {
unsafe { self.write_buf.set_len(0) }
} else {
let _ = self.write_buf.split_to(written);
self.write_buf.advance(written);
}
Ok(false)
}
@ -764,8 +763,16 @@ where
if let DispatcherState::Normal(inner) =
std::mem::replace(&mut self.inner, DispatcherState::None)
{
self.inner =
DispatcherState::UpgradeReadiness(inner, req);
let mut parts = FramedParts::with_read_buf(
inner.io,
inner.codec,
inner.read_buf,
);
parts.write_buf = inner.write_buf;
let framed = Framed::from_parts(parts);
self.inner = DispatcherState::Upgrade(
inner.upgrade.unwrap().call((req, framed)),
);
return self.poll(cx);
} else {
panic!()
@ -815,35 +822,6 @@ where
}
}
}
DispatcherState::UpgradeReadiness(ref mut inner, _) => {
let upgrade = inner.upgrade.as_mut().unwrap();
match upgrade.poll_ready(cx) {
Poll::Ready(Ok(_)) => {
if let DispatcherState::UpgradeReadiness(inner, req) =
std::mem::replace(&mut self.inner, DispatcherState::None)
{
let mut parts = FramedParts::with_read_buf(
inner.io,
inner.codec,
inner.read_buf,
);
parts.write_buf = inner.write_buf;
let framed = Framed::from_parts(parts);
self.inner = DispatcherState::Upgrade(
inner.upgrade.unwrap().call((req, framed)),
);
self.poll(cx)
} else {
panic!()
}
}
Poll::Pending => Poll::Pending,
Poll::Ready(Err(e)) => {
error!("Upgrade handler readiness check error: {}", e);
Poll::Ready(Err(DispatchError::Upgrade))
}
}
}
DispatcherState::Upgrade(ref mut fut) => {
unsafe { Pin::new_unchecked(fut) }.poll(cx).map_err(|e| {
error!("Upgrade handler error: {}", e);

View File

@ -72,7 +72,7 @@ where
Request = (Request, Framed<TcpStream, Codec>),
Response = (),
>,
U::Error: fmt::Display,
U::Error: fmt::Display + Into<Error>,
U::InitError: fmt::Debug,
{
/// Create simple tcp stream service
@ -115,7 +115,7 @@ mod openssl {
Request = (Request, Framed<SslStream<TcpStream>, Codec>),
Response = (),
>,
U::Error: fmt::Display,
U::Error: fmt::Display + Into<Error>,
U::InitError: fmt::Debug,
{
/// Create openssl based service
@ -165,7 +165,7 @@ mod rustls {
Request = (Request, Framed<TlsStream<TcpStream>, Codec>),
Response = (),
>,
U::Error: fmt::Display,
U::Error: fmt::Display + Into<Error>,
U::InitError: fmt::Debug,
{
/// Create rustls based service
@ -255,7 +255,7 @@ where
X::Error: Into<Error>,
X::InitError: fmt::Debug,
U: ServiceFactory<Config = (), Request = (Request, Framed<T, Codec>), Response = ()>,
U::Error: fmt::Display,
U::Error: fmt::Display + Into<Error>,
U::InitError: fmt::Debug,
{
type Config = ();
@ -412,7 +412,7 @@ where
X: Service<Request = Request, Response = Request>,
X::Error: Into<Error>,
U: Service<Request = (Request, Framed<T, Codec>), Response = ()>,
U::Error: fmt::Display,
U::Error: fmt::Display + Into<Error>,
{
type Request = (T, Option<net::SocketAddr>);
type Response = ();
@ -441,6 +441,19 @@ where
.is_ready()
&& ready;
let ready = if let Some(ref mut upg) = self.upgrade {
upg.poll_ready(cx)
.map_err(|e| {
let e = e.into();
log::error!("Http service readiness error: {:?}", e);
DispatchError::Service(e)
})?
.is_ready()
&& ready
} else {
ready
};
if ready {
Poll::Ready(Ok(()))
} else {

View File

@ -169,7 +169,7 @@ where
Request = (Request, Framed<TcpStream, h1::Codec>),
Response = (),
>,
U::Error: fmt::Display,
U::Error: fmt::Display + Into<Error>,
U::InitError: fmt::Debug,
<U::Service as Service>::Future: 'static,
{
@ -214,7 +214,7 @@ mod openssl {
Request = (Request, Framed<SslStream<TcpStream>, h1::Codec>),
Response = (),
>,
U::Error: fmt::Display,
U::Error: fmt::Display + Into<Error>,
U::InitError: fmt::Debug,
<U::Service as Service>::Future: 'static,
{
@ -276,7 +276,7 @@ mod rustls {
Request = (Request, Framed<TlsStream<TcpStream>, h1::Codec>),
Response = (),
>,
U::Error: fmt::Display,
U::Error: fmt::Display + Into<Error>,
U::InitError: fmt::Debug,
<U::Service as Service>::Future: 'static,
{
@ -335,7 +335,7 @@ where
Request = (Request, Framed<T, h1::Codec>),
Response = (),
>,
U::Error: fmt::Display,
U::Error: fmt::Display + Into<Error>,
U::InitError: fmt::Debug,
<U::Service as Service>::Future: 'static,
{
@ -493,7 +493,7 @@ where
X: Service<Request = Request, Response = Request>,
X::Error: Into<Error>,
U: Service<Request = (Request, Framed<T, h1::Codec>), Response = ()>,
U::Error: fmt::Display,
U::Error: fmt::Display + Into<Error>,
{
type Request = (T, Protocol, Option<net::SocketAddr>);
type Response = ();
@ -522,6 +522,19 @@ where
.is_ready()
&& ready;
let ready = if let Some(ref mut upg) = self.upgrade {
upg.poll_ready(cx)
.map_err(|e| {
let e = e.into();
log::error!("Http service readiness error: {:?}", e);
DispatchError::Service(e)
})?
.is_ready()
&& ready
} else {
ready
};
if ready {
Poll::Ready(Ok(()))
} else {

View File

@ -1,6 +1,6 @@
use std::convert::TryFrom;
use bytes::{BufMut, BytesMut};
use bytes::{Buf, BufMut, BytesMut};
use log::debug;
use rand;
@ -108,7 +108,7 @@ impl Parser {
}
// remove prefix
let _ = src.split_to(idx);
src.advance(idx);
// no need for body
if length == 0 {

View File

@ -1,24 +1,70 @@
use std::cell::Cell;
use std::marker::PhantomData;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use actix_codec::{AsyncRead, AsyncWrite, Framed};
use actix_http::{body, h1, ws, Error, HttpService, Request, Response};
use actix_http_test::test_server;
use actix_service::{fn_factory, Service};
use actix_utils::framed::Dispatcher;
use bytes::Bytes;
use futures::future;
use futures::{SinkExt, StreamExt};
use futures::task::{Context, Poll};
use futures::{Future, SinkExt, StreamExt};
async fn ws_service<T: AsyncRead + AsyncWrite + Unpin>(
(req, mut framed): (Request, Framed<T, h1::Codec>),
) -> Result<(), Error> {
let res = ws::handshake(req.head()).unwrap().message_body(());
struct WsService<T>(Arc<Mutex<(PhantomData<T>, Cell<bool>)>>);
framed
.send((res, body::BodySize::None).into())
.await
.unwrap();
impl<T> WsService<T> {
fn new() -> Self {
WsService(Arc::new(Mutex::new((PhantomData, Cell::new(false)))))
}
Dispatcher::new(framed.into_framed(ws::Codec::new()), service)
.await
.map_err(|_| panic!())
fn set_polled(&mut self) {
*self.0.lock().unwrap().1.get_mut() = true;
}
fn was_polled(&self) -> bool {
self.0.lock().unwrap().1.get()
}
}
impl<T> Clone for WsService<T> {
fn clone(&self) -> Self {
WsService(self.0.clone())
}
}
impl<T> Service for WsService<T>
where
T: AsyncRead + AsyncWrite + Unpin + 'static,
{
type Request = (Request, Framed<T, h1::Codec>);
type Response = ();
type Error = Error;
type Future = Pin<Box<dyn Future<Output = Result<(), Error>>>>;
fn poll_ready(&mut self, _ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.set_polled();
Poll::Ready(Ok(()))
}
fn call(&mut self, (req, mut framed): Self::Request) -> Self::Future {
let fut = async move {
let res = ws::handshake(req.head()).unwrap().message_body(());
framed
.send((res, body::BodySize::None).into())
.await
.unwrap();
Dispatcher::new(framed.into_framed(ws::Codec::new()), service)
.await
.map_err(|_| panic!())
};
Box::pin(fut)
}
}
async fn service(msg: ws::Frame) -> Result<ws::Message, Error> {
@ -37,11 +83,16 @@ async fn service(msg: ws::Frame) -> Result<ws::Message, Error> {
#[actix_rt::test]
async fn test_simple() {
let mut srv = test_server(|| {
HttpService::build()
.upgrade(actix_service::fn_service(ws_service))
.finish(|_| future::ok::<_, ()>(Response::NotFound()))
.tcp()
let ws_service = WsService::new();
let mut srv = test_server({
let ws_service = ws_service.clone();
move || {
let ws_service = ws_service.clone();
HttpService::build()
.upgrade(fn_factory(move || future::ok::<_, ()>(ws_service.clone())))
.finish(|_| future::ok::<_, ()>(Response::NotFound()))
.tcp()
}
});
// client service
@ -138,4 +189,6 @@ async fn test_simple() {
item.unwrap().unwrap(),
ws::Frame::Close(Some(ws::CloseCode::Normal.into()))
);
assert!(ws_service.was_polled());
}

View File

@ -1,5 +1,9 @@
# Changes
## [0.2.0] - 2019-12-20
* Use actix-web 2.0
## [0.1.0] - 2019-06-xx
* Move identity middleware to separate crate

View File

@ -1,6 +1,6 @@
[package]
name = "actix-identity"
version = "0.2.0-alpha.3"
version = "0.2.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Identity service for actix web framework."
readme = "README.md"
@ -17,7 +17,7 @@ name = "actix_identity"
path = "src/lib.rs"
[dependencies]
actix-web = { version = "2.0.0-alpha.3", default-features = false, features = ["secure-cookies"] }
actix-web = { version = "2.0.0-rc", default-features = false, features = ["secure-cookies"] }
actix-service = "1.0.0"
futures = "0.3.1"
serde = "1.0"
@ -26,5 +26,5 @@ time = "0.1.42"
[dev-dependencies]
actix-rt = "1.0.0"
actix-http = "1.0.0-alpha.3"
bytes = "0.5.2"
actix-http = "1.0.1"
bytes = "0.5.3"

View File

@ -1,6 +1,10 @@
# Changes
## [2.0.0-alpha.4] - 2019-12-xx
## [0.2.0] - 2019-12-20
* Release
## [0.2.0-alpha.4] - 2019-12-xx
* Multipart handling now handles Pending during read of boundary #1205

View File

@ -1,6 +1,6 @@
[package]
name = "actix-multipart"
version = "0.2.0-alpha.3"
version = "0.2.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Multipart support for actix web framework."
readme = "README.md"
@ -9,8 +9,6 @@ homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-web.git"
documentation = "https://docs.rs/actix-multipart/"
license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
workspace = ".."
edition = "2018"
[lib]
@ -18,10 +16,10 @@ name = "actix_multipart"
path = "src/lib.rs"
[dependencies]
actix-web = { version = "2.0.0-alpha.3", default-features = false }
actix-web = { version = "2.0.0-rc", default-features = false }
actix-service = "1.0.0"
actix-utils = "1.0.0"
bytes = "0.5.2"
actix-utils = "1.0.3"
bytes = "0.5.3"
derive_more = "0.99.2"
httparse = "1.3"
futures = "0.3.1"
@ -32,4 +30,4 @@ twoway = "0.2"
[dev-dependencies]
actix-rt = "1.0.0"
actix-http = "1.0.0-alpha.3"
actix-http = "1.0.0"

View File

@ -1,5 +1,13 @@
# Changes
## [0.3.0] - 2019-12-20
* Release
## [0.3.0-alpha.4] - 2019-12-xx
* Allow access to sessions also from not mutable references to the request
## [0.3.0-alpha.3] - 2019-12-xx
* Add access to the session from RequestHead for use of session from guard methods

View File

@ -1,6 +1,6 @@
[package]
name = "actix-session"
version = "0.3.0-alpha.3"
version = "0.3.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Session for actix web framework."
readme = "README.md"
@ -9,8 +9,6 @@ homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-web.git"
documentation = "https://docs.rs/actix-session/"
license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
workspace = ".."
edition = "2018"
[lib]
@ -24,9 +22,9 @@ default = ["cookie-session"]
cookie-session = ["actix-web/secure-cookies"]
[dependencies]
actix-web = "2.0.0-alpha.3"
actix-web = "2.0.0-rc"
actix-service = "1.0.0"
bytes = "0.5.2"
bytes = "0.5.3"
derive_more = "0.99.2"
futures = "0.3.1"
serde = "1.0"

View File

@ -85,23 +85,23 @@ pub struct Session(Rc<RefCell<SessionInner>>);
/// Helper trait that allows to get session
pub trait UserSession {
fn get_session(&mut self) -> Session;
fn get_session(&self) -> Session;
}
impl UserSession for HttpRequest {
fn get_session(&mut self) -> Session {
fn get_session(&self) -> Session {
Session::get_session(&mut *self.extensions_mut())
}
}
impl UserSession for ServiceRequest {
fn get_session(&mut self) -> Session {
fn get_session(&self) -> Session {
Session::get_session(&mut *self.extensions_mut())
}
}
impl UserSession for RequestHead {
fn get_session(&mut self) -> Session {
fn get_session(&self) -> Session {
Session::get_session(&mut *self.extensions_mut())
}
}

View File

@ -1,5 +1,13 @@
# Changes
## [2.0.0] - 2019-12-20
* Release
## [2.0.0-alpha.1] - 2019-12-15
* Migrate to actix-web 2.0.0
## [1.0.4] - 2019-12-07
* Allow comma-separated websocket subprotocols without spaces (#1172)

View File

@ -1,6 +1,6 @@
[package]
name = "actix-web-actors"
version = "1.0.4"
version = "2.0.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix actors support for actix web framework."
readme = "README.md"
@ -9,8 +9,6 @@ homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-web.git"
documentation = "https://docs.rs/actix-web-actors/"
license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
workspace = ".."
edition = "2018"
[lib]
@ -18,13 +16,14 @@ name = "actix_web_actors"
path = "src/lib.rs"
[dependencies]
actix = "0.8.3"
actix-web = "1.0.9"
actix-http = "0.2.11"
actix-codec = "0.1.2"
bytes = "0.4"
futures = "0.1.25"
actix = "0.9.0"
actix-web = "2.0.0-rc"
actix-http = "1.0.1"
actix-codec = "0.2.0"
bytes = "0.5.2"
futures = "0.3.1"
pin-project = "0.4.6"
[dev-dependencies]
actix-rt = "1.0.0"
env_logger = "0.6"
actix-http-test = { version = "0.2.4", features=["ssl"] }

View File

@ -1,4 +1,6 @@
use std::collections::VecDeque;
use std::pin::Pin;
use std::task::{Context, Poll};
use actix::dev::{
AsyncContextParts, ContextFut, ContextParts, Envelope, Mailbox, ToEnvelope,
@ -7,10 +9,10 @@ use actix::fut::ActorFuture;
use actix::{
Actor, ActorContext, ActorState, Addr, AsyncContext, Handler, Message, SpawnHandle,
};
use actix_web::error::{Error, ErrorInternalServerError};
use actix_web::error::Error;
use bytes::Bytes;
use futures::sync::oneshot::Sender;
use futures::{Async, Future, Poll, Stream};
use futures::channel::oneshot::Sender;
use futures::{Future, Stream};
/// Execution context for http actors
pub struct HttpContext<A>
@ -43,7 +45,7 @@ where
#[inline]
fn spawn<F>(&mut self, fut: F) -> SpawnHandle
where
F: ActorFuture<Item = (), Error = (), Actor = A> + 'static,
F: ActorFuture<Output = (), Actor = A> + 'static,
{
self.inner.spawn(fut)
}
@ -51,7 +53,7 @@ where
#[inline]
fn wait<F>(&mut self, fut: F)
where
F: ActorFuture<Item = (), Error = (), Actor = A> + 'static,
F: ActorFuture<Output = (), Actor = A> + 'static,
{
self.inner.wait(fut)
}
@ -81,7 +83,7 @@ where
{
#[inline]
/// Create a new HTTP Context from a request and an actor
pub fn create(actor: A) -> impl Stream<Item = Bytes, Error = Error> {
pub fn create(actor: A) -> impl Stream<Item = Result<Bytes, Error>> {
let mb = Mailbox::default();
let ctx = HttpContext {
inner: ContextParts::new(mb.sender_producer()),
@ -91,7 +93,7 @@ where
}
/// Create a new HTTP Context
pub fn with_factory<F>(f: F) -> impl Stream<Item = Bytes, Error = Error>
pub fn with_factory<F>(f: F) -> impl Stream<Item = Result<Bytes, Error>>
where
F: FnOnce(&mut Self) -> A + 'static,
{
@ -160,24 +162,23 @@ impl<A> Stream for HttpContextFut<A>
where
A: Actor<Context = HttpContext<A>>,
{
type Item = Bytes;
type Error = Error;
type Item = Result<Bytes, Error>;
fn poll(&mut self) -> Poll<Option<Bytes>, Error> {
fn poll_next(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
if self.fut.alive() {
match self.fut.poll() {
Ok(Async::NotReady) | Ok(Async::Ready(())) => (),
Err(_) => return Err(ErrorInternalServerError("error")),
}
let _ = Pin::new(&mut self.fut).poll(cx);
}
// frames
if let Some(data) = self.fut.ctx().stream.pop_front() {
Ok(Async::Ready(data))
Poll::Ready(data.map(|b| Ok(b)))
} else if self.fut.alive() {
Ok(Async::NotReady)
Poll::Pending
} else {
Ok(Async::Ready(None))
Poll::Ready(None)
}
}
}
@ -199,9 +200,9 @@ mod tests {
use actix::Actor;
use actix_web::http::StatusCode;
use actix_web::test::{block_on, call_service, init_service, TestRequest};
use actix_web::test::{call_service, init_service, read_body, TestRequest};
use actix_web::{web, App, HttpResponse};
use bytes::{Bytes, BytesMut};
use bytes::Bytes;
use super::*;
@ -223,31 +224,25 @@ mod tests {
if self.count > 3 {
ctx.write_eof()
} else {
ctx.write(Bytes::from(format!("LINE-{}", self.count).as_bytes()));
ctx.write(Bytes::from(format!("LINE-{}", self.count)));
ctx.run_later(Duration::from_millis(100), |slf, ctx| slf.write(ctx));
}
}
}
#[test]
fn test_default_resource() {
#[actix_rt::test]
async fn test_default_resource() {
let mut srv =
init_service(App::new().service(web::resource("/test").to(|| {
HttpResponse::Ok().streaming(HttpContext::create(MyActor { count: 0 }))
})));
})))
.await;
let req = TestRequest::with_uri("/test").to_request();
let mut resp = call_service(&mut srv, req);
let resp = call_service(&mut srv, req).await;
assert_eq!(resp.status(), StatusCode::OK);
let body = block_on(resp.take_body().fold(
BytesMut::new(),
move |mut body, chunk| {
body.extend_from_slice(&chunk);
Ok::<_, Error>(body)
},
))
.unwrap();
assert_eq!(body.freeze(), Bytes::from_static(b"LINE-1LINE-2LINE-3"));
let body = read_body(resp).await;
assert_eq!(body, Bytes::from_static(b"LINE-1LINE-2LINE-3"));
}
}

View File

@ -1,6 +1,8 @@
//! Websocket integration
use std::collections::VecDeque;
use std::io;
use std::pin::Pin;
use std::task::{Context, Poll};
use actix::dev::{
AsyncContextParts, ContextFut, ContextParts, Envelope, Mailbox, StreamHandler,
@ -16,20 +18,20 @@ use actix_http::ws::{hash_key, Codec};
pub use actix_http::ws::{
CloseCode, CloseReason, Frame, HandshakeError, Message, ProtocolError,
};
use actix_web::dev::HttpResponseBuilder;
use actix_web::error::{Error, ErrorInternalServerError, PayloadError};
use actix_web::error::{Error, PayloadError};
use actix_web::http::{header, Method, StatusCode};
use actix_web::{HttpRequest, HttpResponse};
use bytes::{Bytes, BytesMut};
use futures::sync::oneshot::Sender;
use futures::{Async, Future, Poll, Stream};
use futures::channel::oneshot::Sender;
use futures::{Future, Stream};
/// Do websocket handshake and start ws actor.
pub fn start<A, T>(actor: A, req: &HttpRequest, stream: T) -> Result<HttpResponse, Error>
where
A: Actor<Context = WebsocketContext<A>> + StreamHandler<Message, ProtocolError>,
T: Stream<Item = Bytes, Error = PayloadError> + 'static,
A: Actor<Context = WebsocketContext<A>>
+ StreamHandler<Result<Message, ProtocolError>>,
T: Stream<Item = Result<Bytes, PayloadError>> + 'static,
{
let mut res = handshake(req)?;
Ok(res.streaming(WebsocketContext::create(actor, stream)))
@ -52,8 +54,9 @@ pub fn start_with_addr<A, T>(
stream: T,
) -> Result<(Addr<A>, HttpResponse), Error>
where
A: Actor<Context = WebsocketContext<A>> + StreamHandler<Message, ProtocolError>,
T: Stream<Item = Bytes, Error = PayloadError> + 'static,
A: Actor<Context = WebsocketContext<A>>
+ StreamHandler<Result<Message, ProtocolError>>,
T: Stream<Item = Result<Bytes, PayloadError>> + 'static,
{
let mut res = handshake(req)?;
let (addr, out_stream) = WebsocketContext::create_with_addr(actor, stream);
@ -70,8 +73,9 @@ pub fn start_with_protocols<A, T>(
stream: T,
) -> Result<HttpResponse, Error>
where
A: Actor<Context = WebsocketContext<A>> + StreamHandler<Message, ProtocolError>,
T: Stream<Item = Bytes, Error = PayloadError> + 'static,
A: Actor<Context = WebsocketContext<A>>
+ StreamHandler<Result<Message, ProtocolError>>,
T: Stream<Item = Result<Bytes, PayloadError>> + 'static,
{
let mut res = handshake_with_protocols(req, protocols)?;
Ok(res.streaming(WebsocketContext::create(actor, stream)))
@ -202,14 +206,14 @@ where
{
fn spawn<F>(&mut self, fut: F) -> SpawnHandle
where
F: ActorFuture<Item = (), Error = (), Actor = A> + 'static,
F: ActorFuture<Output = (), Actor = A> + 'static,
{
self.inner.spawn(fut)
}
fn wait<F>(&mut self, fut: F)
where
F: ActorFuture<Item = (), Error = (), Actor = A> + 'static,
F: ActorFuture<Output = (), Actor = A> + 'static,
{
self.inner.wait(fut)
}
@ -238,10 +242,10 @@ where
{
#[inline]
/// Create a new Websocket context from a request and an actor
pub fn create<S>(actor: A, stream: S) -> impl Stream<Item = Bytes, Error = Error>
pub fn create<S>(actor: A, stream: S) -> impl Stream<Item = Result<Bytes, Error>>
where
A: StreamHandler<Message, ProtocolError>,
S: Stream<Item = Bytes, Error = PayloadError> + 'static,
A: StreamHandler<Result<Message, ProtocolError>>,
S: Stream<Item = Result<Bytes, PayloadError>> + 'static,
{
let (_, stream) = WebsocketContext::create_with_addr(actor, stream);
stream
@ -256,10 +260,10 @@ where
pub fn create_with_addr<S>(
actor: A,
stream: S,
) -> (Addr<A>, impl Stream<Item = Bytes, Error = Error>)
) -> (Addr<A>, impl Stream<Item = Result<Bytes, Error>>)
where
A: StreamHandler<Message, ProtocolError>,
S: Stream<Item = Bytes, Error = PayloadError> + 'static,
A: StreamHandler<Result<Message, ProtocolError>>,
S: Stream<Item = Result<Bytes, PayloadError>> + 'static,
{
let mb = Mailbox::default();
let mut ctx = WebsocketContext {
@ -279,10 +283,10 @@ where
actor: A,
stream: S,
codec: Codec,
) -> impl Stream<Item = Bytes, Error = Error>
) -> impl Stream<Item = Result<Bytes, Error>>
where
A: StreamHandler<Message, ProtocolError>,
S: Stream<Item = Bytes, Error = PayloadError> + 'static,
A: StreamHandler<Result<Message, ProtocolError>>,
S: Stream<Item = Result<Bytes, PayloadError>> + 'static,
{
let mb = Mailbox::default();
let mut ctx = WebsocketContext {
@ -298,11 +302,11 @@ where
pub fn with_factory<S, F>(
stream: S,
f: F,
) -> impl Stream<Item = Bytes, Error = Error>
) -> impl Stream<Item = Result<Bytes, Error>>
where
F: FnOnce(&mut Self) -> A + 'static,
A: StreamHandler<Message, ProtocolError>,
S: Stream<Item = Bytes, Error = PayloadError> + 'static,
A: StreamHandler<Result<Message, ProtocolError>>,
S: Stream<Item = Result<Bytes, PayloadError>> + 'static,
{
let mb = Mailbox::default();
let mut ctx = WebsocketContext {
@ -346,14 +350,14 @@ where
/// Send ping frame
#[inline]
pub fn ping(&mut self, message: &str) {
self.write_raw(Message::Ping(message.to_string()));
pub fn ping(&mut self, message: &[u8]) {
self.write_raw(Message::Ping(Bytes::copy_from_slice(message)));
}
/// Send pong frame
#[inline]
pub fn pong(&mut self, message: &str) {
self.write_raw(Message::Pong(message.to_string()));
pub fn pong(&mut self, message: &[u8]) {
self.write_raw(Message::Pong(Bytes::copy_from_slice(message)));
}
/// Send close frame
@ -415,30 +419,34 @@ impl<A> Stream for WebsocketContextFut<A>
where
A: Actor<Context = WebsocketContext<A>>,
{
type Item = Bytes;
type Error = Error;
type Item = Result<Bytes, Error>;
fn poll(&mut self) -> Poll<Option<Bytes>, Error> {
if self.fut.alive() && self.fut.poll().is_err() {
return Err(ErrorInternalServerError("error"));
fn poll_next(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
let this = self.get_mut();
if this.fut.alive() {
let _ = Pin::new(&mut this.fut).poll(cx);
}
// encode messages
while let Some(item) = self.fut.ctx().messages.pop_front() {
while let Some(item) = this.fut.ctx().messages.pop_front() {
if let Some(msg) = item {
self.encoder.encode(msg, &mut self.buf)?;
this.encoder.encode(msg, &mut this.buf)?;
} else {
self.closed = true;
this.closed = true;
break;
}
}
if !self.buf.is_empty() {
Ok(Async::Ready(Some(self.buf.take().freeze())))
} else if self.fut.alive() && !self.closed {
Ok(Async::NotReady)
if !this.buf.is_empty() {
Poll::Ready(Some(Ok(this.buf.split().freeze())))
} else if this.fut.alive() && !this.closed {
Poll::Pending
} else {
Ok(Async::Ready(None))
Poll::Ready(None)
}
}
}
@ -454,7 +462,9 @@ where
}
}
#[pin_project::pin_project]
struct WsStream<S> {
#[pin]
stream: S,
decoder: Codec,
buf: BytesMut,
@ -463,7 +473,7 @@ struct WsStream<S> {
impl<S> WsStream<S>
where
S: Stream<Item = Bytes, Error = PayloadError>,
S: Stream<Item = Result<Bytes, PayloadError>>,
{
fn new(stream: S, codec: Codec) -> Self {
Self {
@ -477,62 +487,64 @@ where
impl<S> Stream for WsStream<S>
where
S: Stream<Item = Bytes, Error = PayloadError>,
S: Stream<Item = Result<Bytes, PayloadError>>,
{
type Item = Message;
type Error = ProtocolError;
type Item = Result<Message, ProtocolError>;
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
if !self.closed {
fn poll_next(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
let mut this = self.as_mut().project();
if !*this.closed {
loop {
match self.stream.poll() {
Ok(Async::Ready(Some(chunk))) => {
self.buf.extend_from_slice(&chunk[..]);
this = self.as_mut().project();
match Pin::new(&mut this.stream).poll_next(cx) {
Poll::Ready(Some(Ok(chunk))) => {
this.buf.extend_from_slice(&chunk[..]);
}
Ok(Async::Ready(None)) => {
self.closed = true;
Poll::Ready(None) => {
*this.closed = true;
break;
}
Ok(Async::NotReady) => break,
Err(e) => {
return Err(ProtocolError::Io(io::Error::new(
io::ErrorKind::Other,
format!("{}", e),
)));
Poll::Pending => break,
Poll::Ready(Some(Err(e))) => {
return Poll::Ready(Some(Err(ProtocolError::Io(
io::Error::new(io::ErrorKind::Other, format!("{}", e)),
))));
}
}
}
}
match self.decoder.decode(&mut self.buf)? {
match this.decoder.decode(this.buf)? {
None => {
if self.closed {
Ok(Async::Ready(None))
if *this.closed {
Poll::Ready(None)
} else {
Ok(Async::NotReady)
Poll::Pending
}
}
Some(frm) => {
let msg = match frm {
Frame::Text(data) => {
if let Some(data) = data {
Message::Text(
std::str::from_utf8(&data)
.map_err(|_| ProtocolError::BadEncoding)?
.to_string(),
)
} else {
Message::Text(String::new())
}
}
Frame::Binary(data) => Message::Binary(
data.map(|b| b.freeze()).unwrap_or_else(Bytes::new),
Frame::Text(data) => Message::Text(
std::str::from_utf8(&data)
.map_err(|e| {
ProtocolError::Io(io::Error::new(
io::ErrorKind::Other,
format!("{}", e),
))
})?
.to_string(),
),
Frame::Binary(data) => Message::Binary(data),
Frame::Ping(s) => Message::Ping(s),
Frame::Pong(s) => Message::Pong(s),
Frame::Close(reason) => Message::Close(reason),
Frame::Continuation(item) => Message::Continuation(item),
};
Ok(Async::Ready(Some(msg)))
Poll::Ready(Some(Ok(msg)))
}
}
}

View File

@ -1,10 +1,8 @@
use actix::prelude::*;
use actix_http::HttpService;
use actix_http_test::TestServer;
use actix_web::{web, App, HttpRequest};
use actix_web::{test, web, App, HttpRequest};
use actix_web_actors::*;
use bytes::{Bytes, BytesMut};
use futures::{Sink, Stream};
use bytes::Bytes;
use futures::{SinkExt, StreamExt};
struct Ws;
@ -12,9 +10,13 @@ impl Actor for Ws {
type Context = ws::WebsocketContext<Self>;
}
impl StreamHandler<ws::Message, ws::ProtocolError> for Ws {
fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context) {
match msg {
impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for Ws {
fn handle(
&mut self,
msg: Result<ws::Message, ws::ProtocolError>,
ctx: &mut Self::Context,
) {
match msg.unwrap() {
ws::Message::Ping(msg) => ctx.pong(&msg),
ws::Message::Text(text) => ctx.text(text),
ws::Message::Binary(bin) => ctx.binary(bin),
@ -24,45 +26,42 @@ impl StreamHandler<ws::Message, ws::ProtocolError> for Ws {
}
}
#[test]
fn test_simple() {
let mut srv =
TestServer::new(|| {
HttpService::new(App::new().service(web::resource("/").to(
|req: HttpRequest, stream: web::Payload| ws::start(Ws, &req, stream),
)))
});
#[actix_rt::test]
async fn test_simple() {
let mut srv = test::start(|| {
App::new().service(web::resource("/").to(
|req: HttpRequest, stream: web::Payload| {
async move { ws::start(Ws, &req, stream) }
},
))
});
// client service
let framed = srv.ws().unwrap();
let framed = srv
.block_on(framed.send(ws::Message::Text("text".to_string())))
.unwrap();
let (item, framed) = srv.block_on(framed.into_future()).map_err(|_| ()).unwrap();
assert_eq!(item, Some(ws::Frame::Text(Some(BytesMut::from("text")))));
let framed = srv
.block_on(framed.send(ws::Message::Binary("text".into())))
.unwrap();
let (item, framed) = srv.block_on(framed.into_future()).map_err(|_| ()).unwrap();
assert_eq!(
item,
Some(ws::Frame::Binary(Some(Bytes::from_static(b"text").into())))
);
let framed = srv
.block_on(framed.send(ws::Message::Ping("text".into())))
.unwrap();
let (item, framed) = srv.block_on(framed.into_future()).map_err(|_| ()).unwrap();
assert_eq!(item, Some(ws::Frame::Pong("text".to_string().into())));
let framed = srv
.block_on(framed.send(ws::Message::Close(Some(ws::CloseCode::Normal.into()))))
let mut framed = srv.ws().await.unwrap();
framed
.send(ws::Message::Text("text".to_string()))
.await
.unwrap();
let (item, _framed) = srv.block_on(framed.into_future()).map_err(|_| ()).unwrap();
assert_eq!(
item,
Some(ws::Frame::Close(Some(ws::CloseCode::Normal.into())))
);
let item = framed.next().await.unwrap().unwrap();
assert_eq!(item, ws::Frame::Text(Bytes::from_static(b"text")));
framed
.send(ws::Message::Binary("text".into()))
.await
.unwrap();
let item = framed.next().await.unwrap().unwrap();
assert_eq!(item, ws::Frame::Binary(Bytes::from_static(b"text").into()));
framed.send(ws::Message::Ping("text".into())).await.unwrap();
let item = framed.next().await.unwrap().unwrap();
assert_eq!(item, ws::Frame::Pong(Bytes::copy_from_slice(b"text")));
framed
.send(ws::Message::Close(Some(ws::CloseCode::Normal.into())))
.await
.unwrap();
let item = framed.next().await.unwrap().unwrap();
assert_eq!(item, ws::Frame::Close(Some(ws::CloseCode::Normal.into())));
}

View File

@ -1,5 +1,9 @@
# Changes
## [0.2.0] - 2019-12-13
* Generate code for actix-web 2.0
## [0.1.3] - 2019-10-14
* Bump up `syn` & `quote` to 1.0

View File

@ -18,5 +18,5 @@ proc-macro2 = "^1"
[dev-dependencies]
actix-rt = { version = "1.0.0" }
actix-web = { version = "2.0.0-alpha.4" }
actix-web = { version = "2.0.0-rc" }
futures = { version = "0.3.1" }

View File

@ -1,5 +1,10 @@
# Changes
## [1.0.1] - 2019-12-15
* Fix compilation with default features off
## [1.0.0] - 2019-12-13
* Release

View File

@ -1,6 +1,6 @@
[package]
name = "awc"
version = "1.0.0"
version = "1.0.1"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix http client."
readme = "README.md"
@ -40,7 +40,7 @@ actix-http = "1.0.0"
actix-rt = "1.0.0"
base64 = "0.11"
bytes = "0.5.2"
bytes = "0.5.3"
derive_more = "0.99.2"
futures-core = "0.3.1"
log =" 0.4"
@ -54,14 +54,14 @@ open-ssl = { version="0.10", package="openssl", optional = true }
rust-tls = { version = "0.16.0", package="rustls", optional = true, features = ["dangerous_configuration"] }
[dev-dependencies]
actix-connect = { version = "1.0.0", features=["openssl"] }
actix-web = { version = "2.0.0-alpha.3", features=["openssl"] }
actix-http = { version = "1.0.0", features=["openssl"] }
actix-http-test = { version = "1.0.0-alpha.3", features=["openssl"] }
actix-utils = "1.0.0"
actix-connect = { version = "1.0.1", features=["openssl"] }
actix-web = { version = "2.0.0-rc", features=["openssl"] }
actix-http = { version = "1.0.1", features=["openssl"] }
actix-http-test = { version = "1.0.0", features=["openssl"] }
actix-utils = "1.0.3"
actix-server = "1.0.0"
actix-tls = { version = "1.0.0", features=["openssl", "rustls"] }
brotli = "3.3.0"
brotli2 = "0.3.2"
flate2 = "1.0.13"
futures = "0.3.1"
env_logger = "0.6"

View File

@ -7,15 +7,21 @@ use std::time::Duration;
use actix_rt::time::{delay_for, Delay};
use bytes::Bytes;
use derive_more::From;
use futures_core::{ready, Future, Stream};
use futures_core::{Future, Stream};
use serde::Serialize;
use serde_json;
use actix_http::body::{Body, BodyStream};
use actix_http::encoding::Decoder;
use actix_http::http::header::{self, ContentEncoding, IntoHeaderValue};
use actix_http::http::header::{self, IntoHeaderValue};
use actix_http::http::{Error as HttpError, HeaderMap, HeaderName};
use actix_http::{Error, Payload, PayloadStream, RequestHead};
use actix_http::{Error, RequestHead};
#[cfg(feature = "compress")]
use actix_http::encoding::Decoder;
#[cfg(feature = "compress")]
use actix_http::http::header::ContentEncoding;
#[cfg(feature = "compress")]
use actix_http::{Payload, PayloadStream};
use crate::error::{FreezeRequestError, InvalidUrl, SendRequestError};
use crate::response::ClientResponse;
@ -67,6 +73,7 @@ impl SendClientRequest {
}
}
#[cfg(feature = "compress")]
impl Future for SendClientRequest {
type Output =
Result<ClientResponse<Decoder<Payload<PayloadStream>>>, SendRequestError>;
@ -83,7 +90,7 @@ impl Future for SendClientRequest {
}
}
let res = ready!(Pin::new(send).poll(cx)).map(|res| {
let res = futures_core::ready!(Pin::new(send).poll(cx)).map(|res| {
res.map_body(|head, payload| {
if *response_decompress {
Payload::Stream(Decoder::from_headers(
@ -109,6 +116,30 @@ impl Future for SendClientRequest {
}
}
#[cfg(not(feature = "compress"))]
impl Future for SendClientRequest {
type Output = Result<ClientResponse, SendRequestError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.get_mut();
match this {
SendClientRequest::Fut(send, delay, _) => {
if delay.is_some() {
match Pin::new(delay.as_mut().unwrap()).poll(cx) {
Poll::Pending => (),
_ => return Poll::Ready(Err(SendRequestError::Timeout)),
}
}
Pin::new(send).poll(cx)
}
SendClientRequest::Err(ref mut e) => match e.take() {
Some(e) => Poll::Ready(Err(e)),
None => panic!("Attempting to call completed future"),
},
}
}
}
impl From<SendRequestError> for SendClientRequest {
fn from(e: SendRequestError) -> Self {
SendClientRequest::Err(Some(e))

View File

@ -4,7 +4,7 @@ use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Duration;
use brotli::CompressorWriter;
use brotli2::write::BrotliEncoder;
use bytes::Bytes;
use flate2::read::GzDecoder;
use flate2::write::GzEncoder;
@ -14,9 +14,10 @@ use rand::Rng;
use actix_http::HttpService;
use actix_http_test::test_server;
use actix_service::pipeline_factory;
use actix_service::{map_config, pipeline_factory, IntoServiceFactory};
use actix_web::dev::{AppConfig, BodyEncoding};
use actix_web::http::Cookie;
use actix_web::middleware::{BodyEncoding, Compress};
use actix_web::middleware::Compress;
use actix_web::{
http::header, test, web, App, Error, HttpMessage, HttpRequest, HttpResponse,
};
@ -169,10 +170,12 @@ async fn test_connection_reuse() {
ok(io)
})
.and_then(
HttpService::new(
HttpService::new(map_config(
App::new()
.service(web::resource("/").route(web::to(|| HttpResponse::Ok()))),
)
.service(web::resource("/").route(web::to(|| HttpResponse::Ok())))
.into_factory(),
|_| AppConfig::default(),
))
.tcp(),
)
});
@ -205,10 +208,12 @@ async fn test_connection_force_close() {
ok(io)
})
.and_then(
HttpService::new(
HttpService::new(map_config(
App::new()
.service(web::resource("/").route(web::to(|| HttpResponse::Ok()))),
)
.service(web::resource("/").route(web::to(|| HttpResponse::Ok())))
.into_factory(),
|_| AppConfig::default(),
))
.tcp(),
)
});
@ -234,22 +239,25 @@ async fn test_connection_server_close() {
let num = Arc::new(AtomicUsize::new(0));
let num2 = num.clone();
let srv = test_server(move || {
let num2 = num2.clone();
pipeline_factory(move |io| {
num2.fetch_add(1, Ordering::Relaxed);
ok(io)
})
.and_then(
HttpService::new(
App::new().service(
web::resource("/")
.route(web::to(|| HttpResponse::Ok().force_close().finish())),
),
let srv =
test_server(move || {
let num2 = num2.clone();
pipeline_factory(move |io| {
num2.fetch_add(1, Ordering::Relaxed);
ok(io)
})
.and_then(
HttpService::new(map_config(
App::new()
.service(web::resource("/").route(web::to(|| {
HttpResponse::Ok().force_close().finish()
})))
.into_factory(),
|_| AppConfig::default(),
))
.tcp(),
)
.tcp(),
)
});
});
let client = awc::Client::default();
@ -279,8 +287,14 @@ async fn test_connection_wait_queue() {
ok(io)
})
.and_then(
HttpService::new(App::new().service(
web::resource("/").route(web::to(|| HttpResponse::Ok().body(STR))),
HttpService::new(map_config(
App::new()
.service(
web::resource("/")
.route(web::to(|| HttpResponse::Ok().body(STR))),
)
.into_factory(),
|_| AppConfig::default(),
))
.tcp(),
)
@ -316,22 +330,25 @@ async fn test_connection_wait_queue_force_close() {
let num = Arc::new(AtomicUsize::new(0));
let num2 = num.clone();
let srv = test_server(move || {
let num2 = num2.clone();
pipeline_factory(move |io| {
num2.fetch_add(1, Ordering::Relaxed);
ok(io)
})
.and_then(
HttpService::new(
App::new().service(
web::resource("/")
.route(web::to(|| HttpResponse::Ok().force_close().body(STR))),
),
let srv =
test_server(move || {
let num2 = num2.clone();
pipeline_factory(move |io| {
num2.fetch_add(1, Ordering::Relaxed);
ok(io)
})
.and_then(
HttpService::new(map_config(
App::new()
.service(web::resource("/").route(web::to(|| {
HttpResponse::Ok().force_close().body(STR)
})))
.into_factory(),
|_| AppConfig::default(),
))
.tcp(),
)
.tcp(),
)
});
});
let client = awc::Client::build()
.connector(awc::Connector::new().limit(1).finish())
@ -499,9 +516,9 @@ async fn test_client_gzip_encoding_large_random() {
async fn test_client_brotli_encoding() {
let srv = test::start(|| {
App::new().service(web::resource("/").route(web::to(|data: Bytes| {
let mut e = CompressorWriter::new(Vec::new(), 0, 5, 0);
let mut e = BrotliEncoder::new(Vec::new(), 5);
e.write_all(&data).unwrap();
let data = e.into_inner();
let data = e.finish().unwrap();
HttpResponse::Ok()
.header("content-encoding", "br")
.body(data)
@ -526,9 +543,9 @@ async fn test_client_brotli_encoding_large_random() {
let srv = test::start(|| {
App::new().service(web::resource("/").route(web::to(|data: Bytes| {
let mut e = CompressorWriter::new(Vec::new(), 0, 5, 0);
let mut e = BrotliEncoder::new(Vec::new(), 5);
e.write_all(&data).unwrap();
let data = e.into_inner();
let data = e.finish().unwrap();
HttpResponse::Ok()
.header("content-encoding", "br")
.body(data)

View File

@ -4,9 +4,9 @@ use std::sync::Arc;
use actix_http::HttpService;
use actix_http_test::test_server;
use actix_service::{pipeline_factory, ServiceFactory};
use actix_service::{map_config, pipeline_factory, IntoServiceFactory, ServiceFactory};
use actix_web::http::Version;
use actix_web::{web, App, HttpResponse};
use actix_web::{dev::AppConfig, web, App, HttpResponse};
use futures::future::ok;
use open_ssl::ssl::{SslAcceptor, SslFiletype, SslMethod, SslVerifyMode};
use rust_tls::ClientConfig;
@ -62,8 +62,14 @@ async fn _test_connection_reuse_h2() {
})
.and_then(
HttpService::build()
.h2(App::new()
.service(web::resource("/").route(web::to(|| HttpResponse::Ok()))))
.h2(map_config(
App::new()
.service(
web::resource("/").route(web::to(|| HttpResponse::Ok())),
)
.into_factory(),
|_| AppConfig::default(),
))
.openssl(ssl_acceptor())
.map_err(|_| ()),
)

View File

@ -4,9 +4,9 @@ use std::sync::Arc;
use actix_http::HttpService;
use actix_http_test::test_server;
use actix_service::{pipeline_factory, ServiceFactory};
use actix_service::{map_config, pipeline_factory, IntoServiceFactory, ServiceFactory};
use actix_web::http::Version;
use actix_web::{web, App, HttpResponse};
use actix_web::{dev::AppConfig, web, App, HttpResponse};
use futures::future::ok;
use open_ssl::ssl::{SslAcceptor, SslConnector, SslFiletype, SslMethod, SslVerifyMode};
@ -44,8 +44,14 @@ async fn test_connection_reuse_h2() {
})
.and_then(
HttpService::build()
.h2(App::new()
.service(web::resource("/").route(web::to(|| HttpResponse::Ok()))))
.h2(map_config(
App::new()
.service(
web::resource("/").route(web::to(|| HttpResponse::Ok())),
)
.into_factory(),
|_| AppConfig::default(),
))
.openssl(ssl_acceptor())
.map_err(|_| ()),
)

View File

@ -5,6 +5,7 @@ use std::marker::PhantomData;
use std::rc::Rc;
use actix_http::body::{Body, MessageBody};
use actix_http::Extensions;
use actix_service::boxed::{self, BoxServiceFactory};
use actix_service::{
apply, apply_fn_factory, IntoServiceFactory, ServiceFactory, Transform,
@ -12,7 +13,7 @@ use actix_service::{
use futures::future::{FutureExt, LocalBoxFuture};
use crate::app_service::{AppEntry, AppInit, AppRoutingFactory};
use crate::config::{AppConfig, AppConfigInner, ServiceConfig};
use crate::config::ServiceConfig;
use crate::data::{Data, DataFactory};
use crate::dev::ResourceDef;
use crate::error::Error;
@ -36,8 +37,8 @@ pub struct App<T, B> {
factory_ref: Rc<RefCell<Option<AppRoutingFactory>>>,
data: Vec<Box<dyn DataFactory>>,
data_factories: Vec<FnDataFactory>,
config: AppConfigInner,
external: Vec<ResourceDef>,
extensions: Extensions,
_t: PhantomData<B>,
}
@ -52,8 +53,8 @@ impl App<AppEntry, Body> {
services: Vec::new(),
default: None,
factory_ref: fref,
config: AppConfigInner::default(),
external: Vec::new(),
extensions: Extensions::new(),
_t: PhantomData,
}
}
@ -77,8 +78,9 @@ where
/// an application instance. Http server constructs an application
/// instance for each thread, thus application data must be constructed
/// multiple times. If you want to share data between different
/// threads, a shared object should be used, e.g. `Arc`. Application
/// data does not need to be `Send` or `Sync`.
/// threads, a shared object should be used, e.g. `Arc`. Internally `Data` type
/// uses `Arc` so data could be created outside of app factory and clones could
/// be stored via `App::app_data()` method.
///
/// ```rust
/// use std::cell::Cell;
@ -135,10 +137,15 @@ where
self
}
/// Set application data. Application data could be accessed
/// by using `Data<T>` extractor where `T` is data type.
pub fn register_data<U: 'static>(mut self, data: Data<U>) -> Self {
self.data.push(Box::new(data));
/// Set application level arbitrary data item.
///
/// Application data stored with `App::app_data()` method is available
/// via `HttpRequest::app_data()` method at runtime.
///
/// This method could be used for storing `Data<T>` as well, in that case
/// data could be accessed by using `Data<T>` extractor.
pub fn app_data<U: 'static>(mut self, ext: U) -> Self {
self.extensions.insert(ext);
self
}
@ -225,18 +232,6 @@ where
self
}
/// Set server host name.
///
/// Host name is used by application router as a hostname for url generation.
/// Check [ConnectionInfo](./dev/struct.ConnectionInfo.html#method.host)
/// documentation for more information.
///
/// By default host name is set to a "localhost" value.
pub fn hostname(mut self, val: &str) -> Self {
self.config.host = val.to_owned();
self
}
/// Default service to be used if no matching resource could be found.
///
/// It is possible to use services like `Resource`, `Route`.
@ -383,8 +378,8 @@ where
services: self.services,
default: self.default,
factory_ref: self.factory_ref,
config: self.config,
external: self.external,
extensions: self.extensions,
_t: PhantomData,
}
}
@ -445,8 +440,8 @@ where
services: self.services,
default: self.default,
factory_ref: self.factory_ref,
config: self.config,
external: self.external,
extensions: self.extensions,
_t: PhantomData,
}
}
@ -472,7 +467,7 @@ where
external: RefCell::new(self.external),
default: self.default,
factory_ref: self.factory_ref,
config: RefCell::new(AppConfig(Rc::new(self.config))),
extensions: RefCell::new(Some(self.extensions)),
}
}
}
@ -556,6 +551,20 @@ mod tests {
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
#[actix_rt::test]
async fn test_extension() {
let mut srv = init_service(App::new().app_data(10usize).service(
web::resource("/").to(|req: HttpRequest| {
assert_eq!(*req.app_data::<usize>().unwrap(), 10);
HttpResponse::Ok()
}),
))
.await;
let req = TestRequest::default().to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[actix_rt::test]
async fn test_wrap() {
let mut srv = init_service(

View File

@ -39,9 +39,9 @@ where
>,
{
pub(crate) endpoint: T,
pub(crate) extensions: RefCell<Option<Extensions>>,
pub(crate) data: Rc<Vec<Box<dyn DataFactory>>>,
pub(crate) data_factories: Rc<Vec<FnDataFactory>>,
pub(crate) config: RefCell<AppConfig>,
pub(crate) services: Rc<RefCell<Vec<Box<dyn AppServiceFactory>>>>,
pub(crate) default: Option<Rc<HttpNewService>>,
pub(crate) factory_ref: Rc<RefCell<Option<AppRoutingFactory>>>,
@ -58,7 +58,7 @@ where
InitError = (),
>,
{
type Config = ();
type Config = AppConfig;
type Request = Request;
type Response = ServiceResponse<B>;
type Error = T::Error;
@ -66,7 +66,7 @@ where
type Service = AppInitService<T::Service, B>;
type Future = AppInitResult<T, B>;
fn new_service(&self, _: ()) -> Self::Future {
fn new_service(&self, config: AppConfig) -> Self::Future {
// update resource default service
let default = self.default.clone().unwrap_or_else(|| {
Rc::new(boxed::factory(fn_service(|req: ServiceRequest| {
@ -75,11 +75,7 @@ where
});
// App config
let mut config = AppService::new(
self.config.borrow().clone(),
default.clone(),
self.data.clone(),
);
let mut config = AppService::new(config, default.clone(), self.data.clone());
// register services
std::mem::replace(&mut *self.services.borrow_mut(), Vec::new())
@ -119,6 +115,12 @@ where
data: self.data.clone(),
data_factories: Vec::new(),
data_factories_fut: self.data_factories.iter().map(|f| f()).collect(),
extensions: Some(
self.extensions
.borrow_mut()
.take()
.unwrap_or_else(Extensions::new),
),
config,
rmap,
_t: PhantomData,
@ -139,6 +141,7 @@ where
data: Rc<Vec<Box<dyn DataFactory>>>,
data_factories: Vec<Box<dyn DataFactory>>,
data_factories_fut: Vec<LocalBoxFuture<'static, Result<Box<dyn DataFactory>, ()>>>,
extensions: Option<Extensions>,
_t: PhantomData<B>,
}
@ -177,7 +180,7 @@ where
if this.endpoint.is_some() && this.data_factories_fut.is_empty() {
// create app data container
let mut data = Extensions::new();
let mut data = this.extensions.take().unwrap();
for f in this.data.iter() {
f.create(&mut data);
}

View File

@ -124,14 +124,20 @@ impl AppService {
}
#[derive(Clone)]
pub struct AppConfig(pub(crate) Rc<AppConfigInner>);
pub struct AppConfig(Rc<AppConfigInner>);
struct AppConfigInner {
secure: bool,
host: String,
addr: SocketAddr,
}
impl AppConfig {
pub(crate) fn new(inner: AppConfigInner) -> Self {
AppConfig(Rc::new(inner))
pub(crate) fn new(secure: bool, addr: SocketAddr, host: String) -> Self {
AppConfig(Rc::new(AppConfigInner { secure, addr, host }))
}
/// Set server host name.
/// Server host name.
///
/// Host name is used by application router as a hostname for url generation.
/// Check [ConnectionInfo](./struct.ConnectionInfo.html#method.host)
@ -153,19 +159,13 @@ impl AppConfig {
}
}
pub(crate) struct AppConfigInner {
pub(crate) secure: bool,
pub(crate) host: String,
pub(crate) addr: SocketAddr,
}
impl Default for AppConfigInner {
fn default() -> AppConfigInner {
AppConfigInner {
secure: false,
addr: "127.0.0.1:8080".parse().unwrap(),
host: "localhost:8080".to_owned(),
}
impl Default for AppConfig {
fn default() -> Self {
AppConfig::new(
false,
"127.0.0.1:8080".parse().unwrap(),
"localhost:8080".to_owned(),
)
}
}

View File

@ -56,7 +56,7 @@ pub(crate) trait DataFactory {
///
/// let app = App::new()
/// // Store `MyData` in application storage.
/// .register_data(data.clone())
/// .app_data(data.clone())
/// .service(
/// web::resource("/index.html").route(
/// web::get().to(index)));
@ -87,10 +87,10 @@ impl<T> Data<T> {
}
impl<T> Deref for Data<T> {
type Target = T;
type Target = Arc<T>;
fn deref(&self) -> &T {
self.0.as_ref()
fn deref(&self) -> &Arc<T> {
&self.0
}
}
@ -107,8 +107,8 @@ impl<T: 'static> FromRequest for Data<T> {
#[inline]
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
if let Some(st) = req.get_app_data::<T>() {
ok(st)
if let Some(st) = req.app_data::<Data<T>>() {
ok(st.clone())
} else {
log::debug!(
"Failed to construct App-level Data extractor. \
@ -144,11 +144,13 @@ mod tests {
#[actix_rt::test]
async fn test_data_extractor() {
let mut srv =
init_service(App::new().data(10usize).service(
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
))
.await;
let mut srv = init_service(App::new().data("TEST".to_string()).service(
web::resource("/").to(|data: web::Data<String>| {
assert_eq!(data.to_lowercase(), "test");
HttpResponse::Ok()
}),
))
.await;
let req = TestRequest::default().to_request();
let resp = srv.call(req).await.unwrap();
@ -165,9 +167,9 @@ mod tests {
}
#[actix_rt::test]
async fn test_register_data_extractor() {
async fn test_app_data_extractor() {
let mut srv =
init_service(App::new().register_data(Data::new(10usize)).service(
init_service(App::new().app_data(Data::new(10usize)).service(
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
))
.await;
@ -177,7 +179,7 @@ mod tests {
assert_eq!(resp.status(), StatusCode::OK);
let mut srv =
init_service(App::new().register_data(Data::new(10u32)).service(
init_service(App::new().app_data(Data::new(10u32)).service(
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
))
.await;
@ -220,7 +222,7 @@ mod tests {
let mut srv = init_service(App::new().data(1usize).service(
web::resource("/").data(10usize).route(web::get().to(
|data: web::Data<usize>| {
assert_eq!(*data, 10);
assert_eq!(**data, 10);
let _ = data.clone();
HttpResponse::Ok()
},

View File

@ -6,7 +6,6 @@ use url::ParseError as UrlParseError;
use crate::http::StatusCode;
use crate::HttpResponse;
use serde_urlencoded::de;
/// Errors which can occur when attempting to generate resource uri.
#[derive(Debug, PartialEq, Display, From)]
@ -97,7 +96,7 @@ impl ResponseError for JsonPayloadError {
pub enum PathError {
/// Deserialize error
#[display(fmt = "Path deserialize error: {}", _0)]
Deserialize(de::Error),
Deserialize(serde::de::value::Error),
}
/// Return `BadRequest` for `PathError`
@ -112,7 +111,7 @@ impl ResponseError for PathError {
pub enum QueryPayloadError {
/// Deserialize error
#[display(fmt = "Query deserialize error: {}", _0)]
Deserialize(de::Error),
Deserialize(serde::de::value::Error),
}
/// Return `BadRequest` for `QueryPayloadError`

View File

@ -141,6 +141,7 @@ pub mod dev {
pub use crate::types::readlines::Readlines;
pub use actix_http::body::{Body, BodySize, MessageBody, ResponseBody, SizedStream};
#[cfg(feature = "compress")]
pub use actix_http::encoding::Decoder as Decompress;
pub use actix_http::ResponseBuilder as HttpResponseBuilder;
pub use actix_http::{
@ -157,6 +158,50 @@ pub mod dev {
};
path
}
use crate::http::header::ContentEncoding;
use actix_http::{Response, ResponseBuilder};
struct Enc(ContentEncoding);
/// Helper trait that allows to set specific encoding for response.
pub trait BodyEncoding {
/// Get content encoding
fn get_encoding(&self) -> Option<ContentEncoding>;
/// Set content encoding
fn encoding(&mut self, encoding: ContentEncoding) -> &mut Self;
}
impl BodyEncoding for ResponseBuilder {
fn get_encoding(&self) -> Option<ContentEncoding> {
if let Some(ref enc) = self.extensions().get::<Enc>() {
Some(enc.0)
} else {
None
}
}
fn encoding(&mut self, encoding: ContentEncoding) -> &mut Self {
self.extensions_mut().insert(Enc(encoding));
self
}
}
impl<B> BodyEncoding for Response<B> {
fn get_encoding(&self) -> Option<ContentEncoding> {
if let Some(ref enc) = self.extensions().get::<Enc>() {
Some(enc.0)
} else {
None
}
}
fn encoding(&mut self, encoding: ContentEncoding) -> &mut Self {
self.extensions_mut().insert(Enc(encoding));
self
}
}
}
pub mod client {

View File

@ -9,34 +9,14 @@ use std::task::{Context, Poll};
use actix_http::body::MessageBody;
use actix_http::encoding::Encoder;
use actix_http::http::header::{ContentEncoding, ACCEPT_ENCODING};
use actix_http::{Error, Response, ResponseBuilder};
use actix_http::Error;
use actix_service::{Service, Transform};
use futures::future::{ok, Ready};
use pin_project::pin_project;
use crate::dev::BodyEncoding;
use crate::service::{ServiceRequest, ServiceResponse};
struct Enc(ContentEncoding);
/// Helper trait that allows to set specific encoding for response.
pub trait BodyEncoding {
fn encoding(&mut self, encoding: ContentEncoding) -> &mut Self;
}
impl BodyEncoding for ResponseBuilder {
fn encoding(&mut self, encoding: ContentEncoding) -> &mut Self {
self.extensions_mut().insert(Enc(encoding));
self
}
}
impl<B> BodyEncoding for Response<B> {
fn encoding(&mut self, encoding: ContentEncoding) -> &mut Self {
self.extensions_mut().insert(Enc(encoding));
self
}
}
#[derive(Debug, Clone)]
/// `Middleware` for compressing response body.
///
@ -155,8 +135,8 @@ where
match futures::ready!(this.fut.poll(cx)) {
Ok(resp) => {
let enc = if let Some(enc) = resp.response().extensions().get::<Enc>() {
enc.0
let enc = if let Some(enc) = resp.response().get_encoding() {
enc
} else {
*this.encoding
};

View File

@ -1,6 +1,9 @@
//! Middlewares
#[cfg(feature = "compress")]
mod compress;
pub use self::compress::{BodyEncoding, Compress};
#[cfg(feature = "compress")]
pub use self::compress::Compress;
mod condition;
mod defaultheaders;

View File

@ -8,7 +8,6 @@ use actix_router::{Path, Url};
use futures::future::{ok, Ready};
use crate::config::AppConfig;
use crate::data::Data;
use crate::error::UrlGenerationError;
use crate::extract::FromRequest;
use crate::info::ConnectionInfo;
@ -207,25 +206,15 @@ impl HttpRequest {
&self.0.config
}
/// Get an application data stored with `App::data()` method during
/// Get an application data stored with `App::extension()` method during
/// application configuration.
pub fn app_data<T: 'static>(&self) -> Option<&T> {
if let Some(st) = self.0.app_data.get::<Data<T>>() {
if let Some(st) = self.0.app_data.get::<T>() {
Some(&st)
} else {
None
}
}
/// Get an application data stored with `App::data()` method during
/// application configuration.
pub fn get_app_data<T: 'static>(&self) -> Option<Data<T>> {
if let Some(st) = self.0.app_data.get::<Data<T>>() {
Some(st.clone())
} else {
None
}
}
}
impl HttpMessage for HttpRequest {
@ -467,8 +456,8 @@ mod tests {
}
#[actix_rt::test]
async fn test_app_data() {
let mut srv = init_service(App::new().data(10usize).service(
async fn test_data() {
let mut srv = init_service(App::new().app_data(10usize).service(
web::resource("/").to(|req: HttpRequest| {
if req.app_data::<usize>().is_some() {
HttpResponse::Ok()
@ -483,7 +472,7 @@ mod tests {
let resp = call_service(&mut srv, req).await;
assert_eq!(resp.status(), StatusCode::OK);
let mut srv = init_service(App::new().data(10u32).service(
let mut srv = init_service(App::new().app_data(10u32).service(
web::resource("/").to(|req: HttpRequest| {
if req.app_data::<usize>().is_some() {
HttpResponse::Ok()

View File

@ -192,16 +192,13 @@ where
/// }
/// ```
pub fn data<U: 'static>(self, data: U) -> Self {
self.register_data(Data::new(data))
self.app_data(Data::new(data))
}
/// Set or override application data.
///
/// This method has the same effect as [`Resource::data`](#method.data),
/// except that instead of taking a value of some type `T`, it expects a
/// value of type `Data<T>`. Use a `Data<T>` extractor to retrieve its
/// value.
pub fn register_data<U: 'static>(mut self, data: Data<U>) -> Self {
/// This method overrides data stored with [`App::app_data()`](#method.app_data)
pub fn app_data<U: 'static>(mut self, data: U) -> Self {
if self.data.is_none() {
self.data = Some(Extensions::new());
}
@ -754,19 +751,19 @@ mod tests {
App::new()
.data(1.0f64)
.data(1usize)
.register_data(web::Data::new('-'))
.app_data(web::Data::new('-'))
.service(
web::resource("/test")
.data(10usize)
.register_data(web::Data::new('*'))
.app_data(web::Data::new('*'))
.guard(guard::Get())
.to(
|data1: web::Data<usize>,
data2: web::Data<char>,
data3: web::Data<f64>| {
assert_eq!(*data1, 10);
assert_eq!(*data2, '*');
assert_eq!(*data3, 1.0);
assert_eq!(**data1, 10);
assert_eq!(**data2, '*');
assert_eq!(**data3, 1.0);
HttpResponse::Ok()
},
),

View File

@ -148,15 +148,13 @@ where
/// }
/// ```
pub fn data<U: 'static>(self, data: U) -> Self {
self.register_data(Data::new(data))
self.app_data(Data::new(data))
}
/// Set or override application data.
///
/// This method has the same effect as [`Scope::data`](#method.data), except
/// that instead of taking a value of some type `T`, it expects a value of
/// type `Data<T>`. Use a `Data<T>` extractor to retrieve its value.
pub fn register_data<U: 'static>(mut self, data: Data<U>) -> Self {
/// This method overrides data stored with [`App::app_data()`](#method.app_data)
pub fn app_data<U: 'static>(mut self, data: U) -> Self {
if self.data.is_none() {
self.data = Some(Extensions::new());
}
@ -1108,7 +1106,7 @@ mod tests {
web::scope("app").data(10usize).route(
"/t",
web::get().to(|data: web::Data<usize>| {
assert_eq!(*data, 10);
assert_eq!(**data, 10);
let _ = data.clone();
HttpResponse::Ok()
}),
@ -1122,21 +1120,17 @@ mod tests {
}
#[actix_rt::test]
async fn test_override_register_data() {
let mut srv = init_service(
App::new().register_data(web::Data::new(1usize)).service(
web::scope("app")
.register_data(web::Data::new(10usize))
.route(
"/t",
web::get().to(|data: web::Data<usize>| {
assert_eq!(*data, 10);
let _ = data.clone();
HttpResponse::Ok()
}),
),
async fn test_override_app_data() {
let mut srv = init_service(App::new().app_data(web::Data::new(1usize)).service(
web::scope("app").app_data(web::Data::new(10usize)).route(
"/t",
web::get().to(|data: web::Data<usize>| {
assert_eq!(**data, 10);
let _ = data.clone();
HttpResponse::Ok()
}),
),
)
))
.await;
let req = TestRequest::with_uri("/app/t").to_request();

View File

@ -6,7 +6,9 @@ use actix_http::{
body::MessageBody, Error, HttpService, KeepAlive, Protocol, Request, Response,
};
use actix_server::{Server, ServerBuilder};
use actix_service::{pipeline_factory, IntoServiceFactory, Service, ServiceFactory};
use actix_service::{
map_config, pipeline_factory, IntoServiceFactory, Service, ServiceFactory,
};
use futures::future::ok;
use net2::TcpBuilder;
@ -16,12 +18,15 @@ use actix_tls::openssl::{AlpnError, SslAcceptor, SslAcceptorBuilder};
#[cfg(feature = "rustls")]
use actix_tls::rustls::ServerConfig as RustlsServerConfig;
use crate::config::AppConfig;
struct Socket {
scheme: &'static str,
addr: net::SocketAddr,
}
struct Config {
host: Option<String>,
keep_alive: KeepAlive,
client_timeout: u64,
client_shutdown: u64,
@ -52,14 +57,13 @@ pub struct HttpServer<F, I, S, B>
where
F: Fn() -> I + Send + Clone + 'static,
I: IntoServiceFactory<S>,
S: ServiceFactory<Config = (), Request = Request>,
S: ServiceFactory<Config = AppConfig, Request = Request>,
S::Error: Into<Error>,
S::InitError: fmt::Debug,
S::Response: Into<Response<B>>,
B: MessageBody,
{
pub(super) factory: F,
pub(super) host: Option<String>,
config: Arc<Mutex<Config>>,
backlog: i32,
sockets: Vec<Socket>,
@ -71,7 +75,7 @@ impl<F, I, S, B> HttpServer<F, I, S, B>
where
F: Fn() -> I + Send + Clone + 'static,
I: IntoServiceFactory<S>,
S: ServiceFactory<Config = (), Request = Request>,
S: ServiceFactory<Config = AppConfig, Request = Request>,
S::Error: Into<Error> + 'static,
S::InitError: fmt::Debug,
S::Response: Into<Response<B>> + 'static,
@ -82,8 +86,8 @@ where
pub fn new(factory: F) -> Self {
HttpServer {
factory,
host: None,
config: Arc::new(Mutex::new(Config {
host: None,
keep_alive: KeepAlive::Timeout(5),
client_timeout: 5000,
client_shutdown: 5000,
@ -184,8 +188,8 @@ where
/// documentation for more information.
///
/// By default host name is set to a "localhost" value.
pub fn server_hostname<T: AsRef<str>>(mut self, val: T) -> Self {
self.host = Some(val.as_ref().to_owned());
pub fn server_hostname<T: AsRef<str>>(self, val: T) -> Self {
self.config.lock().unwrap().host = Some(val.as_ref().to_owned());
self
}
@ -246,11 +250,17 @@ where
lst,
move || {
let c = cfg.lock().unwrap();
let cfg = AppConfig::new(
false,
addr,
c.host.clone().unwrap_or_else(|| format!("{}", addr)),
);
HttpService::build()
.keep_alive(c.keep_alive)
.client_timeout(c.client_timeout)
.local_addr(addr)
.finish(factory())
.finish(map_config(factory().into_factory(), move |_| cfg.clone()))
.tcp()
},
)?;
@ -288,11 +298,16 @@ where
lst,
move || {
let c = cfg.lock().unwrap();
let cfg = AppConfig::new(
true,
addr,
c.host.clone().unwrap_or_else(|| format!("{}", addr)),
);
HttpService::build()
.keep_alive(c.keep_alive)
.client_timeout(c.client_timeout)
.client_disconnect(c.client_shutdown)
.finish(factory())
.finish(map_config(factory().into_factory(), move |_| cfg.clone()))
.openssl(acceptor.clone())
},
)?;
@ -330,11 +345,16 @@ where
lst,
move || {
let c = cfg.lock().unwrap();
let cfg = AppConfig::new(
true,
addr,
c.host.clone().unwrap_or_else(|| format!("{}", addr)),
);
HttpService::build()
.keep_alive(c.keep_alive)
.client_timeout(c.client_timeout)
.client_disconnect(c.client_shutdown)
.finish(factory())
.finish(map_config(factory().into_factory(), move |_| cfg.clone()))
.rustls(config.clone())
},
)?;
@ -435,24 +455,31 @@ where
let cfg = self.config.clone();
let factory = self.factory.clone();
// todo duplicated:
let socket_addr = net::SocketAddr::new(
net::IpAddr::V4(net::Ipv4Addr::new(127, 0, 0, 1)),
8080,
);
self.sockets.push(Socket {
scheme: "http",
addr: net::SocketAddr::new(
net::IpAddr::V4(net::Ipv4Addr::new(127, 0, 0, 1)),
8080,
),
addr: socket_addr,
});
let addr = format!("actix-web-service-{:?}", lst.local_addr()?);
self.builder = self.builder.listen_uds(addr, lst, move || {
let c = cfg.lock().unwrap();
let config = AppConfig::new(
false,
socket_addr,
c.host.clone().unwrap_or_else(|| format!("{}", socket_addr)),
);
pipeline_factory(|io: UnixStream| ok((io, Protocol::Http1, None))).and_then(
HttpService::build()
.keep_alive(c.keep_alive)
.client_timeout(c.client_timeout)
.finish(factory()),
.finish(map_config(factory().into_factory(), move |_| {
config.clone()
})),
)
})?;
Ok(self)
@ -470,12 +497,13 @@ where
let cfg = self.config.clone();
let factory = self.factory.clone();
let socket_addr = net::SocketAddr::new(
net::IpAddr::V4(net::Ipv4Addr::new(127, 0, 0, 1)),
8080,
);
self.sockets.push(Socket {
scheme: "http",
addr: net::SocketAddr::new(
net::IpAddr::V4(net::Ipv4Addr::new(127, 0, 0, 1)),
8080,
),
addr: socket_addr,
});
self.builder = self.builder.bind_uds(
@ -483,12 +511,19 @@ where
addr,
move || {
let c = cfg.lock().unwrap();
let config = AppConfig::new(
false,
socket_addr,
c.host.clone().unwrap_or_else(|| format!("{}", socket_addr)),
);
pipeline_factory(|io: UnixStream| ok((io, Protocol::Http1, None)))
.and_then(
HttpService::build()
.keep_alive(c.keep_alive)
.client_timeout(c.client_timeout)
.finish(factory()),
.finish(map_config(factory().into_factory(), move |_| {
config.clone()
})),
)
},
)?;
@ -500,7 +535,7 @@ impl<F, I, S, B> HttpServer<F, I, S, B>
where
F: Fn() -> I + Send + Clone + 'static,
I: IntoServiceFactory<S>,
S: ServiceFactory<Config = (), Request = Request>,
S: ServiceFactory<Config = AppConfig, Request = Request>,
S::Error: Into<Error>,
S::InitError: fmt::Debug,
S::Response: Into<Response<B>>,

View File

@ -1,5 +1,6 @@
//! Various helpers for Actix applications to use during testing.
use std::convert::TryFrom;
use std::net::SocketAddr;
use std::rc::Rc;
use std::sync::mpsc;
use std::{fmt, net, thread, time};
@ -12,7 +13,9 @@ use actix_http::{cookie::Cookie, ws, Extensions, HttpService, Request};
use actix_router::{Path, ResourceDef, Url};
use actix_rt::System;
use actix_server::Server;
use actix_service::{IntoService, IntoServiceFactory, Service, ServiceFactory};
use actix_service::{
map_config, IntoService, IntoServiceFactory, Service, ServiceFactory,
};
use awc::error::PayloadError;
use awc::{Client, ClientRequest, ClientResponse, Connector};
use bytes::{Bytes, BytesMut};
@ -25,7 +28,7 @@ use serde_json;
pub use actix_http::test::TestBuffer;
use crate::config::{AppConfig, AppConfigInner};
use crate::config::AppConfig;
use crate::data::Data;
use crate::dev::{Body, MessageBody, Payload};
use crate::request::HttpRequestPool;
@ -79,7 +82,7 @@ pub async fn init_service<R, S, B, E>(
where
R: IntoServiceFactory<S>,
S: ServiceFactory<
Config = (),
Config = AppConfig,
Request = Request,
Response = ServiceResponse<B>,
Error = E,
@ -87,7 +90,7 @@ where
S::InitError: std::fmt::Debug,
{
let srv = app.into_factory();
srv.new_service(()).await.unwrap()
srv.new_service(AppConfig::default()).await.unwrap()
}
/// Calls service and waits for response future completion.
@ -296,8 +299,9 @@ where
pub struct TestRequest {
req: HttpTestRequest,
rmap: ResourceMap,
config: AppConfigInner,
config: AppConfig,
path: Path<Url>,
peer_addr: Option<SocketAddr>,
app_data: Extensions,
}
@ -306,8 +310,9 @@ impl Default for TestRequest {
TestRequest {
req: HttpTestRequest::default(),
rmap: ResourceMap::new(ResourceDef::new("")),
config: AppConfigInner::default(),
config: AppConfig::default(),
path: Path::new(Url::new(Uri::default())),
peer_addr: None,
app_data: Extensions::new(),
}
}
@ -407,6 +412,12 @@ impl TestRequest {
self
}
/// Set peer addr
pub fn peer_addr(mut self, addr: SocketAddr) -> Self {
self.peer_addr = Some(addr);
self
}
/// Set request payload
pub fn set_payload<B: Into<Bytes>>(mut self, data: B) -> Self {
self.req.set_payload(data);
@ -440,6 +451,13 @@ impl TestRequest {
self
}
/// Set application data. This is equivalent of `App::app_data()` method
/// for testing purpose.
pub fn app_data<T: 'static>(mut self, data: T) -> Self {
self.app_data.insert(data);
self
}
#[cfg(test)]
/// Set request config
pub(crate) fn rmap(mut self, rmap: ResourceMap) -> Self {
@ -449,12 +467,15 @@ impl TestRequest {
/// Complete request creation and generate `Request` instance
pub fn to_request(mut self) -> Request {
self.req.finish()
let mut req = self.req.finish();
req.head_mut().peer_addr = self.peer_addr;
req
}
/// Complete request creation and generate `ServiceRequest` instance
pub fn to_srv_request(mut self) -> ServiceRequest {
let (head, payload) = self.req.finish().into_parts();
let (mut head, payload) = self.req.finish().into_parts();
head.peer_addr = self.peer_addr;
self.path.get_mut().update(&head.uri);
ServiceRequest::new(HttpRequest::new(
@ -462,7 +483,7 @@ impl TestRequest {
head,
payload,
Rc::new(self.rmap),
AppConfig::new(self.config),
self.config.clone(),
Rc::new(self.app_data),
HttpRequestPool::create(),
))
@ -475,7 +496,8 @@ impl TestRequest {
/// Complete request creation and generate `HttpRequest` instance
pub fn to_http_request(mut self) -> HttpRequest {
let (head, payload) = self.req.finish().into_parts();
let (mut head, payload) = self.req.finish().into_parts();
head.peer_addr = self.peer_addr;
self.path.get_mut().update(&head.uri);
HttpRequest::new(
@ -483,7 +505,7 @@ impl TestRequest {
head,
payload,
Rc::new(self.rmap),
AppConfig::new(self.config),
self.config.clone(),
Rc::new(self.app_data),
HttpRequestPool::create(),
)
@ -491,7 +513,8 @@ impl TestRequest {
/// Complete request creation and generate `HttpRequest` and `Payload` instances
pub fn to_http_parts(mut self) -> (HttpRequest, Payload) {
let (head, payload) = self.req.finish().into_parts();
let (mut head, payload) = self.req.finish().into_parts();
head.peer_addr = self.peer_addr;
self.path.get_mut().update(&head.uri);
let req = HttpRequest::new(
@ -499,7 +522,7 @@ impl TestRequest {
head,
Payload::None,
Rc::new(self.rmap),
AppConfig::new(self.config),
self.config.clone(),
Rc::new(self.app_data),
HttpRequestPool::create(),
);
@ -538,7 +561,7 @@ pub fn start<F, I, S, B>(factory: F) -> TestServer
where
F: Fn() -> I + Send + Clone + 'static,
I: IntoServiceFactory<S>,
S: ServiceFactory<Config = (), Request = Request> + 'static,
S: ServiceFactory<Config = AppConfig, Request = Request> + 'static,
S::Error: Into<Error> + 'static,
S::InitError: fmt::Debug,
S::Response: Into<HttpResponse<B>> + 'static,
@ -577,7 +600,7 @@ pub fn start_with<F, I, S, B>(cfg: TestServerConfig, factory: F) -> TestServer
where
F: Fn() -> I + Send + Clone + 'static,
I: IntoServiceFactory<S>,
S: ServiceFactory<Config = (), Request = Request> + 'static,
S: ServiceFactory<Config = AppConfig, Request = Request> + 'static,
S::Error: Into<Error> + 'static,
S::InitError: fmt::Debug,
S::Response: Into<HttpResponse<B>> + 'static,
@ -607,63 +630,87 @@ where
match cfg.stream {
StreamType::Tcp => match cfg.tp {
HttpVer::Http1 => builder.listen("test", tcp, move || {
let cfg =
AppConfig::new(false, local_addr, format!("{}", local_addr));
HttpService::build()
.client_timeout(ctimeout)
.h1(factory())
.h1(map_config(factory().into_factory(), move |_| cfg.clone()))
.tcp()
}),
HttpVer::Http2 => builder.listen("test", tcp, move || {
let cfg =
AppConfig::new(false, local_addr, format!("{}", local_addr));
HttpService::build()
.client_timeout(ctimeout)
.h2(factory())
.h2(map_config(factory().into_factory(), move |_| cfg.clone()))
.tcp()
}),
HttpVer::Both => builder.listen("test", tcp, move || {
let cfg =
AppConfig::new(false, local_addr, format!("{}", local_addr));
HttpService::build()
.client_timeout(ctimeout)
.finish(factory())
.finish(map_config(factory().into_factory(), move |_| {
cfg.clone()
}))
.tcp()
}),
},
#[cfg(feature = "openssl")]
StreamType::Openssl(acceptor) => match cfg.tp {
HttpVer::Http1 => builder.listen("test", tcp, move || {
let cfg =
AppConfig::new(true, local_addr, format!("{}", local_addr));
HttpService::build()
.client_timeout(ctimeout)
.h1(factory())
.h1(map_config(factory().into_factory(), move |_| cfg.clone()))
.openssl(acceptor.clone())
}),
HttpVer::Http2 => builder.listen("test", tcp, move || {
let cfg =
AppConfig::new(true, local_addr, format!("{}", local_addr));
HttpService::build()
.client_timeout(ctimeout)
.h2(factory())
.h2(map_config(factory().into_factory(), move |_| cfg.clone()))
.openssl(acceptor.clone())
}),
HttpVer::Both => builder.listen("test", tcp, move || {
let cfg =
AppConfig::new(true, local_addr, format!("{}", local_addr));
HttpService::build()
.client_timeout(ctimeout)
.finish(factory())
.finish(map_config(factory().into_factory(), move |_| {
cfg.clone()
}))
.openssl(acceptor.clone())
}),
},
#[cfg(feature = "rustls")]
StreamType::Rustls(config) => match cfg.tp {
HttpVer::Http1 => builder.listen("test", tcp, move || {
let cfg =
AppConfig::new(true, local_addr, format!("{}", local_addr));
HttpService::build()
.client_timeout(ctimeout)
.h1(factory())
.h1(map_config(factory().into_factory(), move |_| cfg.clone()))
.rustls(config.clone())
}),
HttpVer::Http2 => builder.listen("test", tcp, move || {
let cfg =
AppConfig::new(true, local_addr, format!("{}", local_addr));
HttpService::build()
.client_timeout(ctimeout)
.h2(factory())
.h2(map_config(factory().into_factory(), move |_| cfg.clone()))
.rustls(config.clone())
}),
HttpVer::Both => builder.listen("test", tcp, move || {
let cfg =
AppConfig::new(true, local_addr, format!("{}", local_addr));
HttpService::build()
.client_timeout(ctimeout)
.finish(factory())
.finish(map_config(factory().into_factory(), move |_| {
cfg.clone()
}))
.rustls(config.clone())
}),
},
@ -910,6 +957,7 @@ impl Drop for TestServer {
#[cfg(test)]
mod tests {
use actix_http::httpmessage::HttpMessage;
use futures::FutureExt;
use serde::{Deserialize, Serialize};
use std::time::SystemTime;
@ -923,19 +971,24 @@ mod tests {
.set(header::Date(SystemTime::now().into()))
.param("test", "123")
.data(10u32)
.app_data(20u64)
.peer_addr("127.0.0.1:8081".parse().unwrap())
.to_http_request();
assert!(req.headers().contains_key(header::CONTENT_TYPE));
assert!(req.headers().contains_key(header::DATE));
assert_eq!(
req.head().peer_addr,
Some("127.0.0.1:8081".parse().unwrap())
);
assert_eq!(&req.match_info()["test"], "123");
assert_eq!(req.version(), Version::HTTP_2);
let data = req.get_app_data::<u32>().unwrap();
assert!(req.get_app_data::<u64>().is_none());
assert_eq!(*data, 10);
let data = req.app_data::<Data<u32>>().unwrap();
assert!(req.app_data::<Data<u64>>().is_none());
assert_eq!(*data.get_ref(), 10);
assert!(req.app_data::<u64>().is_none());
let data = req.app_data::<u32>().unwrap();
assert_eq!(*data, 10);
assert!(req.app_data::<u32>().is_none());
let data = req.app_data::<u64>().unwrap();
assert_eq!(*data, 20);
}
#[actix_rt::test]
@ -1095,41 +1148,46 @@ mod tests {
assert!(res.status().is_success());
}
// #[actix_rt::test]
// fn test_actor() {
// use actix::Actor;
#[actix_rt::test]
async fn test_actor() {
use actix::Actor;
// struct MyActor;
struct MyActor;
// struct Num(usize);
// impl actix::Message for Num {
// type Result = usize;
// }
// impl actix::Actor for MyActor {
// type Context = actix::Context<Self>;
// }
// impl actix::Handler<Num> for MyActor {
// type Result = usize;
// fn handle(&mut self, msg: Num, _: &mut Self::Context) -> Self::Result {
// msg.0
// }
// }
struct Num(usize);
impl actix::Message for Num {
type Result = usize;
}
impl actix::Actor for MyActor {
type Context = actix::Context<Self>;
}
impl actix::Handler<Num> for MyActor {
type Result = usize;
fn handle(&mut self, msg: Num, _: &mut Self::Context) -> Self::Result {
msg.0
}
}
// let addr = run_on(|| MyActor.start());
// let mut app = init_service(App::new().service(
// web::resource("/index.html").to(move || {
// addr.send(Num(1)).from_err().and_then(|res| {
// if res == 1 {
// HttpResponse::Ok()
// } else {
// HttpResponse::BadRequest()
// }
// })
// }),
// ));
let addr = MyActor.start();
// let req = TestRequest::post().uri("/index.html").to_request();
// let res = block_fn(|| app.call(req)).unwrap();
// assert!(res.status().is_success());
// }
let mut app = init_service(App::new().service(web::resource("/index.html").to(
move || {
addr.send(Num(1)).map(|res| match res {
Ok(res) => {
if res == 1 {
Ok(HttpResponse::Ok())
} else {
Ok(HttpResponse::BadRequest())
}
}
Err(err) => Err(err),
})
},
)))
.await;
let req = TestRequest::post().uri("/index.html").to_request();
let res = app.call(req).await.unwrap();
assert!(res.status().is_success());
}
}

View File

@ -14,6 +14,7 @@ use futures::StreamExt;
use serde::de::DeserializeOwned;
use serde::Serialize;
#[cfg(feature = "compress")]
use crate::dev::Decompress;
use crate::error::UrlencodedError;
use crate::extract::FromRequest;
@ -189,7 +190,7 @@ impl<T: Serialize> Responder for Form<T> {
/// let app = App::new().service(
/// web::resource("/index.html")
/// // change `Form` extractor configuration
/// .data(
/// .app_data(
/// web::Form::<FormData>::configure(|cfg| cfg.limit(4097))
/// )
/// .route(web::get().to(index))
@ -240,7 +241,10 @@ impl Default for FormConfig {
/// * content-length is greater than 32k
///
pub struct UrlEncoded<U> {
#[cfg(feature = "compress")]
stream: Option<Decompress<Payload>>,
#[cfg(not(feature = "compress"))]
stream: Option<Payload>,
limit: usize,
length: Option<usize>,
encoding: &'static Encoding,
@ -273,7 +277,11 @@ impl<U> UrlEncoded<U> {
}
};
#[cfg(feature = "compress")]
let payload = Decompress::from_headers(payload.take(), req.headers());
#[cfg(not(feature = "compress"))]
let payload = payload.take();
UrlEncoded {
encoding,
stream: Some(payload),

View File

@ -16,6 +16,7 @@ use serde_json;
use actix_http::http::{header::CONTENT_LENGTH, StatusCode};
use actix_http::{HttpMessage, Payload, Response};
#[cfg(feature = "compress")]
use crate::dev::Decompress;
use crate::error::{Error, JsonPayloadError};
use crate::extract::FromRequest;
@ -223,17 +224,18 @@ where
///
/// fn main() {
/// let app = App::new().service(
/// web::resource("/index.html").data(
/// // change json extractor configuration
/// web::Json::<Info>::configure(|cfg| {
/// cfg.limit(4096)
/// .content_type(|mime| { // <- accept text/plain content type
/// mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
/// })
/// .error_handler(|err, req| { // <- create custom error response
/// error::InternalError::from_response(
/// err, HttpResponse::Conflict().finish()).into()
/// })
/// web::resource("/index.html")
/// .app_data(
/// // change json extractor configuration
/// web::Json::<Info>::configure(|cfg| {
/// cfg.limit(4096)
/// .content_type(|mime| { // <- accept text/plain content type
/// mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
/// })
/// .error_handler(|err, req| { // <- create custom error response
/// error::InternalError::from_response(
/// err, HttpResponse::Conflict().finish()).into()
/// })
/// }))
/// .route(web::post().to(index))
/// );
@ -293,7 +295,10 @@ impl Default for JsonConfig {
pub struct JsonBody<U> {
limit: usize,
length: Option<usize>,
#[cfg(feature = "compress")]
stream: Option<Decompress<Payload>>,
#[cfg(not(feature = "compress"))]
stream: Option<Payload>,
err: Option<JsonPayloadError>,
fut: Option<LocalBoxFuture<'static, Result<U, JsonPayloadError>>>,
}
@ -332,7 +337,11 @@ where
.get(&CONTENT_LENGTH)
.and_then(|l| l.to_str().ok())
.and_then(|s| s.parse::<usize>().ok());
#[cfg(feature = "compress")]
let payload = Decompress::from_headers(payload.take(), req.headers());
#[cfg(not(feature = "compress"))]
let payload = payload.take();
JsonBody {
limit: 262_144,
@ -454,7 +463,7 @@ mod tests {
header::HeaderValue::from_static("16"),
)
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.data(JsonConfig::default().limit(10).error_handler(|err, _| {
.app_data(JsonConfig::default().limit(10).error_handler(|err, _| {
let msg = MyObject {
name: "invalid request".to_string(),
};
@ -506,7 +515,7 @@ mod tests {
header::HeaderValue::from_static("16"),
)
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.data(JsonConfig::default().limit(10))
.app_data(JsonConfig::default().limit(10))
.to_http_parts();
let s = Json::<MyObject>::from_request(&req, &mut pl).await;
@ -523,7 +532,7 @@ mod tests {
header::HeaderValue::from_static("16"),
)
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.data(
.app_data(
JsonConfig::default()
.limit(10)
.error_handler(|_, _| JsonPayloadError::ContentType.into()),
@ -596,7 +605,7 @@ mod tests {
header::HeaderValue::from_static("16"),
)
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.data(JsonConfig::default().limit(4096))
.app_data(JsonConfig::default().limit(4096))
.to_http_parts();
let s = Json::<MyObject>::from_request(&req, &mut pl).await;
@ -614,7 +623,7 @@ mod tests {
header::HeaderValue::from_static("16"),
)
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.data(JsonConfig::default().content_type(|mime: mime::Mime| {
.app_data(JsonConfig::default().content_type(|mime: mime::Mime| {
mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
}))
.to_http_parts();
@ -634,7 +643,7 @@ mod tests {
header::HeaderValue::from_static("16"),
)
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.data(JsonConfig::default().content_type(|mime: mime::Mime| {
.app_data(JsonConfig::default().content_type(|mime: mime::Mime| {
mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
}))
.to_http_parts();

View File

@ -15,6 +15,8 @@ use crate::FromRequest;
#[derive(PartialEq, Eq, PartialOrd, Ord)]
/// Extract typed information from the request's path.
///
/// [**PathConfig**](struct.PathConfig.html) allows to configure extraction process.
///
/// ## Example
///
/// ```rust
@ -212,7 +214,7 @@ where
/// fn main() {
/// let app = App::new().service(
/// web::resource("/messages/{folder}")
/// .data(PathConfig::default().error_handler(|err, req| {
/// .app_data(PathConfig::default().error_handler(|err, req| {
/// error::InternalError::from_response(
/// err,
/// HttpResponse::Conflict().finish(),
@ -358,7 +360,7 @@ mod tests {
#[actix_rt::test]
async fn test_custom_err_handler() {
let (req, mut pl) = TestRequest::with_uri("/name/user1/")
.data(PathConfig::default().error_handler(|err, _| {
.app_data(PathConfig::default().error_handler(|err, _| {
error::InternalError::from_response(
err,
HttpResponse::Conflict().finish(),

View File

@ -176,7 +176,7 @@ impl FromRequest for Bytes {
/// fn main() {
/// let app = App::new().service(
/// web::resource("/index.html")
/// .data(String::configure(|cfg| { // <- limit size of the payload
/// .app_data(String::configure(|cfg| { // <- limit size of the payload
/// cfg.limit(4096)
/// }))
/// .route(web::get().to(index)) // <- register handler with extractor params
@ -301,7 +301,10 @@ impl Default for PayloadConfig {
pub struct HttpMessageBody {
limit: usize,
length: Option<usize>,
#[cfg(feature = "compress")]
stream: Option<dev::Decompress<dev::Payload>>,
#[cfg(not(feature = "compress"))]
stream: Option<dev::Payload>,
err: Option<PayloadError>,
fut: Option<LocalBoxFuture<'static, Result<Bytes, PayloadError>>>,
}
@ -322,8 +325,13 @@ impl HttpMessageBody {
}
}
#[cfg(feature = "compress")]
let stream = Some(dev::Decompress::from_headers(payload.take(), req.headers()));
#[cfg(not(feature = "compress"))]
let stream = Some(payload.take());
HttpMessageBody {
stream: Some(dev::Decompress::from_headers(payload.take(), req.headers())),
stream,
limit: 262_144,
length: len,
fut: None,

View File

@ -19,6 +19,8 @@ use crate::request::HttpRequest;
/// be decoded into any type which depends upon data ordering e.g. tuples or tuple-structs.
/// Attempts to do so will *fail at runtime*.
///
/// [**QueryConfig**](struct.QueryConfig.html) allows to configure extraction process.
///
/// ## Example
///
/// ```rust
@ -185,7 +187,7 @@ where
///
/// fn main() {
/// let app = App::new().service(
/// web::resource("/index.html").data(
/// web::resource("/index.html").app_data(
/// // change query extractor configuration
/// web::Query::<Info>::configure(|cfg| {
/// cfg.error_handler(|err, req| { // <- create custom error response
@ -273,7 +275,7 @@ mod tests {
#[actix_rt::test]
async fn test_custom_error_responder() {
let req = TestRequest::with_uri("/name/user1/")
.data(QueryConfig::default().error_handler(|e, _| {
.app_data(QueryConfig::default().error_handler(|e, _| {
let resp = HttpResponse::UnprocessableEntity().finish();
InternalError::from_response(e, resp).into()
}))

View File

@ -1,5 +1,12 @@
# Changes
## [1.0.0] - 2019-12-13
### Changed
* Replaced `TestServer::start()` with `test_server()`
## [1.0.0-alpha.3] - 2019-12-07
### Changed

View File

@ -40,7 +40,7 @@ actix-testing = "1.0.0"
awc = "1.0.0"
base64 = "0.11"
bytes = "0.5.2"
bytes = "0.5.3"
futures = "0.3.1"
http = "0.2.0"
log = "0.4"
@ -55,5 +55,5 @@ time = "0.1"
open-ssl = { version="0.10", package="openssl", optional = true }
[dev-dependencies]
actix-web = "2.0.0-alpha.4"
actix-http = "1.0.0"
actix-web = "2.0.0-rc"
actix-http = "1.0.1"

View File

@ -5,8 +5,7 @@ use std::{net, thread, time::Duration};
#[cfg(feature = "openssl")]
use open_ssl::ssl::SslAcceptorBuilder;
use actix_http::Response;
use actix_web::{web, App, HttpServer};
use actix_web::{web, App, HttpResponse, HttpServer};
fn unused_addr() -> net::SocketAddr {
let addr: net::SocketAddr = "127.0.0.1:0".parse().unwrap();
@ -28,7 +27,7 @@ async fn test_start() {
let srv = HttpServer::new(|| {
App::new().service(
web::resource("/").route(web::to(|| Response::Ok().body("test"))),
web::resource("/").route(web::to(|| HttpResponse::Ok().body("test"))),
)
})
.workers(1)
@ -91,6 +90,8 @@ fn ssl_acceptor() -> std::io::Result<SslAcceptorBuilder> {
#[actix_rt::test]
#[cfg(feature = "openssl")]
async fn test_start_ssl() {
use actix_web::HttpRequest;
let addr = unused_addr();
let (tx, rx) = mpsc::channel();
@ -99,9 +100,10 @@ async fn test_start_ssl() {
let builder = ssl_acceptor().unwrap();
let srv = HttpServer::new(|| {
App::new().service(
web::resource("/").route(web::to(|| Response::Ok().body("test"))),
)
App::new().service(web::resource("/").route(web::to(|req: HttpRequest| {
assert!(req.app_config().secure());
HttpResponse::Ok().body("test")
})))
})
.workers(1)
.shutdown_timeout(1)

View File

@ -1,19 +1,22 @@
use std::io::{Read, Write};
use std::pin::Pin;
use std::task::{Context, Poll};
use actix_http::http::header::{
ContentEncoding, ACCEPT_ENCODING, CONTENT_ENCODING, CONTENT_LENGTH,
TRANSFER_ENCODING,
};
use brotli::{CompressorWriter, DecompressorWriter};
use brotli2::write::{BrotliDecoder, BrotliEncoder};
use bytes::Bytes;
use flate2::read::GzDecoder;
use flate2::write::{GzEncoder, ZlibDecoder, ZlibEncoder};
use flate2::Compression;
use futures::{future::ok, stream::once};
use futures::{ready, Future};
use rand::{distributions::Alphanumeric, Rng};
use actix_web::middleware::{BodyEncoding, Compress};
use actix_web::{dev, http, test, web, App, Error, HttpResponse};
use actix_web::dev::BodyEncoding;
use actix_web::middleware::Compress;
use actix_web::{dev, test, web, App, Error, HttpResponse};
const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
Hello World Hello World Hello World Hello World Hello World \
@ -37,6 +40,42 @@ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
Hello World Hello World Hello World Hello World Hello World \
Hello World Hello World Hello World Hello World Hello World";
struct TestBody {
data: Bytes,
chunk_size: usize,
delay: actix_rt::time::Delay,
}
impl TestBody {
fn new(data: Bytes, chunk_size: usize) -> Self {
TestBody {
data,
chunk_size,
delay: actix_rt::time::delay_for(std::time::Duration::from_millis(10)),
}
}
}
impl futures::Stream for TestBody {
type Item = Result<Bytes, Error>;
fn poll_next(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
ready!(Pin::new(&mut self.delay).poll(cx));
self.delay = actix_rt::time::delay_for(std::time::Duration::from_millis(10));
let chunk_size = std::cmp::min(self.chunk_size, self.data.len());
let chunk = self.data.split_to(chunk_size);
if chunk.is_empty() {
Poll::Ready(None)
} else {
Poll::Ready(Some(Ok(chunk)))
}
}
}
#[actix_rt::test]
async fn test_body() {
let srv = test::start(|| {
@ -247,7 +286,7 @@ async fn test_body_chunked_implicit() {
.wrap(Compress::new(ContentEncoding::Gzip))
.service(web::resource("/").route(web::get().to(move || {
HttpResponse::Ok()
.streaming(once(ok::<_, Error>(Bytes::from_static(STR.as_ref()))))
.streaming(TestBody::new(Bytes::from_static(STR.as_ref()), 24))
})))
});
@ -280,7 +319,7 @@ async fn test_body_br_streaming() {
App::new().wrap(Compress::new(ContentEncoding::Br)).service(
web::resource("/").route(web::to(move || {
HttpResponse::Ok()
.streaming(once(ok::<_, Error>(Bytes::from_static(STR.as_ref()))))
.streaming(TestBody::new(Bytes::from_static(STR.as_ref()), 24))
})),
)
});
@ -296,11 +335,13 @@ async fn test_body_br_streaming() {
// read response
let bytes = response.body().await.unwrap();
println!("TEST: {:?}", bytes.len());
// decode br
let mut e = DecompressorWriter::new(Vec::with_capacity(2048), 0);
let mut e = BrotliDecoder::new(Vec::with_capacity(2048));
e.write_all(bytes.as_ref()).unwrap();
let dec = e.into_inner().unwrap();
let dec = e.finish().unwrap();
println!("T: {:?}", Bytes::copy_from_slice(&dec));
assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref()));
}
@ -332,7 +373,7 @@ async fn test_no_chunking() {
HttpResponse::Ok()
.no_chunking()
.content_length(STR.len() as u64)
.streaming(once(ok::<_, Error>(Bytes::from_static(STR.as_ref()))))
.streaming(TestBody::new(Bytes::from_static(STR.as_ref()), 24))
})))
});
@ -396,9 +437,9 @@ async fn test_body_brotli() {
let bytes = response.body().await.unwrap();
// decode brotli
let mut e = DecompressorWriter::new(Vec::with_capacity(2048), 0);
let mut e = BrotliDecoder::new(Vec::with_capacity(2048));
e.write_all(bytes.as_ref()).unwrap();
let dec = e.into_inner().unwrap();
let dec = e.finish().unwrap();
assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref()));
}
@ -607,9 +648,9 @@ async fn test_brotli_encoding() {
)
});
let mut e = CompressorWriter::new(Vec::new(), 0, 3, 0);
let mut e = BrotliEncoder::new(Vec::new(), 5);
e.write_all(STR.as_ref()).unwrap();
let enc = e.into_inner();
let enc = e.finish().unwrap();
// client request
let request = srv
@ -626,17 +667,24 @@ async fn test_brotli_encoding() {
#[actix_rt::test]
async fn test_brotli_encoding_large() {
let data = STR.repeat(10);
let data = rand::thread_rng()
.sample_iter(&Alphanumeric)
.take(320_000)
.collect::<String>();
let srv = test::start_with(test::config().h1(), || {
App::new().service(
web::resource("/")
.route(web::to(move |body: Bytes| HttpResponse::Ok().body(body))),
.app_data(web::PayloadConfig::new(320_000))
.route(web::to(move |body: Bytes| {
HttpResponse::Ok().streaming(TestBody::new(body, 10240))
})),
)
});
let mut e = CompressorWriter::new(Vec::new(), 0, 3, 0);
let mut e = BrotliEncoder::new(Vec::new(), 5);
e.write_all(data.as_ref()).unwrap();
let enc = e.into_inner();
let enc = e.finish().unwrap();
// client request
let request = srv
@ -647,7 +695,7 @@ async fn test_brotli_encoding_large() {
assert!(response.status().is_success());
// read response
let bytes = response.body().await.unwrap();
let bytes = response.body().limit(320_000).await.unwrap();
assert_eq!(bytes, Bytes::from(data));
}
@ -668,20 +716,20 @@ async fn test_brotli_encoding_large_openssl() {
let srv = test::start_with(test::config().openssl(builder.build()), move || {
App::new().service(web::resource("/").route(web::to(|bytes: Bytes| {
HttpResponse::Ok()
.encoding(http::ContentEncoding::Identity)
.encoding(actix_web::http::ContentEncoding::Identity)
.body(bytes)
})))
});
// body
let mut e = CompressorWriter::new(Vec::new(), 0, 3, 0);
let mut e = BrotliEncoder::new(Vec::new(), 3);
e.write_all(data.as_ref()).unwrap();
let enc = e.into_inner();
let enc = e.finish().unwrap();
// client request
let mut response = srv
.post("/")
.header(http::header::CONTENT_ENCODING, "br")
.header(actix_web::http::header::CONTENT_ENCODING, "br")
.send_body(enc)
.await
.unwrap();
@ -716,7 +764,7 @@ async fn test_reading_deflate_encoding_large_random_rustls() {
let srv = test::start_with(test::config().rustls(config), || {
App::new().service(web::resource("/").route(web::to(|bytes: Bytes| {
HttpResponse::Ok()
.encoding(http::ContentEncoding::Identity)
.encoding(actix_web::http::ContentEncoding::Identity)
.body(bytes)
})))
});
@ -729,8 +777,8 @@ async fn test_reading_deflate_encoding_large_random_rustls() {
// client request
let req = srv
.post("/")
.header(http::header::CONTENT_ENCODING, "deflate")
.send_body(enc);
.header(actix_web::http::header::CONTENT_ENCODING, "deflate")
.send_stream(TestBody::new(Bytes::from(enc), 1024));
let mut response = req.await.unwrap();
assert!(response.status().is_success());
@ -741,93 +789,6 @@ async fn test_reading_deflate_encoding_large_random_rustls() {
assert_eq!(bytes, Bytes::from(data));
}
// #[cfg(all(feature = "tls", feature = "ssl"))]
// #[test]
// fn test_reading_deflate_encoding_large_random_nativetls() {
// use native_tls::{Identity, TlsAcceptor};
// use openssl::ssl::{
// SslAcceptor, SslConnector, SslFiletype, SslMethod, SslVerifyMode,
// };
// use std::fs::File;
// use std::sync::mpsc;
// use actix::{Actor, System};
// let (tx, rx) = mpsc::channel();
// // load ssl keys
// let mut file = File::open("tests/identity.pfx").unwrap();
// let mut identity = vec![];
// file.read_to_end(&mut identity).unwrap();
// let identity = Identity::from_pkcs12(&identity, "1").unwrap();
// let acceptor = TlsAcceptor::new(identity).unwrap();
// // load ssl keys
// let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
// builder
// .set_private_key_file("tests/key.pem", SslFiletype::PEM)
// .unwrap();
// builder
// .set_certificate_chain_file("tests/cert.pem")
// .unwrap();
// let data = rand::thread_rng()
// .sample_iter(&Alphanumeric)
// .take(160_000)
// .collect::<String>();
// let addr = test::TestServer::unused_addr();
// thread::spawn(move || {
// System::run(move || {
// server::new(|| {
// App::new().handler("/", |req: &HttpRequest| {
// req.body()
// .and_then(|bytes: Bytes| {
// Ok(HttpResponse::Ok()
// .content_encoding(http::ContentEncoding::Identity)
// .body(bytes))
// })
// .responder()
// })
// })
// .bind_tls(addr, acceptor)
// .unwrap()
// .start();
// let _ = tx.send(System::current());
// });
// });
// let sys = rx.recv().unwrap();
// let mut rt = System::new("test");
// // client connector
// let mut builder = SslConnector::builder(SslMethod::tls()).unwrap();
// builder.set_verify(SslVerifyMode::NONE);
// let conn = client::ClientConnector::with_connector(builder.build()).start();
// // encode data
// let mut e = ZlibEncoder::new(Vec::new(), Compression::default());
// e.write_all(data.as_ref()).unwrap();
// let enc = e.finish().unwrap();
// // client request
// let request = client::ClientRequest::build()
// .uri(format!("https://{}/", addr))
// .method(http::Method::POST)
// .header(http::header::CONTENT_ENCODING, "deflate")
// .with_connector(conn)
// .body(enc)
// .unwrap();
// let response = rt.block_on(request.send()).unwrap();
// assert!(response.status().is_success());
// // read response
// let bytes = rt.block_on(response.body()).unwrap();
// assert_eq!(bytes.len(), data.len());
// assert_eq!(bytes, Bytes::from(data));
// let _ = sys.stop();
// }
// #[test]
// fn test_server_cookies() {
// use actix_web::http;