1
0
mirror of https://github.com/fafhrd91/actix-web synced 2025-01-18 05:41:50 +01:00

update to latest actix-net

This commit is contained in:
Nikolay Kim 2019-12-02 17:33:11 +06:00
parent 33574403b5
commit f4c01384ec
33 changed files with 941 additions and 898 deletions

View File

@ -63,7 +63,7 @@ secure-cookies = ["actix-http/secure-cookies"]
fail = ["actix-http/fail"] fail = ["actix-http/fail"]
# openssl # openssl
openssl = ["open-ssl", "actix-server/openssl", "awc/openssl"] openssl = ["open-ssl", "actix-tls/openssl", "awc/openssl"]
# rustls # rustls
# rustls = ["rust-tls", "actix-server/rustls", "awc/rustls"] # rustls = ["rust-tls", "actix-server/rustls", "awc/rustls"]
@ -76,10 +76,11 @@ actix-router = "0.1.5"
actix-rt = "1.0.0-alpha.1" actix-rt = "1.0.0-alpha.1"
actix-web-codegen = "0.2.0-alpha.1" actix-web-codegen = "0.2.0-alpha.1"
actix-http = "0.3.0-alpha.1" actix-http = "0.3.0-alpha.1"
actix-server = "0.8.0-alpha.1" actix-server = "0.8.0-alpha.2"
actix-server-config = "0.3.0-alpha.1"
actix-testing = "0.3.0-alpha.1" actix-testing = "0.3.0-alpha.1"
actix-threadpool = "0.2.0-alpha.1" actix-threadpool = "0.2.0-alpha.1"
#actix-tls = "0.1.0-alpha.1"
actix-tls = { git = "https://github.com/actix/actix-net.git", optional = true }
awc = { version = "0.3.0-alpha.1", optional = true } awc = { version = "0.3.0-alpha.1", optional = true }
bytes = "0.4" bytes = "0.4"
@ -123,7 +124,6 @@ actix-web = { path = "." }
actix-http = { path = "actix-http" } actix-http = { path = "actix-http" }
actix-http-test = { path = "test-server" } actix-http-test = { path = "test-server" }
actix-web-codegen = { path = "actix-web-codegen" } actix-web-codegen = { path = "actix-web-codegen" }
# actix-web-actors = { path = "actix-web-actors" }
actix-cors = { path = "actix-cors" } actix-cors = { path = "actix-cors" }
actix-identity = { path = "actix-identity" } actix-identity = { path = "actix-identity" }
actix-session = { path = "actix-session" } actix-session = { path = "actix-session" }
@ -136,7 +136,7 @@ actix-connect = { git = "https://github.com/actix/actix-net.git" }
actix-rt = { git = "https://github.com/actix/actix-net.git" } actix-rt = { git = "https://github.com/actix/actix-net.git" }
actix-macros = { git = "https://github.com/actix/actix-net.git" } actix-macros = { git = "https://github.com/actix/actix-net.git" }
actix-server = { git = "https://github.com/actix/actix-net.git" } actix-server = { git = "https://github.com/actix/actix-net.git" }
actix-server-config = { git = "https://github.com/actix/actix-net.git" }
actix-service = { git = "https://github.com/actix/actix-net.git" } actix-service = { git = "https://github.com/actix/actix-net.git" }
actix-testing = { git = "https://github.com/actix/actix-net.git" } actix-testing = { git = "https://github.com/actix/actix-net.git" }
actix-tls = { git = "https://github.com/actix/actix-net.git" }
actix-utils = { git = "https://github.com/actix/actix-net.git" } actix-utils = { git = "https://github.com/actix/actix-net.git" }

View File

@ -25,7 +25,6 @@ actix-service = "1.0.0-alpha.1"
actix-router = "0.1.2" actix-router = "0.1.2"
actix-rt = "1.0.0-alpha.1" actix-rt = "1.0.0-alpha.1"
actix-http = "0.3.0-alpha.1" actix-http = "0.3.0-alpha.1"
actix-server-config = "0.3.0-alpha.1"
bytes = "0.4" bytes = "0.4"
futures = "0.3.1" futures = "0.3.1"
@ -33,7 +32,7 @@ pin-project = "0.4.6"
log = "0.4" log = "0.4"
[dev-dependencies] [dev-dependencies]
actix-server = { version = "0.8.0-alpha.1", features=["openssl"] } actix-server = { version = "0.8.0-alpha.1" }
actix-connect = { version = "0.3.0-alpha.1", features=["openssl"] } actix-connect = { version = "0.3.0-alpha.1", features=["openssl"] }
actix-http-test = { version = "0.3.0-alpha.1", features=["openssl"] } actix-http-test = { version = "0.3.0-alpha.1", features=["openssl"] }
actix-utils = "0.5.0-alpha.1" actix-utils = "0.5.0-alpha.1"

View File

@ -7,7 +7,6 @@ use actix_codec::{AsyncRead, AsyncWrite, Framed};
use actix_http::h1::{Codec, SendResponse}; use actix_http::h1::{Codec, SendResponse};
use actix_http::{Error, Request, Response}; use actix_http::{Error, Request, Response};
use actix_router::{Path, Router, Url}; use actix_router::{Path, Router, Url};
use actix_server_config::ServerConfig;
use actix_service::{IntoServiceFactory, Service, ServiceFactory}; use actix_service::{IntoServiceFactory, Service, ServiceFactory};
use futures::future::{ok, FutureExt, LocalBoxFuture}; use futures::future::{ok, FutureExt, LocalBoxFuture};
@ -97,7 +96,7 @@ where
T: AsyncRead + AsyncWrite + Unpin + 'static, T: AsyncRead + AsyncWrite + Unpin + 'static,
S: 'static, S: 'static,
{ {
type Config = ServerConfig; type Config = ();
type Request = (Request, Framed<T, Codec>); type Request = (Request, Framed<T, Codec>);
type Response = (); type Response = ();
type Error = Error; type Error = Error;
@ -105,7 +104,7 @@ where
type Service = FramedAppService<T, S>; type Service = FramedAppService<T, S>;
type Future = CreateService<T, S>; type Future = CreateService<T, S>;
fn new_service(&self, _: &ServerConfig) -> Self::Future { fn new_service(&self, _: &()) -> Self::Future {
CreateService { CreateService {
fut: self fut: self
.services .services

View File

@ -46,6 +46,7 @@ async fn test_simple() {
FramedApp::new().service(FramedRoute::get("/index.html").to(ws_service)), FramedApp::new().service(FramedRoute::get("/index.html").to(ws_service)),
) )
.finish(|_| future::ok::<_, Error>(Response::NotFound())) .finish(|_| future::ok::<_, Error>(Response::NotFound()))
.tcp()
}); });
assert!(srv.ws_at("/test").await.is_err()); assert!(srv.ws_at("/test").await.is_err());

View File

@ -26,7 +26,7 @@ path = "src/lib.rs"
default = [] default = []
# openssl # openssl
openssl = ["open-ssl", "actix-connect/openssl", "tokio-openssl"] openssl = ["open-ssl", "actix-tls/openssl", "actix-connect/openssl", "tokio-openssl"]
# rustls support # rustls support
# rustls = ["rust-tls", "webpki-roots", "actix-connect/rustls"] # rustls = ["rust-tls", "webpki-roots", "actix-connect/rustls"]
@ -51,9 +51,9 @@ actix-service = "1.0.0-alpha.1"
actix-codec = "0.2.0-alpha.1" actix-codec = "0.2.0-alpha.1"
actix-connect = "1.0.0-alpha.1" actix-connect = "1.0.0-alpha.1"
actix-utils = "0.5.0-alpha.1" actix-utils = "0.5.0-alpha.1"
actix-server-config = "0.3.0-alpha.1"
actix-rt = "1.0.0-alpha.1" actix-rt = "1.0.0-alpha.1"
actix-threadpool = "0.2.0-alpha.1" actix-threadpool = "0.2.0-alpha.1"
actix-tls = { git = "https://github.com/actix/actix-net.git", optional = true }
base64 = "0.10" base64 = "0.10"
bitflags = "1.0" bitflags = "1.0"
@ -103,10 +103,11 @@ tokio-openssl = { version = "0.4.0-alpha.6", optional = true }
# webpki-roots = { version = "0.18", optional = true } # webpki-roots = { version = "0.18", optional = true }
[dev-dependencies] [dev-dependencies]
#actix-server = { version = "0.8.0-alpha.1", features=["openssl", "rustls"] } actix-server = { version = "0.8.0-alpha.1" }
actix-server = { version = "0.8.0-alpha.1", features=["openssl"] }
actix-connect = { version = "1.0.0-alpha.1", features=["openssl"] } actix-connect = { version = "1.0.0-alpha.1", features=["openssl"] }
actix-http-test = { version = "0.3.0-alpha.1", features=["openssl"] } actix-http-test = { version = "0.3.0-alpha.1", features=["openssl"] }
#actix-tls = { version = "0.1.0-alpha.1", features=["openssl"] }
actix-tls = { git = "https://github.com/actix/actix-net.git", features=["openssl"] }
env_logger = "0.6" env_logger = "0.6"
serde_derive = "1.0" serde_derive = "1.0"
open-ssl = { version="0.10", package="openssl" } open-ssl = { version="0.10", package="openssl" }

View File

@ -34,6 +34,7 @@ fn main() -> io::Result<()> {
) )
} }
}) })
.tcp()
})? })?
.run() .run()
} }

View File

@ -25,7 +25,7 @@ fn main() -> io::Result<()> {
Server::build() Server::build()
.bind("echo", "127.0.0.1:8080", || { .bind("echo", "127.0.0.1:8080", || {
HttpService::build().finish(handle_request) HttpService::build().finish(handle_request).tcp()
})? })?
.run() .run()
} }

View File

@ -21,6 +21,7 @@ fn main() -> io::Result<()> {
res.header("x-head", HeaderValue::from_static("dummy value!")); res.header("x-head", HeaderValue::from_static("dummy value!"));
future::ok::<_, ()>(res.body("Hello world!")) future::ok::<_, ()>(res.body("Hello world!"))
}) })
.tcp()
})? })?
.run() .run()
} }

View File

@ -1,9 +1,8 @@
use std::fmt;
use std::marker::PhantomData; use std::marker::PhantomData;
use std::rc::Rc; use std::rc::Rc;
use std::{fmt, net};
use actix_codec::Framed; use actix_codec::Framed;
use actix_server_config::ServerConfig as SrvConfig;
use actix_service::{IntoServiceFactory, Service, ServiceFactory}; use actix_service::{IntoServiceFactory, Service, ServiceFactory};
use crate::body::MessageBody; use crate::body::MessageBody;
@ -24,6 +23,8 @@ pub struct HttpServiceBuilder<T, S, X = ExpectHandler, U = UpgradeHandler<T>> {
keep_alive: KeepAlive, keep_alive: KeepAlive,
client_timeout: u64, client_timeout: u64,
client_disconnect: u64, client_disconnect: u64,
secure: bool,
local_addr: Option<net::SocketAddr>,
expect: X, expect: X,
upgrade: Option<U>, upgrade: Option<U>,
on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>, on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
@ -32,7 +33,7 @@ pub struct HttpServiceBuilder<T, S, X = ExpectHandler, U = UpgradeHandler<T>> {
impl<T, S> HttpServiceBuilder<T, S, ExpectHandler, UpgradeHandler<T>> impl<T, S> HttpServiceBuilder<T, S, ExpectHandler, UpgradeHandler<T>>
where where
S: ServiceFactory<Config = SrvConfig, Request = Request>, S: ServiceFactory<Config = (), Request = Request>,
S::Error: Into<Error> + 'static, S::Error: Into<Error> + 'static,
S::InitError: fmt::Debug, S::InitError: fmt::Debug,
<S::Service as Service>::Future: 'static, <S::Service as Service>::Future: 'static,
@ -43,6 +44,8 @@ where
keep_alive: KeepAlive::Timeout(5), keep_alive: KeepAlive::Timeout(5),
client_timeout: 5000, client_timeout: 5000,
client_disconnect: 0, client_disconnect: 0,
secure: false,
local_addr: None,
expect: ExpectHandler, expect: ExpectHandler,
upgrade: None, upgrade: None,
on_connect: None, on_connect: None,
@ -53,19 +56,15 @@ where
impl<T, S, X, U> HttpServiceBuilder<T, S, X, U> impl<T, S, X, U> HttpServiceBuilder<T, S, X, U>
where where
S: ServiceFactory<Config = SrvConfig, Request = Request>, S: ServiceFactory<Config = (), Request = Request>,
S::Error: Into<Error> + 'static, S::Error: Into<Error> + 'static,
S::InitError: fmt::Debug, S::InitError: fmt::Debug,
<S::Service as Service>::Future: 'static, <S::Service as Service>::Future: 'static,
X: ServiceFactory<Config = SrvConfig, Request = Request, Response = Request>, X: ServiceFactory<Config = (), Request = Request, Response = Request>,
X::Error: Into<Error>, X::Error: Into<Error>,
X::InitError: fmt::Debug, X::InitError: fmt::Debug,
<X::Service as Service>::Future: 'static, <X::Service as Service>::Future: 'static,
U: ServiceFactory< U: ServiceFactory<Config = (), Request = (Request, Framed<T, Codec>), Response = ()>,
Config = SrvConfig,
Request = (Request, Framed<T, Codec>),
Response = (),
>,
U::Error: fmt::Display, U::Error: fmt::Display,
U::InitError: fmt::Debug, U::InitError: fmt::Debug,
<U::Service as Service>::Future: 'static, <U::Service as Service>::Future: 'static,
@ -78,6 +77,18 @@ where
self self
} }
/// Set connection secure state
pub fn secure(mut self) -> Self {
self.secure = true;
self
}
/// Set the local address that this service is bound to.
pub fn local_addr(mut self, addr: net::SocketAddr) -> Self {
self.local_addr = Some(addr);
self
}
/// Set server client timeout in milliseconds for first request. /// Set server client timeout in milliseconds for first request.
/// ///
/// Defines a timeout for reading client request header. If a client does not transmit /// Defines a timeout for reading client request header. If a client does not transmit
@ -113,7 +124,7 @@ where
pub fn expect<F, X1>(self, expect: F) -> HttpServiceBuilder<T, S, X1, U> pub fn expect<F, X1>(self, expect: F) -> HttpServiceBuilder<T, S, X1, U>
where where
F: IntoServiceFactory<X1>, F: IntoServiceFactory<X1>,
X1: ServiceFactory<Config = SrvConfig, Request = Request, Response = Request>, X1: ServiceFactory<Config = (), Request = Request, Response = Request>,
X1::Error: Into<Error>, X1::Error: Into<Error>,
X1::InitError: fmt::Debug, X1::InitError: fmt::Debug,
<X1::Service as Service>::Future: 'static, <X1::Service as Service>::Future: 'static,
@ -122,6 +133,8 @@ where
keep_alive: self.keep_alive, keep_alive: self.keep_alive,
client_timeout: self.client_timeout, client_timeout: self.client_timeout,
client_disconnect: self.client_disconnect, client_disconnect: self.client_disconnect,
secure: self.secure,
local_addr: self.local_addr,
expect: expect.into_factory(), expect: expect.into_factory(),
upgrade: self.upgrade, upgrade: self.upgrade,
on_connect: self.on_connect, on_connect: self.on_connect,
@ -137,7 +150,7 @@ where
where where
F: IntoServiceFactory<U1>, F: IntoServiceFactory<U1>,
U1: ServiceFactory< U1: ServiceFactory<
Config = SrvConfig, Config = (),
Request = (Request, Framed<T, Codec>), Request = (Request, Framed<T, Codec>),
Response = (), Response = (),
>, >,
@ -149,6 +162,8 @@ where
keep_alive: self.keep_alive, keep_alive: self.keep_alive,
client_timeout: self.client_timeout, client_timeout: self.client_timeout,
client_disconnect: self.client_disconnect, client_disconnect: self.client_disconnect,
secure: self.secure,
local_addr: self.local_addr,
expect: self.expect, expect: self.expect,
upgrade: Some(upgrade.into_factory()), upgrade: Some(upgrade.into_factory()),
on_connect: self.on_connect, on_connect: self.on_connect,
@ -170,7 +185,7 @@ where
} }
/// Finish service configuration and create *http service* for HTTP/1 protocol. /// Finish service configuration and create *http service* for HTTP/1 protocol.
pub fn h1<F, P, B>(self, service: F) -> H1Service<T, P, S, B, X, U> pub fn h1<F, B>(self, service: F) -> H1Service<T, S, B, X, U>
where where
B: MessageBody, B: MessageBody,
F: IntoServiceFactory<S>, F: IntoServiceFactory<S>,
@ -182,6 +197,8 @@ where
self.keep_alive, self.keep_alive,
self.client_timeout, self.client_timeout,
self.client_disconnect, self.client_disconnect,
self.secure,
self.local_addr,
); );
H1Service::with_config(cfg, service.into_factory()) H1Service::with_config(cfg, service.into_factory())
.expect(self.expect) .expect(self.expect)
@ -190,7 +207,7 @@ where
} }
/// Finish service configuration and create *http service* for HTTP/2 protocol. /// Finish service configuration and create *http service* for HTTP/2 protocol.
pub fn h2<F, P, B>(self, service: F) -> H2Service<T, P, S, B> pub fn h2<F, B>(self, service: F) -> H2Service<T, S, B>
where where
B: MessageBody + 'static, B: MessageBody + 'static,
F: IntoServiceFactory<S>, F: IntoServiceFactory<S>,
@ -203,12 +220,14 @@ where
self.keep_alive, self.keep_alive,
self.client_timeout, self.client_timeout,
self.client_disconnect, self.client_disconnect,
self.secure,
self.local_addr,
); );
H2Service::with_config(cfg, service.into_factory()).on_connect(self.on_connect) H2Service::with_config(cfg, service.into_factory()).on_connect(self.on_connect)
} }
/// Finish service configuration and create `HttpService` instance. /// Finish service configuration and create `HttpService` instance.
pub fn finish<F, P, B>(self, service: F) -> HttpService<T, P, S, B, X, U> pub fn finish<F, B>(self, service: F) -> HttpService<T, S, B, X, U>
where where
B: MessageBody + 'static, B: MessageBody + 'static,
F: IntoServiceFactory<S>, F: IntoServiceFactory<S>,
@ -221,6 +240,8 @@ where
self.keep_alive, self.keep_alive,
self.client_timeout, self.client_timeout,
self.client_disconnect, self.client_disconnect,
self.secure,
self.local_addr,
); );
HttpService::with_config(cfg, service.into_factory()) HttpService::with_config(cfg, service.into_factory())
.expect(self.expect) .expect(self.expect)

View File

@ -1,8 +1,8 @@
use std::cell::UnsafeCell; use std::cell::UnsafeCell;
use std::fmt;
use std::fmt::Write; use std::fmt::Write;
use std::rc::Rc; use std::rc::Rc;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use std::{fmt, net};
use actix_rt::time::{delay, delay_for, Delay}; use actix_rt::time::{delay, delay_for, Delay};
use bytes::BytesMut; use bytes::BytesMut;
@ -47,6 +47,8 @@ struct Inner {
client_timeout: u64, client_timeout: u64,
client_disconnect: u64, client_disconnect: u64,
ka_enabled: bool, ka_enabled: bool,
secure: bool,
local_addr: Option<std::net::SocketAddr>,
timer: DateService, timer: DateService,
} }
@ -58,7 +60,7 @@ impl Clone for ServiceConfig {
impl Default for ServiceConfig { impl Default for ServiceConfig {
fn default() -> Self { fn default() -> Self {
Self::new(KeepAlive::Timeout(5), 0, 0) Self::new(KeepAlive::Timeout(5), 0, 0, false, None)
} }
} }
@ -68,6 +70,8 @@ impl ServiceConfig {
keep_alive: KeepAlive, keep_alive: KeepAlive,
client_timeout: u64, client_timeout: u64,
client_disconnect: u64, client_disconnect: u64,
secure: bool,
local_addr: Option<net::SocketAddr>,
) -> ServiceConfig { ) -> ServiceConfig {
let (keep_alive, ka_enabled) = match keep_alive { let (keep_alive, ka_enabled) = match keep_alive {
KeepAlive::Timeout(val) => (val as u64, true), KeepAlive::Timeout(val) => (val as u64, true),
@ -85,10 +89,24 @@ impl ServiceConfig {
ka_enabled, ka_enabled,
client_timeout, client_timeout,
client_disconnect, client_disconnect,
secure,
local_addr,
timer: DateService::new(), timer: DateService::new(),
})) }))
} }
#[inline]
/// Returns true if connection is secure(https)
pub fn secure(&self) -> bool {
self.0.secure
}
#[inline]
/// Returns the local address that this server is bound to.
pub fn local_addr(&self) -> Option<net::SocketAddr> {
self.0.local_addr
}
#[inline] #[inline]
/// Keep alive duration if configured. /// Keep alive duration if configured.
pub fn keep_alive(&self) -> Option<Duration> { pub fn keep_alive(&self) -> Option<Duration> {
@ -271,7 +289,7 @@ mod tests {
#[actix_rt::test] #[actix_rt::test]
async fn test_date() { async fn test_date() {
let settings = ServiceConfig::new(KeepAlive::Os, 0, 0); let settings = ServiceConfig::new(KeepAlive::Os, 0, 0, false, None);
let mut buf1 = BytesMut::with_capacity(DATE_VALUE_LENGTH + 10); let mut buf1 = BytesMut::with_capacity(DATE_VALUE_LENGTH + 10);
settings.set_date(&mut buf1); settings.set_date(&mut buf1);
let mut buf2 = BytesMut::with_capacity(DATE_VALUE_LENGTH + 10); let mut buf2 = BytesMut::with_capacity(DATE_VALUE_LENGTH + 10);

View File

@ -5,9 +5,8 @@ use std::task::{Context, Poll};
use std::time::Instant; use std::time::Instant;
use std::{fmt, io, net}; use std::{fmt, io, net};
use actix_codec::{AsyncRead, Decoder, Encoder, Framed, FramedParts}; use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed, FramedParts};
use actix_rt::time::{delay, Delay}; use actix_rt::time::{delay, Delay};
use actix_server_config::IoStream;
use actix_service::Service; use actix_service::Service;
use bitflags::bitflags; use bitflags::bitflags;
use bytes::{BufMut, BytesMut}; use bytes::{BufMut, BytesMut};
@ -168,7 +167,7 @@ impl PartialEq for PollResponse {
impl<T, S, B, X, U> Dispatcher<T, S, B, X, U> impl<T, S, B, X, U> Dispatcher<T, S, B, X, U>
where where
T: IoStream, T: AsyncRead + AsyncWrite + Unpin,
S: Service<Request = Request>, S: Service<Request = Request>,
S::Error: Into<Error>, S::Error: Into<Error>,
S::Response: Into<Response<B>>, S::Response: Into<Response<B>>,
@ -186,6 +185,7 @@ where
expect: CloneableService<X>, expect: CloneableService<X>,
upgrade: Option<CloneableService<U>>, upgrade: Option<CloneableService<U>>,
on_connect: Option<Box<dyn DataFactory>>, on_connect: Option<Box<dyn DataFactory>>,
peer_addr: Option<net::SocketAddr>,
) -> Self { ) -> Self {
Dispatcher::with_timeout( Dispatcher::with_timeout(
stream, stream,
@ -197,6 +197,7 @@ where
expect, expect,
upgrade, upgrade,
on_connect, on_connect,
peer_addr,
) )
} }
@ -211,6 +212,7 @@ where
expect: CloneableService<X>, expect: CloneableService<X>,
upgrade: Option<CloneableService<U>>, upgrade: Option<CloneableService<U>>,
on_connect: Option<Box<dyn DataFactory>>, on_connect: Option<Box<dyn DataFactory>>,
peer_addr: Option<net::SocketAddr>,
) -> Self { ) -> Self {
let keepalive = config.keep_alive_enabled(); let keepalive = config.keep_alive_enabled();
let flags = if keepalive { let flags = if keepalive {
@ -234,7 +236,6 @@ where
payload: None, payload: None,
state: State::None, state: State::None,
error: None, error: None,
peer_addr: io.peer_addr(),
messages: VecDeque::new(), messages: VecDeque::new(),
io, io,
codec, codec,
@ -244,6 +245,7 @@ where
upgrade, upgrade,
on_connect, on_connect,
flags, flags,
peer_addr,
ka_expire, ka_expire,
ka_timer, ka_timer,
}), }),
@ -253,7 +255,7 @@ where
impl<T, S, B, X, U> InnerDispatcher<T, S, B, X, U> impl<T, S, B, X, U> InnerDispatcher<T, S, B, X, U>
where where
T: IoStream, T: AsyncRead + AsyncWrite + Unpin,
S: Service<Request = Request>, S: Service<Request = Request>,
S::Error: Into<Error>, S::Error: Into<Error>,
S::Response: Into<Response<B>>, S::Response: Into<Response<B>>,
@ -682,7 +684,7 @@ where
impl<T, S, B, X, U> Unpin for Dispatcher<T, S, B, X, U> impl<T, S, B, X, U> Unpin for Dispatcher<T, S, B, X, U>
where where
T: IoStream, T: AsyncRead + AsyncWrite + Unpin,
S: Service<Request = Request>, S: Service<Request = Request>,
S::Error: Into<Error>, S::Error: Into<Error>,
S::Response: Into<Response<B>>, S::Response: Into<Response<B>>,
@ -696,7 +698,7 @@ where
impl<T, S, B, X, U> Future for Dispatcher<T, S, B, X, U> impl<T, S, B, X, U> Future for Dispatcher<T, S, B, X, U>
where where
T: IoStream, T: AsyncRead + AsyncWrite + Unpin,
S: Service<Request = Request>, S: Service<Request = Request>,
S::Error: Into<Error>, S::Error: Into<Error>,
S::Response: Into<Response<B>>, S::Response: Into<Response<B>>,
@ -907,6 +909,7 @@ mod tests {
CloneableService::new(ExpectHandler), CloneableService::new(ExpectHandler),
None, None,
None, None,
None,
); );
match Pin::new(&mut h1).poll(cx) { match Pin::new(&mut h1).poll(cx) {
Poll::Pending => panic!(), Poll::Pending => panic!(),

View File

@ -1,6 +1,5 @@
use std::task::{Context, Poll}; use std::task::{Context, Poll};
use actix_server_config::ServerConfig;
use actix_service::{Service, ServiceFactory}; use actix_service::{Service, ServiceFactory};
use futures::future::{ok, Ready}; use futures::future::{ok, Ready};
@ -10,7 +9,7 @@ use crate::request::Request;
pub struct ExpectHandler; pub struct ExpectHandler;
impl ServiceFactory for ExpectHandler { impl ServiceFactory for ExpectHandler {
type Config = ServerConfig; type Config = ();
type Request = Request; type Request = Request;
type Response = Request; type Response = Request;
type Error = Error; type Error = Error;
@ -18,7 +17,7 @@ impl ServiceFactory for ExpectHandler {
type InitError = Error; type InitError = Error;
type Future = Ready<Result<Self::Service, Self::InitError>>; type Future = Ready<Result<Self::Service, Self::InitError>>;
fn new_service(&self, _: &ServerConfig) -> Self::Future { fn new_service(&self, _: &()) -> Self::Future {
ok(ExpectHandler) ok(ExpectHandler)
} }
} }

View File

@ -1,19 +1,19 @@
use std::fmt;
use std::future::Future; use std::future::Future;
use std::marker::PhantomData; use std::marker::PhantomData;
use std::pin::Pin; use std::pin::Pin;
use std::rc::Rc; use std::rc::Rc;
use std::task::{Context, Poll}; use std::task::{Context, Poll};
use std::{fmt, net};
use actix_codec::Framed; use actix_codec::{AsyncRead, AsyncWrite, Framed};
use actix_server_config::{Io, IoStream, ServerConfig as SrvConfig}; use actix_rt::net::TcpStream;
use actix_service::{IntoServiceFactory, Service, ServiceFactory}; use actix_service::{pipeline_factory, IntoServiceFactory, Service, ServiceFactory};
use futures::future::{ok, Ready}; use futures::future::{ok, Ready};
use futures::ready; use futures::ready;
use crate::body::MessageBody; use crate::body::MessageBody;
use crate::cloneable::CloneableService; use crate::cloneable::CloneableService;
use crate::config::{KeepAlive, ServiceConfig}; use crate::config::ServiceConfig;
use crate::error::{DispatchError, Error, ParseError}; use crate::error::{DispatchError, Error, ParseError};
use crate::helpers::DataFactory; use crate::helpers::DataFactory;
use crate::request::Request; use crate::request::Request;
@ -24,39 +24,25 @@ use super::dispatcher::Dispatcher;
use super::{ExpectHandler, Message, UpgradeHandler}; use super::{ExpectHandler, Message, UpgradeHandler};
/// `ServiceFactory` implementation for HTTP1 transport /// `ServiceFactory` implementation for HTTP1 transport
pub struct H1Service<T, P, S, B, X = ExpectHandler, U = UpgradeHandler<T>> { pub struct H1Service<T, S, B, X = ExpectHandler, U = UpgradeHandler<T>> {
srv: S, srv: S,
cfg: ServiceConfig, cfg: ServiceConfig,
expect: X, expect: X,
upgrade: Option<U>, upgrade: Option<U>,
on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>, on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
_t: PhantomData<(T, P, B)>, _t: PhantomData<(T, B)>,
} }
impl<T, P, S, B> H1Service<T, P, S, B> impl<T, S, B> H1Service<T, S, B>
where where
S: ServiceFactory<Config = SrvConfig, Request = Request>, S: ServiceFactory<Config = (), Request = Request>,
S::Error: Into<Error>, S::Error: Into<Error>,
S::InitError: fmt::Debug, S::InitError: fmt::Debug,
S::Response: Into<Response<B>>, S::Response: Into<Response<B>>,
B: MessageBody, B: MessageBody,
{ {
/// Create new `HttpService` instance with default config.
pub fn new<F: IntoServiceFactory<S>>(service: F) -> Self {
let cfg = ServiceConfig::new(KeepAlive::Timeout(5), 5000, 0);
H1Service {
cfg,
srv: service.into_factory(),
expect: ExpectHandler,
upgrade: None,
on_connect: None,
_t: PhantomData,
}
}
/// Create new `HttpService` instance with config. /// Create new `HttpService` instance with config.
pub fn with_config<F: IntoServiceFactory<S>>( pub(crate) fn with_config<F: IntoServiceFactory<S>>(
cfg: ServiceConfig, cfg: ServiceConfig,
service: F, service: F,
) -> Self { ) -> Self {
@ -71,15 +57,102 @@ where
} }
} }
impl<T, P, S, B, X, U> H1Service<T, P, S, B, X, U> impl<S, B, X, U> H1Service<TcpStream, S, B, X, U>
where where
S: ServiceFactory<Config = SrvConfig, Request = Request>, S: ServiceFactory<Config = (), Request = Request>,
S::Error: Into<Error>,
S::InitError: fmt::Debug,
S::Response: Into<Response<B>>,
B: MessageBody,
X: ServiceFactory<Config = (), Request = Request, Response = Request>,
X::Error: Into<Error>,
X::InitError: fmt::Debug,
U: ServiceFactory<
Config = (),
Request = (Request, Framed<TcpStream, Codec>),
Response = (),
>,
U::Error: fmt::Display,
U::InitError: fmt::Debug,
{
/// Create simple tcp stream service
pub fn tcp(
self,
) -> impl ServiceFactory<
Config = (),
Request = TcpStream,
Response = (),
Error = DispatchError,
InitError = (),
> {
pipeline_factory(|io: TcpStream| {
let peer_addr = io.peer_addr().ok();
ok((io, peer_addr))
})
.and_then(self)
}
}
#[cfg(feature = "openssl")]
mod openssl {
use super::*;
use actix_tls::openssl::{Acceptor, SslStream};
use actix_tls::{openssl::HandshakeError, SslError};
use open_ssl::ssl::SslAcceptor;
impl<S, B, X, U> H1Service<SslStream<TcpStream>, S, B, X, U>
where
S: ServiceFactory<Config = (), Request = Request>,
S::Error: Into<Error>,
S::InitError: fmt::Debug,
S::Response: Into<Response<B>>,
B: MessageBody,
X: ServiceFactory<Config = (), Request = Request, Response = Request>,
X::Error: Into<Error>,
X::InitError: fmt::Debug,
U: ServiceFactory<
Config = (),
Request = (Request, Framed<SslStream<TcpStream>, Codec>),
Response = (),
>,
U::Error: fmt::Display,
U::InitError: fmt::Debug,
{
/// Create openssl based service
pub fn openssl(
self,
acceptor: SslAcceptor,
) -> impl ServiceFactory<
Config = (),
Request = TcpStream,
Response = (),
Error = SslError<HandshakeError<TcpStream>, DispatchError>,
InitError = (),
> {
pipeline_factory(
Acceptor::new(acceptor)
.map_err(SslError::Ssl)
.map_init_err(|_| panic!()),
)
.and_then(|io: SslStream<TcpStream>| {
let peer_addr = io.get_ref().peer_addr().ok();
ok((io, peer_addr))
})
.and_then(self.map_err(SslError::Service))
}
}
}
impl<T, S, B, X, U> H1Service<T, S, B, X, U>
where
S: ServiceFactory<Config = (), Request = Request>,
S::Error: Into<Error>, S::Error: Into<Error>,
S::Response: Into<Response<B>>, S::Response: Into<Response<B>>,
S::InitError: fmt::Debug, S::InitError: fmt::Debug,
B: MessageBody, B: MessageBody,
{ {
pub fn expect<X1>(self, expect: X1) -> H1Service<T, P, S, B, X1, U> pub fn expect<X1>(self, expect: X1) -> H1Service<T, S, B, X1, U>
where where
X1: ServiceFactory<Request = Request, Response = Request>, X1: ServiceFactory<Request = Request, Response = Request>,
X1::Error: Into<Error>, X1::Error: Into<Error>,
@ -95,7 +168,7 @@ where
} }
} }
pub fn upgrade<U1>(self, upgrade: Option<U1>) -> H1Service<T, P, S, B, X, U1> pub fn upgrade<U1>(self, upgrade: Option<U1>) -> H1Service<T, S, B, X, U1>
where where
U1: ServiceFactory<Request = (Request, Framed<T, Codec>), Response = ()>, U1: ServiceFactory<Request = (Request, Framed<T, Codec>), Response = ()>,
U1::Error: fmt::Display, U1::Error: fmt::Display,
@ -121,34 +194,30 @@ where
} }
} }
impl<T, P, S, B, X, U> ServiceFactory for H1Service<T, P, S, B, X, U> impl<T, S, B, X, U> ServiceFactory for H1Service<T, S, B, X, U>
where where
T: IoStream, T: AsyncRead + AsyncWrite + Unpin,
S: ServiceFactory<Config = SrvConfig, Request = Request>, S: ServiceFactory<Config = (), Request = Request>,
S::Error: Into<Error>, S::Error: Into<Error>,
S::Response: Into<Response<B>>, S::Response: Into<Response<B>>,
S::InitError: fmt::Debug, S::InitError: fmt::Debug,
B: MessageBody, B: MessageBody,
X: ServiceFactory<Config = SrvConfig, Request = Request, Response = Request>, X: ServiceFactory<Config = (), Request = Request, Response = Request>,
X::Error: Into<Error>, X::Error: Into<Error>,
X::InitError: fmt::Debug, X::InitError: fmt::Debug,
U: ServiceFactory< U: ServiceFactory<Config = (), Request = (Request, Framed<T, Codec>), Response = ()>,
Config = SrvConfig,
Request = (Request, Framed<T, Codec>),
Response = (),
>,
U::Error: fmt::Display, U::Error: fmt::Display,
U::InitError: fmt::Debug, U::InitError: fmt::Debug,
{ {
type Config = SrvConfig; type Config = ();
type Request = Io<T, P>; type Request = (T, Option<net::SocketAddr>);
type Response = (); type Response = ();
type Error = DispatchError; type Error = DispatchError;
type InitError = (); type InitError = ();
type Service = H1ServiceHandler<T, P, S::Service, B, X::Service, U::Service>; type Service = H1ServiceHandler<T, S::Service, B, X::Service, U::Service>;
type Future = H1ServiceResponse<T, P, S, B, X, U>; type Future = H1ServiceResponse<T, S, B, X, U>;
fn new_service(&self, cfg: &SrvConfig) -> Self::Future { fn new_service(&self, cfg: &()) -> Self::Future {
H1ServiceResponse { H1ServiceResponse {
fut: self.srv.new_service(cfg), fut: self.srv.new_service(cfg),
fut_ex: Some(self.expect.new_service(cfg)), fut_ex: Some(self.expect.new_service(cfg)),
@ -164,7 +233,7 @@ where
#[doc(hidden)] #[doc(hidden)]
#[pin_project::pin_project] #[pin_project::pin_project]
pub struct H1ServiceResponse<T, P, S, B, X, U> pub struct H1ServiceResponse<T, S, B, X, U>
where where
S: ServiceFactory<Request = Request>, S: ServiceFactory<Request = Request>,
S::Error: Into<Error>, S::Error: Into<Error>,
@ -186,12 +255,12 @@ where
upgrade: Option<U::Service>, upgrade: Option<U::Service>,
on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>, on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
cfg: Option<ServiceConfig>, cfg: Option<ServiceConfig>,
_t: PhantomData<(T, P, B)>, _t: PhantomData<(T, B)>,
} }
impl<T, P, S, B, X, U> Future for H1ServiceResponse<T, P, S, B, X, U> impl<T, S, B, X, U> Future for H1ServiceResponse<T, S, B, X, U>
where where
T: IoStream, T: AsyncRead + AsyncWrite + Unpin,
S: ServiceFactory<Request = Request>, S: ServiceFactory<Request = Request>,
S::Error: Into<Error>, S::Error: Into<Error>,
S::Response: Into<Response<B>>, S::Response: Into<Response<B>>,
@ -204,8 +273,7 @@ where
U::Error: fmt::Display, U::Error: fmt::Display,
U::InitError: fmt::Debug, U::InitError: fmt::Debug,
{ {
type Output = type Output = Result<H1ServiceHandler<T, S::Service, B, X::Service, U::Service>, ()>;
Result<H1ServiceHandler<T, P, S::Service, B, X::Service, U::Service>, ()>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
let mut this = self.as_mut().project(); let mut this = self.as_mut().project();
@ -247,16 +315,16 @@ where
} }
/// `Service` implementation for HTTP1 transport /// `Service` implementation for HTTP1 transport
pub struct H1ServiceHandler<T, P, S, B, X, U> { pub struct H1ServiceHandler<T, S, B, X, U> {
srv: CloneableService<S>, srv: CloneableService<S>,
expect: CloneableService<X>, expect: CloneableService<X>,
upgrade: Option<CloneableService<U>>, upgrade: Option<CloneableService<U>>,
on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>, on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
cfg: ServiceConfig, cfg: ServiceConfig,
_t: PhantomData<(T, P, B)>, _t: PhantomData<(T, B)>,
} }
impl<T, P, S, B, X, U> H1ServiceHandler<T, P, S, B, X, U> impl<T, S, B, X, U> H1ServiceHandler<T, S, B, X, U>
where where
S: Service<Request = Request>, S: Service<Request = Request>,
S::Error: Into<Error>, S::Error: Into<Error>,
@ -273,7 +341,7 @@ where
expect: X, expect: X,
upgrade: Option<U>, upgrade: Option<U>,
on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>, on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
) -> H1ServiceHandler<T, P, S, B, X, U> { ) -> H1ServiceHandler<T, S, B, X, U> {
H1ServiceHandler { H1ServiceHandler {
srv: CloneableService::new(srv), srv: CloneableService::new(srv),
expect: CloneableService::new(expect), expect: CloneableService::new(expect),
@ -285,9 +353,9 @@ where
} }
} }
impl<T, P, S, B, X, U> Service for H1ServiceHandler<T, P, S, B, X, U> impl<T, S, B, X, U> Service for H1ServiceHandler<T, S, B, X, U>
where where
T: IoStream, T: AsyncRead + AsyncWrite + Unpin,
S: Service<Request = Request>, S: Service<Request = Request>,
S::Error: Into<Error>, S::Error: Into<Error>,
S::Response: Into<Response<B>>, S::Response: Into<Response<B>>,
@ -297,7 +365,7 @@ where
U: Service<Request = (Request, Framed<T, Codec>), Response = ()>, U: Service<Request = (Request, Framed<T, Codec>), Response = ()>,
U::Error: fmt::Display, U::Error: fmt::Display,
{ {
type Request = Io<T, P>; type Request = (T, Option<net::SocketAddr>);
type Response = (); type Response = ();
type Error = DispatchError; type Error = DispatchError;
type Future = Dispatcher<T, S, B, X, U>; type Future = Dispatcher<T, S, B, X, U>;
@ -331,9 +399,7 @@ where
} }
} }
fn call(&mut self, req: Self::Request) -> Self::Future { fn call(&mut self, (io, addr): Self::Request) -> Self::Future {
let io = req.into_parts().0;
let on_connect = if let Some(ref on_connect) = self.on_connect { let on_connect = if let Some(ref on_connect) = self.on_connect {
Some(on_connect(&io)) Some(on_connect(&io))
} else { } else {
@ -347,20 +413,21 @@ where
self.expect.clone(), self.expect.clone(),
self.upgrade.clone(), self.upgrade.clone(),
on_connect, on_connect,
addr,
) )
} }
} }
/// `ServiceFactory` implementation for `OneRequestService` service /// `ServiceFactory` implementation for `OneRequestService` service
#[derive(Default)] #[derive(Default)]
pub struct OneRequest<T, P> { pub struct OneRequest<T> {
config: ServiceConfig, config: ServiceConfig,
_t: PhantomData<(T, P)>, _t: PhantomData<T>,
} }
impl<T, P> OneRequest<T, P> impl<T> OneRequest<T>
where where
T: IoStream, T: AsyncRead + AsyncWrite + Unpin,
{ {
/// Create new `H1SimpleService` instance. /// Create new `H1SimpleService` instance.
pub fn new() -> Self { pub fn new() -> Self {
@ -371,38 +438,38 @@ where
} }
} }
impl<T, P> ServiceFactory for OneRequest<T, P> impl<T> ServiceFactory for OneRequest<T>
where where
T: IoStream, T: AsyncRead + AsyncWrite + Unpin,
{ {
type Config = SrvConfig; type Config = ();
type Request = Io<T, P>; type Request = T;
type Response = (Request, Framed<T, Codec>); type Response = (Request, Framed<T, Codec>);
type Error = ParseError; type Error = ParseError;
type InitError = (); type InitError = ();
type Service = OneRequestService<T, P>; type Service = OneRequestService<T>;
type Future = Ready<Result<Self::Service, Self::InitError>>; type Future = Ready<Result<Self::Service, Self::InitError>>;
fn new_service(&self, _: &SrvConfig) -> Self::Future { fn new_service(&self, _: &()) -> Self::Future {
ok(OneRequestService { ok(OneRequestService {
config: self.config.clone(),
_t: PhantomData, _t: PhantomData,
config: self.config.clone(),
}) })
} }
} }
/// `Service` implementation for HTTP1 transport. Reads one request and returns /// `Service` implementation for HTTP1 transport. Reads one request and returns
/// request and framed object. /// request and framed object.
pub struct OneRequestService<T, P> { pub struct OneRequestService<T> {
_t: PhantomData<T>,
config: ServiceConfig, config: ServiceConfig,
_t: PhantomData<(T, P)>,
} }
impl<T, P> Service for OneRequestService<T, P> impl<T> Service for OneRequestService<T>
where where
T: IoStream, T: AsyncRead + AsyncWrite + Unpin,
{ {
type Request = Io<T, P>; type Request = T;
type Response = (Request, Framed<T, Codec>); type Response = (Request, Framed<T, Codec>);
type Error = ParseError; type Error = ParseError;
type Future = OneRequestServiceResponse<T>; type Future = OneRequestServiceResponse<T>;
@ -413,10 +480,7 @@ where
fn call(&mut self, req: Self::Request) -> Self::Future { fn call(&mut self, req: Self::Request) -> Self::Future {
OneRequestServiceResponse { OneRequestServiceResponse {
framed: Some(Framed::new( framed: Some(Framed::new(req, Codec::new(self.config.clone()))),
req.into_parts().0,
Codec::new(self.config.clone()),
)),
} }
} }
} }
@ -424,14 +488,14 @@ where
#[doc(hidden)] #[doc(hidden)]
pub struct OneRequestServiceResponse<T> pub struct OneRequestServiceResponse<T>
where where
T: IoStream, T: AsyncRead + AsyncWrite + Unpin,
{ {
framed: Option<Framed<T, Codec>>, framed: Option<Framed<T, Codec>>,
} }
impl<T> Future for OneRequestServiceResponse<T> impl<T> Future for OneRequestServiceResponse<T>
where where
T: IoStream, T: AsyncRead + AsyncWrite + Unpin,
{ {
type Output = Result<(Request, Framed<T, Codec>), ParseError>; type Output = Result<(Request, Framed<T, Codec>), ParseError>;

View File

@ -2,7 +2,6 @@ use std::marker::PhantomData;
use std::task::{Context, Poll}; use std::task::{Context, Poll};
use actix_codec::Framed; use actix_codec::Framed;
use actix_server_config::ServerConfig;
use actix_service::{Service, ServiceFactory}; use actix_service::{Service, ServiceFactory};
use futures::future::Ready; use futures::future::Ready;
@ -13,7 +12,7 @@ use crate::request::Request;
pub struct UpgradeHandler<T>(PhantomData<T>); pub struct UpgradeHandler<T>(PhantomData<T>);
impl<T> ServiceFactory for UpgradeHandler<T> { impl<T> ServiceFactory for UpgradeHandler<T> {
type Config = ServerConfig; type Config = ();
type Request = (Request, Framed<T, Codec>); type Request = (Request, Framed<T, Codec>);
type Response = (); type Response = ();
type Error = Error; type Error = Error;
@ -21,7 +20,7 @@ impl<T> ServiceFactory for UpgradeHandler<T> {
type InitError = Error; type InitError = Error;
type Future = Ready<Result<Self::Service, Self::InitError>>; type Future = Ready<Result<Self::Service, Self::InitError>>;
fn new_service(&self, _: &ServerConfig) -> Self::Future { fn new_service(&self, _: &()) -> Self::Future {
unimplemented!() unimplemented!()
} }
} }

View File

@ -8,7 +8,6 @@ use std::{fmt, mem, net};
use actix_codec::{AsyncRead, AsyncWrite}; use actix_codec::{AsyncRead, AsyncWrite};
use actix_rt::time::Delay; use actix_rt::time::Delay;
use actix_server_config::IoStream;
use actix_service::Service; use actix_service::Service;
use bitflags::bitflags; use bitflags::bitflags;
use bytes::{Bytes, BytesMut}; use bytes::{Bytes, BytesMut};
@ -36,7 +35,10 @@ const CHUNK_SIZE: usize = 16_384;
/// Dispatcher for HTTP/2 protocol /// Dispatcher for HTTP/2 protocol
#[pin_project::pin_project] #[pin_project::pin_project]
pub struct Dispatcher<T: IoStream, S: Service<Request = Request>, B: MessageBody> { pub struct Dispatcher<T, S: Service<Request = Request>, B: MessageBody>
where
T: AsyncRead + AsyncWrite + Unpin,
{
service: CloneableService<S>, service: CloneableService<S>,
connection: Connection<T, Bytes>, connection: Connection<T, Bytes>,
on_connect: Option<Box<dyn DataFactory>>, on_connect: Option<Box<dyn DataFactory>>,
@ -49,7 +51,7 @@ pub struct Dispatcher<T: IoStream, S: Service<Request = Request>, B: MessageBody
impl<T, S, B> Dispatcher<T, S, B> impl<T, S, B> Dispatcher<T, S, B>
where where
T: IoStream, T: AsyncRead + AsyncWrite + Unpin,
S: Service<Request = Request>, S: Service<Request = Request>,
S::Error: Into<Error>, S::Error: Into<Error>,
// S::Future: 'static, // S::Future: 'static,
@ -95,7 +97,7 @@ where
impl<T, S, B> Future for Dispatcher<T, S, B> impl<T, S, B> Future for Dispatcher<T, S, B>
where where
T: IoStream, T: AsyncRead + AsyncWrite + Unpin,
S: Service<Request = Request>, S: Service<Request = Request>,
S::Error: Into<Error> + 'static, S::Error: Into<Error> + 'static,
S::Future: 'static, S::Future: 'static,

View File

@ -6,8 +6,11 @@ use std::task::{Context, Poll};
use std::{io, net, rc}; use std::{io, net, rc};
use actix_codec::{AsyncRead, AsyncWrite, Framed}; use actix_codec::{AsyncRead, AsyncWrite, Framed};
use actix_server_config::{Io, IoStream, ServerConfig as SrvConfig}; use actix_rt::net::TcpStream;
use actix_service::{IntoServiceFactory, Service, ServiceFactory}; use actix_service::{
factory_fn, pipeline_factory, service_fn2, IntoServiceFactory, Service,
ServiceFactory,
};
use bytes::Bytes; use bytes::Bytes;
use futures::future::{ok, Ready}; use futures::future::{ok, Ready};
use futures::{ready, Stream}; use futures::{ready, Stream};
@ -23,39 +26,28 @@ use crate::helpers::DataFactory;
use crate::payload::Payload; use crate::payload::Payload;
use crate::request::Request; use crate::request::Request;
use crate::response::Response; use crate::response::Response;
use crate::Protocol;
use super::dispatcher::Dispatcher; use super::dispatcher::Dispatcher;
/// `ServiceFactory` implementation for HTTP2 transport /// `ServiceFactory` implementation for HTTP2 transport
pub struct H2Service<T, P, S, B> { pub struct H2Service<T, S, B> {
srv: S, srv: S,
cfg: ServiceConfig, cfg: ServiceConfig,
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>, on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
_t: PhantomData<(T, P, B)>, _t: PhantomData<(T, B)>,
} }
impl<T, P, S, B> H2Service<T, P, S, B> impl<T, S, B> H2Service<T, S, B>
where where
S: ServiceFactory<Config = SrvConfig, Request = Request>, S: ServiceFactory<Config = (), Request = Request>,
S::Error: Into<Error> + 'static, S::Error: Into<Error> + 'static,
S::Response: Into<Response<B>> + 'static, S::Response: Into<Response<B>> + 'static,
<S::Service as Service>::Future: 'static, <S::Service as Service>::Future: 'static,
B: MessageBody + 'static, B: MessageBody + 'static,
{ {
/// Create new `HttpService` instance.
pub fn new<F: IntoServiceFactory<S>>(service: F) -> Self {
let cfg = ServiceConfig::new(KeepAlive::Timeout(5), 5000, 0);
H2Service {
cfg,
on_connect: None,
srv: service.into_factory(),
_t: PhantomData,
}
}
/// Create new `HttpService` instance with config. /// Create new `HttpService` instance with config.
pub fn with_config<F: IntoServiceFactory<S>>( pub(crate) fn with_config<F: IntoServiceFactory<S>>(
cfg: ServiceConfig, cfg: ServiceConfig,
service: F, service: F,
) -> Self { ) -> Self {
@ -77,24 +69,98 @@ where
} }
} }
impl<T, P, S, B> ServiceFactory for H2Service<T, P, S, B> impl<S, B> H2Service<TcpStream, S, B>
where where
T: IoStream, S: ServiceFactory<Config = (), Request = Request>,
S: ServiceFactory<Config = SrvConfig, Request = Request>,
S::Error: Into<Error> + 'static, S::Error: Into<Error> + 'static,
S::Response: Into<Response<B>> + 'static, S::Response: Into<Response<B>> + 'static,
<S::Service as Service>::Future: 'static, <S::Service as Service>::Future: 'static,
B: MessageBody + 'static, B: MessageBody + 'static,
{ {
type Config = SrvConfig; /// Create simple tcp based service
type Request = Io<T, P>; pub fn tcp(
self,
) -> impl ServiceFactory<
Config = (),
Request = TcpStream,
Response = (),
Error = DispatchError,
InitError = S::InitError,
> {
pipeline_factory(factory_fn(|| {
async {
Ok::<_, S::InitError>(service_fn2(|io: TcpStream| {
let peer_addr = io.peer_addr().ok();
ok::<_, DispatchError>((io, peer_addr))
}))
}
}))
.and_then(self)
}
}
#[cfg(feature = "openssl")]
mod openssl {
use actix_service::{factory_fn, service_fn2};
use actix_tls::openssl::{Acceptor, SslStream};
use actix_tls::{openssl::HandshakeError, SslError};
use open_ssl::ssl::SslAcceptor;
use super::*;
impl<S, B> H2Service<SslStream<TcpStream>, S, B>
where
S: ServiceFactory<Config = (), Request = Request>,
S::Error: Into<Error> + 'static,
S::Response: Into<Response<B>> + 'static,
<S::Service as Service>::Future: 'static,
B: MessageBody + 'static,
{
/// Create ssl based service
pub fn openssl(
self,
acceptor: SslAcceptor,
) -> impl ServiceFactory<
Config = (),
Request = TcpStream,
Response = (),
Error = SslError<HandshakeError<TcpStream>, DispatchError>,
InitError = S::InitError,
> {
pipeline_factory(
Acceptor::new(acceptor)
.map_err(SslError::Ssl)
.map_init_err(|_| panic!()),
)
.and_then(factory_fn(|| {
ok::<_, S::InitError>(service_fn2(|io: SslStream<TcpStream>| {
let peer_addr = io.get_ref().peer_addr().ok();
ok((io, peer_addr))
}))
}))
.and_then(self.map_err(SslError::Service))
}
}
}
impl<T, S, B> ServiceFactory for H2Service<T, S, B>
where
T: AsyncRead + AsyncWrite + Unpin,
S: ServiceFactory<Config = (), Request = Request>,
S::Error: Into<Error> + 'static,
S::Response: Into<Response<B>> + 'static,
<S::Service as Service>::Future: 'static,
B: MessageBody + 'static,
{
type Config = ();
type Request = (T, Option<net::SocketAddr>);
type Response = (); type Response = ();
type Error = DispatchError; type Error = DispatchError;
type InitError = S::InitError; type InitError = S::InitError;
type Service = H2ServiceHandler<T, P, S::Service, B>; type Service = H2ServiceHandler<T, S::Service, B>;
type Future = H2ServiceResponse<T, P, S, B>; type Future = H2ServiceResponse<T, S, B>;
fn new_service(&self, cfg: &SrvConfig) -> Self::Future { fn new_service(&self, cfg: &()) -> Self::Future {
H2ServiceResponse { H2ServiceResponse {
fut: self.srv.new_service(cfg), fut: self.srv.new_service(cfg),
cfg: Some(self.cfg.clone()), cfg: Some(self.cfg.clone()),
@ -106,24 +172,24 @@ where
#[doc(hidden)] #[doc(hidden)]
#[pin_project::pin_project] #[pin_project::pin_project]
pub struct H2ServiceResponse<T, P, S: ServiceFactory, B> { pub struct H2ServiceResponse<T, S: ServiceFactory, B> {
#[pin] #[pin]
fut: S::Future, fut: S::Future,
cfg: Option<ServiceConfig>, cfg: Option<ServiceConfig>,
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>, on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
_t: PhantomData<(T, P, B)>, _t: PhantomData<(T, B)>,
} }
impl<T, P, S, B> Future for H2ServiceResponse<T, P, S, B> impl<T, S, B> Future for H2ServiceResponse<T, S, B>
where where
T: IoStream, T: AsyncRead + AsyncWrite + Unpin,
S: ServiceFactory<Config = SrvConfig, Request = Request>, S: ServiceFactory<Config = (), Request = Request>,
S::Error: Into<Error> + 'static, S::Error: Into<Error> + 'static,
S::Response: Into<Response<B>> + 'static, S::Response: Into<Response<B>> + 'static,
<S::Service as Service>::Future: 'static, <S::Service as Service>::Future: 'static,
B: MessageBody + 'static, B: MessageBody + 'static,
{ {
type Output = Result<H2ServiceHandler<T, P, S::Service, B>, S::InitError>; type Output = Result<H2ServiceHandler<T, S::Service, B>, S::InitError>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
let this = self.as_mut().project(); let this = self.as_mut().project();
@ -140,14 +206,14 @@ where
} }
/// `Service` implementation for http/2 transport /// `Service` implementation for http/2 transport
pub struct H2ServiceHandler<T, P, S, B> { pub struct H2ServiceHandler<T, S, B> {
srv: CloneableService<S>, srv: CloneableService<S>,
cfg: ServiceConfig, cfg: ServiceConfig,
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>, on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
_t: PhantomData<(T, P, B)>, _t: PhantomData<(T, B)>,
} }
impl<T, P, S, B> H2ServiceHandler<T, P, S, B> impl<T, S, B> H2ServiceHandler<T, S, B>
where where
S: Service<Request = Request>, S: Service<Request = Request>,
S::Error: Into<Error> + 'static, S::Error: Into<Error> + 'static,
@ -159,7 +225,7 @@ where
cfg: ServiceConfig, cfg: ServiceConfig,
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>, on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
srv: S, srv: S,
) -> H2ServiceHandler<T, P, S, B> { ) -> H2ServiceHandler<T, S, B> {
H2ServiceHandler { H2ServiceHandler {
cfg, cfg,
on_connect, on_connect,
@ -169,16 +235,16 @@ where
} }
} }
impl<T, P, S, B> Service for H2ServiceHandler<T, P, S, B> impl<T, S, B> Service for H2ServiceHandler<T, S, B>
where where
T: IoStream, T: AsyncRead + AsyncWrite + Unpin,
S: Service<Request = Request>, S: Service<Request = Request>,
S::Error: Into<Error> + 'static, S::Error: Into<Error> + 'static,
S::Future: 'static, S::Future: 'static,
S::Response: Into<Response<B>> + 'static, S::Response: Into<Response<B>> + 'static,
B: MessageBody + 'static, B: MessageBody + 'static,
{ {
type Request = Io<T, P>; type Request = (T, Option<net::SocketAddr>);
type Response = (); type Response = ();
type Error = DispatchError; type Error = DispatchError;
type Future = H2ServiceHandlerResponse<T, S, B>; type Future = H2ServiceHandlerResponse<T, S, B>;
@ -191,9 +257,7 @@ where
}) })
} }
fn call(&mut self, req: Self::Request) -> Self::Future { fn call(&mut self, (io, addr): Self::Request) -> Self::Future {
let io = req.into_parts().0;
let peer_addr = io.peer_addr();
let on_connect = if let Some(ref on_connect) = self.on_connect { let on_connect = if let Some(ref on_connect) = self.on_connect {
Some(on_connect(&io)) Some(on_connect(&io))
} else { } else {
@ -204,7 +268,7 @@ where
state: State::Handshake( state: State::Handshake(
Some(self.srv.clone()), Some(self.srv.clone()),
Some(self.cfg.clone()), Some(self.cfg.clone()),
peer_addr, addr,
on_connect, on_connect,
server::handshake(io), server::handshake(io),
), ),
@ -212,8 +276,9 @@ where
} }
} }
enum State<T: IoStream, S: Service<Request = Request>, B: MessageBody> enum State<T, S: Service<Request = Request>, B: MessageBody>
where where
T: AsyncRead + AsyncWrite + Unpin,
S::Future: 'static, S::Future: 'static,
{ {
Incoming(Dispatcher<T, S, B>), Incoming(Dispatcher<T, S, B>),
@ -228,7 +293,7 @@ where
pub struct H2ServiceHandlerResponse<T, S, B> pub struct H2ServiceHandlerResponse<T, S, B>
where where
T: IoStream, T: AsyncRead + AsyncWrite + Unpin,
S: Service<Request = Request>, S: Service<Request = Request>,
S::Error: Into<Error> + 'static, S::Error: Into<Error> + 'static,
S::Future: 'static, S::Future: 'static,
@ -240,7 +305,7 @@ where
impl<T, S, B> Future for H2ServiceHandlerResponse<T, S, B> impl<T, S, B> Future for H2ServiceHandlerResponse<T, S, B>
where where
T: IoStream, T: AsyncRead + AsyncWrite + Unpin,
S: Service<Request = Request>, S: Service<Request = Request>,
S::Error: Into<Error> + 'static, S::Error: Into<Error> + 'static,
S::Future: 'static, S::Future: 'static,

View File

@ -64,3 +64,10 @@ pub mod http {
pub use crate::header::ContentEncoding; pub use crate::header::ContentEncoding;
pub use crate::message::ConnectionType; pub use crate::message::ConnectionType;
} }
/// Http protocol
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum Protocol {
Http1,
Http2,
}

View File

@ -1,15 +1,13 @@
use std::marker::PhantomData; use std::marker::PhantomData;
use std::pin::Pin; use std::pin::Pin;
use std::task::{Context, Poll}; use std::task::{Context, Poll};
use std::{fmt, io, net, rc}; use std::{fmt, net, rc};
use actix_codec::{AsyncRead, AsyncWrite, Framed}; use actix_codec::{AsyncRead, AsyncWrite, Framed};
use actix_server_config::{ use actix_rt::net::TcpStream;
Io as ServerIo, IoStream, Protocol, ServerConfig as SrvConfig, use actix_service::{pipeline_factory, IntoServiceFactory, Service, ServiceFactory};
}; use bytes::Bytes;
use actix_service::{IntoServiceFactory, Service, ServiceFactory}; use futures::{future::ok, ready, Future};
use bytes::{BufMut, Bytes, BytesMut};
use futures::{ready, Future};
use h2::server::{self, Handshake}; use h2::server::{self, Handshake};
use pin_project::{pin_project, project}; use pin_project::{pin_project, project};
@ -21,21 +19,21 @@ use crate::error::{DispatchError, Error};
use crate::helpers::DataFactory; use crate::helpers::DataFactory;
use crate::request::Request; use crate::request::Request;
use crate::response::Response; use crate::response::Response;
use crate::{h1, h2::Dispatcher}; use crate::{h1, h2::Dispatcher, Protocol};
/// `ServiceFactory` HTTP1.1/HTTP2 transport implementation /// `ServiceFactory` HTTP1.1/HTTP2 transport implementation
pub struct HttpService<T, P, S, B, X = h1::ExpectHandler, U = h1::UpgradeHandler<T>> { pub struct HttpService<T, S, B, X = h1::ExpectHandler, U = h1::UpgradeHandler<T>> {
srv: S, srv: S,
cfg: ServiceConfig, cfg: ServiceConfig,
expect: X, expect: X,
upgrade: Option<U>, upgrade: Option<U>,
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>, on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
_t: PhantomData<(T, P, B)>, _t: PhantomData<(T, B)>,
} }
impl<T, S, B> HttpService<T, (), S, B> impl<T, S, B> HttpService<T, S, B>
where where
S: ServiceFactory<Config = SrvConfig, Request = Request>, S: ServiceFactory<Config = (), Request = Request>,
S::Error: Into<Error> + 'static, S::Error: Into<Error> + 'static,
S::InitError: fmt::Debug, S::InitError: fmt::Debug,
S::Response: Into<Response<B>> + 'static, S::Response: Into<Response<B>> + 'static,
@ -48,9 +46,9 @@ where
} }
} }
impl<T, P, S, B> HttpService<T, P, S, B> impl<T, S, B> HttpService<T, S, B>
where where
S: ServiceFactory<Config = SrvConfig, Request = Request>, S: ServiceFactory<Config = (), Request = Request>,
S::Error: Into<Error> + 'static, S::Error: Into<Error> + 'static,
S::InitError: fmt::Debug, S::InitError: fmt::Debug,
S::Response: Into<Response<B>> + 'static, S::Response: Into<Response<B>> + 'static,
@ -59,7 +57,7 @@ where
{ {
/// Create new `HttpService` instance. /// Create new `HttpService` instance.
pub fn new<F: IntoServiceFactory<S>>(service: F) -> Self { pub fn new<F: IntoServiceFactory<S>>(service: F) -> Self {
let cfg = ServiceConfig::new(KeepAlive::Timeout(5), 5000, 0); let cfg = ServiceConfig::new(KeepAlive::Timeout(5), 5000, 0, false, None);
HttpService { HttpService {
cfg, cfg,
@ -87,9 +85,9 @@ where
} }
} }
impl<T, P, S, B, X, U> HttpService<T, P, S, B, X, U> impl<T, S, B, X, U> HttpService<T, S, B, X, U>
where where
S: ServiceFactory<Config = SrvConfig, Request = Request>, S: ServiceFactory<Config = (), Request = Request>,
S::Error: Into<Error> + 'static, S::Error: Into<Error> + 'static,
S::InitError: fmt::Debug, S::InitError: fmt::Debug,
S::Response: Into<Response<B>> + 'static, S::Response: Into<Response<B>> + 'static,
@ -101,9 +99,9 @@ where
/// Service get called with request that contains `EXPECT` header. /// Service get called with request that contains `EXPECT` header.
/// Service must return request in case of success, in that case /// Service must return request in case of success, in that case
/// request will be forwarded to main service. /// request will be forwarded to main service.
pub fn expect<X1>(self, expect: X1) -> HttpService<T, P, S, B, X1, U> pub fn expect<X1>(self, expect: X1) -> HttpService<T, S, B, X1, U>
where where
X1: ServiceFactory<Config = SrvConfig, Request = Request, Response = Request>, X1: ServiceFactory<Config = (), Request = Request, Response = Request>,
X1::Error: Into<Error>, X1::Error: Into<Error>,
X1::InitError: fmt::Debug, X1::InitError: fmt::Debug,
<X1::Service as Service>::Future: 'static, <X1::Service as Service>::Future: 'static,
@ -122,10 +120,10 @@ where
/// ///
/// If service is provided then normal requests handling get halted /// If service is provided then normal requests handling get halted
/// and this service get called with original request and framed object. /// and this service get called with original request and framed object.
pub fn upgrade<U1>(self, upgrade: Option<U1>) -> HttpService<T, P, S, B, X, U1> pub fn upgrade<U1>(self, upgrade: Option<U1>) -> HttpService<T, S, B, X, U1>
where where
U1: ServiceFactory< U1: ServiceFactory<
Config = SrvConfig, Config = (),
Request = (Request, Framed<T, h1::Codec>), Request = (Request, Framed<T, h1::Codec>),
Response = (), Response = (),
>, >,
@ -153,21 +151,122 @@ where
} }
} }
impl<T, P, S, B, X, U> ServiceFactory for HttpService<T, P, S, B, X, U> impl<S, B, X, U> HttpService<TcpStream, S, B, X, U>
where where
T: IoStream, S: ServiceFactory<Config = (), Request = Request>,
S: ServiceFactory<Config = SrvConfig, Request = Request>,
S::Error: Into<Error> + 'static, S::Error: Into<Error> + 'static,
S::InitError: fmt::Debug, S::InitError: fmt::Debug,
S::Response: Into<Response<B>> + 'static, S::Response: Into<Response<B>> + 'static,
<S::Service as Service>::Future: 'static, <S::Service as Service>::Future: 'static,
B: MessageBody + 'static, B: MessageBody + 'static,
X: ServiceFactory<Config = SrvConfig, Request = Request, Response = Request>, X: ServiceFactory<Config = (), Request = Request, Response = Request>,
X::Error: Into<Error>, X::Error: Into<Error>,
X::InitError: fmt::Debug, X::InitError: fmt::Debug,
<X::Service as Service>::Future: 'static, <X::Service as Service>::Future: 'static,
U: ServiceFactory< U: ServiceFactory<
Config = SrvConfig, Config = (),
Request = (Request, Framed<TcpStream, h1::Codec>),
Response = (),
>,
U::Error: fmt::Display,
U::InitError: fmt::Debug,
<U::Service as Service>::Future: 'static,
{
/// Create simple tcp stream service
pub fn tcp(
self,
) -> impl ServiceFactory<
Config = (),
Request = TcpStream,
Response = (),
Error = DispatchError,
InitError = (),
> {
pipeline_factory(|io: TcpStream| {
let peer_addr = io.peer_addr().ok();
ok((io, Protocol::Http1, peer_addr))
})
.and_then(self)
}
}
#[cfg(feature = "openssl")]
mod openssl {
use super::*;
use actix_tls::openssl::{Acceptor, SslStream};
use actix_tls::{openssl::HandshakeError, SslError};
use open_ssl::ssl::SslAcceptor;
impl<S, B, X, U> HttpService<SslStream<TcpStream>, S, B, X, U>
where
S: ServiceFactory<Config = (), Request = Request>,
S::Error: Into<Error> + 'static,
S::InitError: fmt::Debug,
S::Response: Into<Response<B>> + 'static,
<S::Service as Service>::Future: 'static,
B: MessageBody + 'static,
X: ServiceFactory<Config = (), Request = Request, Response = Request>,
X::Error: Into<Error>,
X::InitError: fmt::Debug,
<X::Service as Service>::Future: 'static,
U: ServiceFactory<
Config = (),
Request = (Request, Framed<SslStream<TcpStream>, h1::Codec>),
Response = (),
>,
U::Error: fmt::Display,
U::InitError: fmt::Debug,
<U::Service as Service>::Future: 'static,
{
/// Create openssl based service
pub fn openssl(
self,
acceptor: SslAcceptor,
) -> impl ServiceFactory<
Config = (),
Request = TcpStream,
Response = (),
Error = SslError<HandshakeError<TcpStream>, DispatchError>,
InitError = (),
> {
pipeline_factory(
Acceptor::new(acceptor)
.map_err(SslError::Ssl)
.map_init_err(|_| panic!()),
)
.and_then(|io: SslStream<TcpStream>| {
let proto = if let Some(protos) = io.ssl().selected_alpn_protocol() {
if protos.windows(2).any(|window| window == b"h2") {
Protocol::Http2
} else {
Protocol::Http1
}
} else {
Protocol::Http1
};
let peer_addr = io.get_ref().peer_addr().ok();
ok((io, proto, peer_addr))
})
.and_then(self.map_err(SslError::Service))
}
}
}
impl<T, S, B, X, U> ServiceFactory for HttpService<T, S, B, X, U>
where
T: AsyncRead + AsyncWrite + Unpin,
S: ServiceFactory<Config = (), Request = Request>,
S::Error: Into<Error> + 'static,
S::InitError: fmt::Debug,
S::Response: Into<Response<B>> + 'static,
<S::Service as Service>::Future: 'static,
B: MessageBody + 'static,
X: ServiceFactory<Config = (), Request = Request, Response = Request>,
X::Error: Into<Error>,
X::InitError: fmt::Debug,
<X::Service as Service>::Future: 'static,
U: ServiceFactory<
Config = (),
Request = (Request, Framed<T, h1::Codec>), Request = (Request, Framed<T, h1::Codec>),
Response = (), Response = (),
>, >,
@ -175,15 +274,15 @@ where
U::InitError: fmt::Debug, U::InitError: fmt::Debug,
<U::Service as Service>::Future: 'static, <U::Service as Service>::Future: 'static,
{ {
type Config = SrvConfig; type Config = ();
type Request = ServerIo<T, P>; type Request = (T, Protocol, Option<net::SocketAddr>);
type Response = (); type Response = ();
type Error = DispatchError; type Error = DispatchError;
type InitError = (); type InitError = ();
type Service = HttpServiceHandler<T, P, S::Service, B, X::Service, U::Service>; type Service = HttpServiceHandler<T, S::Service, B, X::Service, U::Service>;
type Future = HttpServiceResponse<T, P, S, B, X, U>; type Future = HttpServiceResponse<T, S, B, X, U>;
fn new_service(&self, cfg: &SrvConfig) -> Self::Future { fn new_service(&self, cfg: &()) -> Self::Future {
HttpServiceResponse { HttpServiceResponse {
fut: self.srv.new_service(cfg), fut: self.srv.new_service(cfg),
fut_ex: Some(self.expect.new_service(cfg)), fut_ex: Some(self.expect.new_service(cfg)),
@ -191,7 +290,7 @@ where
expect: None, expect: None,
upgrade: None, upgrade: None,
on_connect: self.on_connect.clone(), on_connect: self.on_connect.clone(),
cfg: Some(self.cfg.clone()), cfg: self.cfg.clone(),
_t: PhantomData, _t: PhantomData,
} }
} }
@ -201,7 +300,6 @@ where
#[pin_project] #[pin_project]
pub struct HttpServiceResponse< pub struct HttpServiceResponse<
T, T,
P,
S: ServiceFactory, S: ServiceFactory,
B, B,
X: ServiceFactory, X: ServiceFactory,
@ -216,13 +314,13 @@ pub struct HttpServiceResponse<
expect: Option<X::Service>, expect: Option<X::Service>,
upgrade: Option<U::Service>, upgrade: Option<U::Service>,
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>, on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
cfg: Option<ServiceConfig>, cfg: ServiceConfig,
_t: PhantomData<(T, P, B)>, _t: PhantomData<(T, B)>,
} }
impl<T, P, S, B, X, U> Future for HttpServiceResponse<T, P, S, B, X, U> impl<T, S, B, X, U> Future for HttpServiceResponse<T, S, B, X, U>
where where
T: IoStream, T: AsyncRead + AsyncWrite + Unpin,
S: ServiceFactory<Request = Request>, S: ServiceFactory<Request = Request>,
S::Error: Into<Error> + 'static, S::Error: Into<Error> + 'static,
S::InitError: fmt::Debug, S::InitError: fmt::Debug,
@ -239,7 +337,7 @@ where
<U::Service as Service>::Future: 'static, <U::Service as Service>::Future: 'static,
{ {
type Output = type Output =
Result<HttpServiceHandler<T, P, S::Service, B, X::Service, U::Service>, ()>; Result<HttpServiceHandler<T, S::Service, B, X::Service, U::Service>, ()>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
let mut this = self.as_mut().project(); let mut this = self.as_mut().project();
@ -269,7 +367,7 @@ where
Poll::Ready(result.map(|service| { Poll::Ready(result.map(|service| {
let this = self.as_mut().project(); let this = self.as_mut().project();
HttpServiceHandler::new( HttpServiceHandler::new(
this.cfg.take().unwrap(), this.cfg.clone(),
service, service,
this.expect.take().unwrap(), this.expect.take().unwrap(),
this.upgrade.take(), this.upgrade.take(),
@ -280,16 +378,16 @@ where
} }
/// `Service` implementation for http transport /// `Service` implementation for http transport
pub struct HttpServiceHandler<T, P, S, B, X, U> { pub struct HttpServiceHandler<T, S, B, X, U> {
srv: CloneableService<S>, srv: CloneableService<S>,
expect: CloneableService<X>, expect: CloneableService<X>,
upgrade: Option<CloneableService<U>>, upgrade: Option<CloneableService<U>>,
cfg: ServiceConfig, cfg: ServiceConfig,
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>, on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
_t: PhantomData<(T, P, B, X)>, _t: PhantomData<(T, B, X)>,
} }
impl<T, P, S, B, X, U> HttpServiceHandler<T, P, S, B, X, U> impl<T, S, B, X, U> HttpServiceHandler<T, S, B, X, U>
where where
S: Service<Request = Request>, S: Service<Request = Request>,
S::Error: Into<Error> + 'static, S::Error: Into<Error> + 'static,
@ -307,7 +405,7 @@ where
expect: X, expect: X,
upgrade: Option<U>, upgrade: Option<U>,
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>, on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
) -> HttpServiceHandler<T, P, S, B, X, U> { ) -> HttpServiceHandler<T, S, B, X, U> {
HttpServiceHandler { HttpServiceHandler {
cfg, cfg,
on_connect, on_connect,
@ -319,9 +417,9 @@ where
} }
} }
impl<T, P, S, B, X, U> Service for HttpServiceHandler<T, P, S, B, X, U> impl<T, S, B, X, U> Service for HttpServiceHandler<T, S, B, X, U>
where where
T: IoStream, T: AsyncRead + AsyncWrite + Unpin,
S: Service<Request = Request>, S: Service<Request = Request>,
S::Error: Into<Error> + 'static, S::Error: Into<Error> + 'static,
S::Future: 'static, S::Future: 'static,
@ -332,7 +430,7 @@ where
U: Service<Request = (Request, Framed<T, h1::Codec>), Response = ()>, U: Service<Request = (Request, Framed<T, h1::Codec>), Response = ()>,
U::Error: fmt::Display, U::Error: fmt::Display,
{ {
type Request = ServerIo<T, P>; type Request = (T, Protocol, Option<net::SocketAddr>);
type Response = (); type Response = ();
type Error = DispatchError; type Error = DispatchError;
type Future = HttpServiceHandlerResponse<T, S, B, X, U>; type Future = HttpServiceHandlerResponse<T, S, B, X, U>;
@ -366,9 +464,7 @@ where
} }
} }
fn call(&mut self, req: Self::Request) -> Self::Future { fn call(&mut self, (io, proto, peer_addr): Self::Request) -> Self::Future {
let (io, _, proto) = req.into_parts();
let on_connect = if let Some(ref on_connect) = self.on_connect { let on_connect = if let Some(ref on_connect) = self.on_connect {
Some(on_connect(&io)) Some(on_connect(&io))
} else { } else {
@ -376,23 +472,16 @@ where
}; };
match proto { match proto {
Protocol::Http2 => { Protocol::Http2 => HttpServiceHandlerResponse {
let peer_addr = io.peer_addr(); state: State::H2Handshake(Some((
let io = Io {
inner: io,
unread: None,
};
HttpServiceHandlerResponse {
state: State::Handshake(Some((
server::handshake(io), server::handshake(io),
self.cfg.clone(), self.cfg.clone(),
self.srv.clone(), self.srv.clone(),
peer_addr,
on_connect, on_connect,
peer_addr,
))), ))),
} },
} Protocol::Http1 => HttpServiceHandlerResponse {
Protocol::Http10 | Protocol::Http11 => HttpServiceHandlerResponse {
state: State::H1(h1::Dispatcher::new( state: State::H1(h1::Dispatcher::new(
io, io,
self.cfg.clone(), self.cfg.clone(),
@ -400,19 +489,9 @@ where
self.expect.clone(), self.expect.clone(),
self.upgrade.clone(), self.upgrade.clone(),
on_connect, on_connect,
peer_addr,
)), )),
}, },
_ => HttpServiceHandlerResponse {
state: State::Unknown(Some((
io,
BytesMut::with_capacity(14),
self.cfg.clone(),
self.srv.clone(),
self.expect.clone(),
self.upgrade.clone(),
on_connect,
))),
},
} }
} }
} }
@ -423,7 +502,7 @@ where
S: Service<Request = Request>, S: Service<Request = Request>,
S::Future: 'static, S::Future: 'static,
S::Error: Into<Error>, S::Error: Into<Error>,
T: IoStream, T: AsyncRead + AsyncWrite + Unpin,
B: MessageBody, B: MessageBody,
X: Service<Request = Request, Response = Request>, X: Service<Request = Request, Response = Request>,
X::Error: Into<Error>, X::Error: Into<Error>,
@ -431,25 +510,14 @@ where
U::Error: fmt::Display, U::Error: fmt::Display,
{ {
H1(#[pin] h1::Dispatcher<T, S, B, X, U>), H1(#[pin] h1::Dispatcher<T, S, B, X, U>),
H2(#[pin] Dispatcher<Io<T>, S, B>), H2(#[pin] Dispatcher<T, S, B>),
Unknown( H2Handshake(
Option<( Option<(
T, Handshake<T, Bytes>,
BytesMut,
ServiceConfig, ServiceConfig,
CloneableService<S>, CloneableService<S>,
CloneableService<X>,
Option<CloneableService<U>>,
Option<Box<dyn DataFactory>>, Option<Box<dyn DataFactory>>,
)>,
),
Handshake(
Option<(
Handshake<Io<T>, Bytes>,
ServiceConfig,
CloneableService<S>,
Option<net::SocketAddr>, Option<net::SocketAddr>,
Option<Box<dyn DataFactory>>,
)>, )>,
), ),
} }
@ -457,7 +525,7 @@ where
#[pin_project] #[pin_project]
pub struct HttpServiceHandlerResponse<T, S, B, X, U> pub struct HttpServiceHandlerResponse<T, S, B, X, U>
where where
T: IoStream, T: AsyncRead + AsyncWrite + Unpin,
S: Service<Request = Request>, S: Service<Request = Request>,
S::Error: Into<Error> + 'static, S::Error: Into<Error> + 'static,
S::Future: 'static, S::Future: 'static,
@ -472,11 +540,9 @@ where
state: State<T, S, B, X, U>, state: State<T, S, B, X, U>,
} }
const HTTP2_PREFACE: [u8; 14] = *b"PRI * HTTP/2.0";
impl<T, S, B, X, U> Future for HttpServiceHandlerResponse<T, S, B, X, U> impl<T, S, B, X, U> Future for HttpServiceHandlerResponse<T, S, B, X, U>
where where
T: IoStream, T: AsyncRead + AsyncWrite + Unpin,
S: Service<Request = Request>, S: Service<Request = Request>,
S::Error: Into<Error> + 'static, S::Error: Into<Error> + 'static,
S::Future: 'static, S::Future: 'static,
@ -496,7 +562,7 @@ where
impl<T, S, B, X, U> State<T, S, B, X, U> impl<T, S, B, X, U> State<T, S, B, X, U>
where where
T: IoStream, T: AsyncRead + AsyncWrite + Unpin,
S: Service<Request = Request>, S: Service<Request = Request>,
S::Error: Into<Error> + 'static, S::Error: Into<Error> + 'static,
S::Response: Into<Response<B>> + 'static, S::Response: Into<Response<B>> + 'static,
@ -515,57 +581,7 @@ where
match self.as_mut().project() { match self.as_mut().project() {
State::H1(disp) => disp.poll(cx), State::H1(disp) => disp.poll(cx),
State::H2(disp) => disp.poll(cx), State::H2(disp) => disp.poll(cx),
State::Unknown(ref mut data) => { State::H2Handshake(ref mut data) => {
if let Some(ref mut item) = data {
loop {
// Safety - we only write to the returned slice.
let b = unsafe { item.1.bytes_mut() };
let n = ready!(Pin::new(&mut item.0).poll_read(cx, b))?;
if n == 0 {
return Poll::Ready(Ok(()));
}
// Safety - we know that 'n' bytes have
// been initialized via the contract of
// 'poll_read'
unsafe { item.1.advance_mut(n) };
if item.1.len() >= HTTP2_PREFACE.len() {
break;
}
}
} else {
panic!()
}
let (io, buf, cfg, srv, expect, upgrade, on_connect) =
data.take().unwrap();
if buf[..14] == HTTP2_PREFACE[..] {
let peer_addr = io.peer_addr();
let io = Io {
inner: io,
unread: Some(buf),
};
self.set(State::Handshake(Some((
server::handshake(io),
cfg,
srv,
peer_addr,
on_connect,
))));
} else {
self.set(State::H1(h1::Dispatcher::with_timeout(
io,
h1::Codec::new(cfg.clone()),
cfg,
buf,
None,
srv,
expect,
upgrade,
on_connect,
)))
}
self.poll(cx)
}
State::Handshake(ref mut data) => {
let conn = if let Some(ref mut item) = data { let conn = if let Some(ref mut item) = data {
match Pin::new(&mut item.0).poll(cx) { match Pin::new(&mut item.0).poll(cx) {
Poll::Ready(Ok(conn)) => conn, Poll::Ready(Ok(conn)) => conn,
@ -578,7 +594,7 @@ where
} else { } else {
panic!() panic!()
}; };
let (_, cfg, srv, peer_addr, on_connect) = data.take().unwrap(); let (_, cfg, srv, on_connect, peer_addr) = data.take().unwrap();
self.set(State::H2(Dispatcher::new( self.set(State::H2(Dispatcher::new(
srv, conn, on_connect, cfg, None, peer_addr, srv, conn, on_connect, cfg, None, peer_addr,
))); )));
@ -587,117 +603,3 @@ where
} }
} }
} }
/// Wrapper for `AsyncRead + AsyncWrite` types
#[pin_project::pin_project]
struct Io<T> {
unread: Option<BytesMut>,
#[pin]
inner: T,
}
impl<T: io::Read> io::Read for Io<T> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
if let Some(mut bytes) = self.unread.take() {
let size = std::cmp::min(buf.len(), bytes.len());
buf[..size].copy_from_slice(&bytes[..size]);
if bytes.len() > size {
bytes.split_to(size);
self.unread = Some(bytes);
}
Ok(size)
} else {
self.inner.read(buf)
}
}
}
impl<T: io::Write> io::Write for Io<T> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.inner.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.inner.flush()
}
}
impl<T: AsyncRead> AsyncRead for Io<T> {
// unsafe fn initializer(&self) -> io::Initializer {
// self.get_mut().inner.initializer()
// }
unsafe fn prepare_uninitialized_buffer(&self, buf: &mut [u8]) -> bool {
self.inner.prepare_uninitialized_buffer(buf)
}
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
let this = self.project();
if let Some(mut bytes) = this.unread.take() {
let size = std::cmp::min(buf.len(), bytes.len());
buf[..size].copy_from_slice(&bytes[..size]);
if bytes.len() > size {
bytes.split_to(size);
*this.unread = Some(bytes);
}
Poll::Ready(Ok(size))
} else {
this.inner.poll_read(cx, buf)
}
}
// fn poll_read_vectored(
// self: Pin<&mut Self>,
// cx: &mut Context<'_>,
// bufs: &mut [io::IoSliceMut<'_>],
// ) -> Poll<io::Result<usize>> {
// self.get_mut().inner.poll_read_vectored(cx, bufs)
// }
}
impl<T: AsyncWrite> actix_codec::AsyncWrite for Io<T> {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
self.project().inner.poll_write(cx, buf)
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
self.project().inner.poll_flush(cx)
}
fn poll_shutdown(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<io::Result<()>> {
self.project().inner.poll_shutdown(cx)
}
}
impl<T: IoStream> actix_server_config::IoStream for Io<T> {
#[inline]
fn peer_addr(&self) -> Option<net::SocketAddr> {
self.inner.peer_addr()
}
#[inline]
fn set_nodelay(&mut self, nodelay: bool) -> io::Result<()> {
self.inner.set_nodelay(nodelay)
}
#[inline]
fn set_linger(&mut self, dur: Option<std::time::Duration>) -> io::Result<()> {
self.inner.set_linger(dur)
}
#[inline]
fn set_keepalive(&mut self, dur: Option<std::time::Duration>) -> io::Result<()> {
self.inner.set_keepalive(dur)
}
}

View File

@ -6,7 +6,6 @@ use std::str::FromStr;
use std::task::{Context, Poll}; use std::task::{Context, Poll};
use actix_codec::{AsyncRead, AsyncWrite}; use actix_codec::{AsyncRead, AsyncWrite};
use actix_server_config::IoStream;
use bytes::{Bytes, BytesMut}; use bytes::{Bytes, BytesMut};
use http::header::{self, HeaderName, HeaderValue}; use http::header::{self, HeaderName, HeaderValue};
use http::{HttpTryFrom, Method, Uri, Version}; use http::{HttpTryFrom, Method, Uri, Version};
@ -272,17 +271,3 @@ impl AsyncWrite for TestBuffer {
Poll::Ready(Ok(())) Poll::Ready(Ok(()))
} }
} }
impl IoStream for TestBuffer {
fn set_nodelay(&mut self, _nodelay: bool) -> io::Result<()> {
Ok(())
}
fn set_linger(&mut self, _dur: Option<std::time::Duration>) -> io::Result<()> {
Ok(())
}
fn set_keepalive(&mut self, _dur: Option<std::time::Duration>) -> io::Result<()> {
Ok(())
}
}

View File

@ -30,7 +30,9 @@ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
#[actix_rt::test] #[actix_rt::test]
async fn test_h1_v2() { async fn test_h1_v2() {
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
HttpService::build().finish(|_| future::ok::<_, ()>(Response::Ok().body(STR))) HttpService::build()
.finish(|_| future::ok::<_, ()>(Response::Ok().body(STR)))
.tcp()
}); });
let response = srv.get("/").send().await.unwrap(); let response = srv.get("/").send().await.unwrap();
@ -57,6 +59,7 @@ async fn test_connection_close() {
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
HttpService::build() HttpService::build()
.finish(|_| ok::<_, ()>(Response::Ok().body(STR))) .finish(|_| ok::<_, ()>(Response::Ok().body(STR)))
.tcp()
.map(|_| ()) .map(|_| ())
}); });
@ -75,6 +78,7 @@ async fn test_with_query_parameter() {
ok::<_, ()>(Response::BadRequest().finish()) ok::<_, ()>(Response::BadRequest().finish())
} }
}) })
.tcp()
.map(|_| ()) .map(|_| ())
}); });

View File

@ -1,11 +1,8 @@
#![cfg(feature = "openssl")] #![cfg(feature = "openssl")]
use std::io; use std::io;
use actix_codec::{AsyncRead, AsyncWrite};
use actix_http_test::TestServer; use actix_http_test::TestServer;
use actix_server::ssl::OpensslAcceptor; use actix_service::{service_fn, ServiceFactory};
use actix_server_config::ServerConfig;
use actix_service::{factory_fn_cfg, pipeline_factory, service_fn2, ServiceFactory};
use bytes::{Bytes, BytesMut}; use bytes::{Bytes, BytesMut};
use futures::future::{err, ok, ready}; use futures::future::{err, ok, ready};
@ -36,7 +33,7 @@ where
Ok(body) Ok(body)
} }
fn ssl_acceptor<T: AsyncRead + AsyncWrite>() -> io::Result<OpensslAcceptor<T, ()>> { fn ssl_acceptor() -> SslAcceptor {
// load ssl keys // load ssl keys
let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap(); let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
builder builder
@ -47,30 +44,29 @@ fn ssl_acceptor<T: AsyncRead + AsyncWrite>() -> io::Result<OpensslAcceptor<T, ()
.unwrap(); .unwrap();
builder.set_alpn_select_callback(|_, protos| { builder.set_alpn_select_callback(|_, protos| {
const H2: &[u8] = b"\x02h2"; const H2: &[u8] = b"\x02h2";
const H11: &[u8] = b"\x08http/1.1";
if protos.windows(3).any(|window| window == H2) { if protos.windows(3).any(|window| window == H2) {
Ok(b"h2") Ok(b"h2")
} else if protos.windows(9).any(|window| window == H11) {
Ok(b"http/1.1")
} else { } else {
Err(AlpnError::NOACK) Err(AlpnError::NOACK)
} }
}); });
builder.set_alpn_protos(b"\x02h2")?; builder
Ok(OpensslAcceptor::new(builder.build())) .set_alpn_protos(b"\x08http/1.1\x02h2")
.expect("Can not contrust SslAcceptor");
builder.build()
} }
#[actix_rt::test] #[actix_rt::test]
async fn test_h2() -> io::Result<()> { async fn test_h2() -> io::Result<()> {
let openssl = ssl_acceptor()?;
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
pipeline_factory(
openssl
.clone()
.map_err(|e| println!("Openssl error: {}", e)),
)
.and_then(
HttpService::build() HttpService::build()
.h2(|_| ok::<_, Error>(Response::Ok().finish())) .h2(|_| ok::<_, Error>(Response::Ok().finish()))
.map_err(|_| ()), .openssl(ssl_acceptor())
) .map_err(|_| ())
}); });
let response = srv.sget("/").send().await.unwrap(); let response = srv.sget("/").send().await.unwrap();
@ -80,22 +76,15 @@ async fn test_h2() -> io::Result<()> {
#[actix_rt::test] #[actix_rt::test]
async fn test_h2_1() -> io::Result<()> { async fn test_h2_1() -> io::Result<()> {
let openssl = ssl_acceptor()?;
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
pipeline_factory(
openssl
.clone()
.map_err(|e| println!("Openssl error: {}", e)),
)
.and_then(
HttpService::build() HttpService::build()
.finish(|req: Request| { .finish(|req: Request| {
assert!(req.peer_addr().is_some()); assert!(req.peer_addr().is_some());
assert_eq!(req.version(), Version::HTTP_2); assert_eq!(req.version(), Version::HTTP_2);
ok::<_, Error>(Response::Ok().finish()) ok::<_, Error>(Response::Ok().finish())
}) })
.map_err(|_| ()), .openssl(ssl_acceptor())
) .map_err(|_| ())
}); });
let response = srv.sget("/").send().await.unwrap(); let response = srv.sget("/").send().await.unwrap();
@ -106,14 +95,7 @@ async fn test_h2_1() -> io::Result<()> {
#[actix_rt::test] #[actix_rt::test]
async fn test_h2_body() -> io::Result<()> { async fn test_h2_body() -> io::Result<()> {
let data = "HELLOWORLD".to_owned().repeat(64 * 1024); let data = "HELLOWORLD".to_owned().repeat(64 * 1024);
let openssl = ssl_acceptor()?;
let mut srv = TestServer::start(move || { let mut srv = TestServer::start(move || {
pipeline_factory(
openssl
.clone()
.map_err(|e| println!("Openssl error: {}", e)),
)
.and_then(
HttpService::build() HttpService::build()
.h2(|mut req: Request<_>| { .h2(|mut req: Request<_>| {
async move { async move {
@ -121,8 +103,8 @@ async fn test_h2_body() -> io::Result<()> {
Ok::<_, Error>(Response::Ok().body(body)) Ok::<_, Error>(Response::Ok().body(body))
} }
}) })
.map_err(|_| ()), .openssl(ssl_acceptor())
) .map_err(|_| ())
}); });
let response = srv.sget("/").send_body(data.clone()).await.unwrap(); let response = srv.sget("/").send_body(data.clone()).await.unwrap();
@ -135,15 +117,7 @@ async fn test_h2_body() -> io::Result<()> {
#[actix_rt::test] #[actix_rt::test]
async fn test_h2_content_length() { async fn test_h2_content_length() {
let openssl = ssl_acceptor().unwrap();
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
pipeline_factory(
openssl
.clone()
.map_err(|e| println!("Openssl error: {}", e)),
)
.and_then(
HttpService::build() HttpService::build()
.h2(|req: Request| { .h2(|req: Request| {
let indx: usize = req.uri().path()[1..].parse().unwrap(); let indx: usize = req.uri().path()[1..].parse().unwrap();
@ -157,8 +131,8 @@ async fn test_h2_content_length() {
]; ];
ok::<_, ()>(Response::new(statuses[indx])) ok::<_, ()>(Response::new(statuses[indx]))
}) })
.map_err(|_| ()), .openssl(ssl_acceptor())
) .map_err(|_| ())
}); });
let header = HeaderName::from_static("content-length"); let header = HeaderName::from_static("content-length");
@ -193,14 +167,9 @@ async fn test_h2_content_length() {
async fn test_h2_headers() { async fn test_h2_headers() {
let data = STR.repeat(10); let data = STR.repeat(10);
let data2 = data.clone(); let data2 = data.clone();
let openssl = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || { let mut srv = TestServer::start(move || {
let data = data.clone(); let data = data.clone();
pipeline_factory(openssl
.clone()
.map_err(|e| println!("Openssl error: {}", e)))
.and_then(
HttpService::build().h2(move |_| { HttpService::build().h2(move |_| {
let mut builder = Response::Ok(); let mut builder = Response::Ok();
for idx in 0..90 { for idx in 0..90 {
@ -222,7 +191,9 @@ async fn test_h2_headers() {
); );
} }
ok::<_, ()>(builder.body(data.clone())) ok::<_, ()>(builder.body(data.clone()))
}).map_err(|_| ())) })
.openssl(ssl_acceptor())
.map_err(|_| ())
}); });
let response = srv.sget("/").send().await.unwrap(); let response = srv.sget("/").send().await.unwrap();
@ -257,18 +228,11 @@ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
#[actix_rt::test] #[actix_rt::test]
async fn test_h2_body2() { async fn test_h2_body2() {
let openssl = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || { let mut srv = TestServer::start(move || {
pipeline_factory(
openssl
.clone()
.map_err(|e| println!("Openssl error: {}", e)),
)
.and_then(
HttpService::build() HttpService::build()
.h2(|_| ok::<_, ()>(Response::Ok().body(STR))) .h2(|_| ok::<_, ()>(Response::Ok().body(STR)))
.map_err(|_| ()), .openssl(ssl_acceptor())
) .map_err(|_| ())
}); });
let response = srv.sget("/").send().await.unwrap(); let response = srv.sget("/").send().await.unwrap();
@ -281,18 +245,11 @@ async fn test_h2_body2() {
#[actix_rt::test] #[actix_rt::test]
async fn test_h2_head_empty() { async fn test_h2_head_empty() {
let openssl = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || { let mut srv = TestServer::start(move || {
pipeline_factory(
openssl
.clone()
.map_err(|e| println!("Openssl error: {}", e)),
)
.and_then(
HttpService::build() HttpService::build()
.finish(|_| ok::<_, ()>(Response::Ok().body(STR))) .finish(|_| ok::<_, ()>(Response::Ok().body(STR)))
.map_err(|_| ()), .openssl(ssl_acceptor())
) .map_err(|_| ())
}); });
let response = srv.shead("/").send().await.unwrap(); let response = srv.shead("/").send().await.unwrap();
@ -311,22 +268,13 @@ async fn test_h2_head_empty() {
#[actix_rt::test] #[actix_rt::test]
async fn test_h2_head_binary() { async fn test_h2_head_binary() {
let openssl = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || { let mut srv = TestServer::start(move || {
pipeline_factory(
openssl
.clone()
.map_err(|e| println!("Openssl error: {}", e)),
)
.and_then(
HttpService::build() HttpService::build()
.h2(|_| { .h2(|_| {
ok::<_, ()>( ok::<_, ()>(Response::Ok().content_length(STR.len() as u64).body(STR))
Response::Ok().content_length(STR.len() as u64).body(STR),
)
}) })
.map_err(|_| ()), .openssl(ssl_acceptor())
) .map_err(|_| ())
}); });
let response = srv.shead("/").send().await.unwrap(); let response = srv.shead("/").send().await.unwrap();
@ -344,18 +292,11 @@ async fn test_h2_head_binary() {
#[actix_rt::test] #[actix_rt::test]
async fn test_h2_head_binary2() { async fn test_h2_head_binary2() {
let openssl = ssl_acceptor().unwrap();
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
pipeline_factory(
openssl
.clone()
.map_err(|e| println!("Openssl error: {}", e)),
)
.and_then(
HttpService::build() HttpService::build()
.h2(|_| ok::<_, ()>(Response::Ok().body(STR))) .h2(|_| ok::<_, ()>(Response::Ok().body(STR)))
.map_err(|_| ()), .openssl(ssl_acceptor())
) .map_err(|_| ())
}); });
let response = srv.shead("/").send().await.unwrap(); let response = srv.shead("/").send().await.unwrap();
@ -369,24 +310,16 @@ async fn test_h2_head_binary2() {
#[actix_rt::test] #[actix_rt::test]
async fn test_h2_body_length() { async fn test_h2_body_length() {
let openssl = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || { let mut srv = TestServer::start(move || {
pipeline_factory(
openssl
.clone()
.map_err(|e| println!("Openssl error: {}", e)),
)
.and_then(
HttpService::build() HttpService::build()
.h2(|_| { .h2(|_| {
let body = once(ok(Bytes::from_static(STR.as_ref()))); let body = once(ok(Bytes::from_static(STR.as_ref())));
ok::<_, ()>( ok::<_, ()>(
Response::Ok() Response::Ok().body(body::SizedStream::new(STR.len() as u64, body)),
.body(body::SizedStream::new(STR.len() as u64, body)),
) )
}) })
.map_err(|_| ()), .openssl(ssl_acceptor())
) .map_err(|_| ())
}); });
let response = srv.sget("/").send().await.unwrap(); let response = srv.sget("/").send().await.unwrap();
@ -399,14 +332,7 @@ async fn test_h2_body_length() {
#[actix_rt::test] #[actix_rt::test]
async fn test_h2_body_chunked_explicit() { async fn test_h2_body_chunked_explicit() {
let openssl = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || { let mut srv = TestServer::start(move || {
pipeline_factory(
openssl
.clone()
.map_err(|e| println!("Openssl error: {}", e)),
)
.and_then(
HttpService::build() HttpService::build()
.h2(|_| { .h2(|_| {
let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref()))); let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref())));
@ -416,8 +342,8 @@ async fn test_h2_body_chunked_explicit() {
.streaming(body), .streaming(body),
) )
}) })
.map_err(|_| ()), .openssl(ssl_acceptor())
) .map_err(|_| ())
}); });
let response = srv.sget("/").send().await.unwrap(); let response = srv.sget("/").send().await.unwrap();
@ -433,18 +359,9 @@ async fn test_h2_body_chunked_explicit() {
#[actix_rt::test] #[actix_rt::test]
async fn test_h2_response_http_error_handling() { async fn test_h2_response_http_error_handling() {
let openssl = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || { let mut srv = TestServer::start(move || {
pipeline_factory(
openssl
.clone()
.map_err(|e| println!("Openssl error: {}", e)),
)
.and_then(
HttpService::build() HttpService::build()
.h2(factory_fn_cfg(|_: &ServerConfig| { .h2(service_fn(|_| {
ok::<_, ()>(service_fn2(|_| {
let broken_header = Bytes::from_static(b"\0\0\0"); let broken_header = Bytes::from_static(b"\0\0\0");
ok::<_, ()>( ok::<_, ()>(
Response::Ok() Response::Ok()
@ -452,9 +369,8 @@ async fn test_h2_response_http_error_handling() {
.body(STR), .body(STR),
) )
})) }))
})) .openssl(ssl_acceptor())
.map_err(|_| ()), .map_err(|_| ())
)
}); });
let response = srv.sget("/").send().await.unwrap(); let response = srv.sget("/").send().await.unwrap();
@ -467,19 +383,11 @@ async fn test_h2_response_http_error_handling() {
#[actix_rt::test] #[actix_rt::test]
async fn test_h2_service_error() { async fn test_h2_service_error() {
let openssl = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || { let mut srv = TestServer::start(move || {
pipeline_factory(
openssl
.clone()
.map_err(|e| println!("Openssl error: {}", e)),
)
.and_then(
HttpService::build() HttpService::build()
.h2(|_| err::<Response, Error>(ErrorBadRequest("error"))) .h2(|_| err::<Response, Error>(ErrorBadRequest("error")))
.map_err(|_| ()), .openssl(ssl_acceptor())
) .map_err(|_| ())
}); });
let response = srv.sget("/").send().await.unwrap(); let response = srv.sget("/").send().await.unwrap();
@ -492,23 +400,15 @@ async fn test_h2_service_error() {
#[actix_rt::test] #[actix_rt::test]
async fn test_h2_on_connect() { async fn test_h2_on_connect() {
let openssl = ssl_acceptor().unwrap();
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
pipeline_factory(
openssl
.clone()
.map_err(|e| println!("Openssl error: {}", e)),
)
.and_then(
HttpService::build() HttpService::build()
.on_connect(|_| 10usize) .on_connect(|_| 10usize)
.h2(|req: Request| { .h2(|req: Request| {
assert!(req.extensions().contains::<usize>()); assert!(req.extensions().contains::<usize>());
ok::<_, ()>(Response::Ok().finish()) ok::<_, ()>(Response::Ok().finish())
}) })
.map_err(|_| ()), .openssl(ssl_acceptor())
) .map_err(|_| ())
}); });
let response = srv.sget("/").send().await.unwrap(); let response = srv.sget("/").send().await.unwrap();

View File

@ -4,8 +4,7 @@ use std::{net, thread};
use actix_http_test::TestServer; use actix_http_test::TestServer;
use actix_rt::time::delay_for; use actix_rt::time::delay_for;
use actix_server_config::ServerConfig; use actix_service::service_fn;
use actix_service::{factory_fn_cfg, pipeline, service_fn, ServiceFactory};
use bytes::Bytes; use bytes::Bytes;
use futures::future::{self, err, ok, ready, FutureExt}; use futures::future::{self, err, ok, ready, FutureExt};
use futures::stream::{once, StreamExt}; use futures::stream::{once, StreamExt};
@ -27,6 +26,7 @@ async fn test_h1() {
assert!(req.peer_addr().is_some()); assert!(req.peer_addr().is_some());
future::ok::<_, ()>(Response::Ok().finish()) future::ok::<_, ()>(Response::Ok().finish())
}) })
.tcp()
}); });
let response = srv.get("/").send().await.unwrap(); let response = srv.get("/").send().await.unwrap();
@ -45,7 +45,7 @@ async fn test_h1_2() {
assert_eq!(req.version(), http::Version::HTTP_11); assert_eq!(req.version(), http::Version::HTTP_11);
future::ok::<_, ()>(Response::Ok().finish()) future::ok::<_, ()>(Response::Ok().finish())
}) })
.map(|_| ()) .tcp()
}); });
let response = srv.get("/").send().await.unwrap(); let response = srv.get("/").send().await.unwrap();
@ -64,6 +64,7 @@ async fn test_expect_continue() {
} }
})) }))
.finish(|_| future::ok::<_, ()>(Response::Ok().finish())) .finish(|_| future::ok::<_, ()>(Response::Ok().finish()))
.tcp()
}); });
let mut stream = net::TcpStream::connect(srv.addr()).unwrap(); let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
@ -92,7 +93,8 @@ async fn test_expect_continue_h1() {
} }
}) })
})) }))
.h1(|_| future::ok::<_, ()>(Response::Ok().finish())) .h1(service_fn(|_| future::ok::<_, ()>(Response::Ok().finish())))
.tcp()
}); });
let mut stream = net::TcpStream::connect(srv.addr()).unwrap(); let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
@ -114,7 +116,8 @@ async fn test_chunked_payload() {
let total_size: usize = chunk_sizes.iter().sum(); let total_size: usize = chunk_sizes.iter().sum();
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::build().h1(service_fn(|mut request: Request| { HttpService::build()
.h1(service_fn(|mut request: Request| {
request request
.take_payload() .take_payload()
.map(|res| match res { .map(|res| match res {
@ -126,6 +129,7 @@ async fn test_chunked_payload() {
Ok::<_, Error>(Response::Ok().body(format!("size={}", req_size))) Ok::<_, Error>(Response::Ok().body(format!("size={}", req_size)))
}) })
})) }))
.tcp()
}); });
let returned_size = { let returned_size = {
@ -167,6 +171,7 @@ async fn test_slow_request() {
HttpService::build() HttpService::build()
.client_timeout(100) .client_timeout(100)
.finish(|_| future::ok::<_, ()>(Response::Ok().finish())) .finish(|_| future::ok::<_, ()>(Response::Ok().finish()))
.tcp()
}); });
let mut stream = net::TcpStream::connect(srv.addr()).unwrap(); let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
@ -179,7 +184,9 @@ async fn test_slow_request() {
#[actix_rt::test] #[actix_rt::test]
async fn test_http1_malformed_request() { async fn test_http1_malformed_request() {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::build().h1(|_| future::ok::<_, ()>(Response::Ok().finish())) HttpService::build()
.h1(|_| future::ok::<_, ()>(Response::Ok().finish()))
.tcp()
}); });
let mut stream = net::TcpStream::connect(srv.addr()).unwrap(); let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
@ -192,7 +199,9 @@ async fn test_http1_malformed_request() {
#[actix_rt::test] #[actix_rt::test]
async fn test_http1_keepalive() { async fn test_http1_keepalive() {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::build().h1(|_| future::ok::<_, ()>(Response::Ok().finish())) HttpService::build()
.h1(|_| future::ok::<_, ()>(Response::Ok().finish()))
.tcp()
}); });
let mut stream = net::TcpStream::connect(srv.addr()).unwrap(); let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
@ -213,6 +222,7 @@ async fn test_http1_keepalive_timeout() {
HttpService::build() HttpService::build()
.keep_alive(1) .keep_alive(1)
.h1(|_| future::ok::<_, ()>(Response::Ok().finish())) .h1(|_| future::ok::<_, ()>(Response::Ok().finish()))
.tcp()
}); });
let mut stream = net::TcpStream::connect(srv.addr()).unwrap(); let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
@ -230,7 +240,9 @@ async fn test_http1_keepalive_timeout() {
#[actix_rt::test] #[actix_rt::test]
async fn test_http1_keepalive_close() { async fn test_http1_keepalive_close() {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::build().h1(|_| future::ok::<_, ()>(Response::Ok().finish())) HttpService::build()
.h1(|_| future::ok::<_, ()>(Response::Ok().finish()))
.tcp()
}); });
let mut stream = net::TcpStream::connect(srv.addr()).unwrap(); let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
@ -248,7 +260,9 @@ async fn test_http1_keepalive_close() {
#[actix_rt::test] #[actix_rt::test]
async fn test_http10_keepalive_default_close() { async fn test_http10_keepalive_default_close() {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::build().h1(|_| future::ok::<_, ()>(Response::Ok().finish())) HttpService::build()
.h1(|_| future::ok::<_, ()>(Response::Ok().finish()))
.tcp()
}); });
let mut stream = net::TcpStream::connect(srv.addr()).unwrap(); let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
@ -265,7 +279,9 @@ async fn test_http10_keepalive_default_close() {
#[actix_rt::test] #[actix_rt::test]
async fn test_http10_keepalive() { async fn test_http10_keepalive() {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::build().h1(|_| future::ok::<_, ()>(Response::Ok().finish())) HttpService::build()
.h1(|_| future::ok::<_, ()>(Response::Ok().finish()))
.tcp()
}); });
let mut stream = net::TcpStream::connect(srv.addr()).unwrap(); let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
@ -292,6 +308,7 @@ async fn test_http1_keepalive_disabled() {
HttpService::build() HttpService::build()
.keep_alive(KeepAlive::Disabled) .keep_alive(KeepAlive::Disabled)
.h1(|_| future::ok::<_, ()>(Response::Ok().finish())) .h1(|_| future::ok::<_, ()>(Response::Ok().finish()))
.tcp()
}); });
let mut stream = net::TcpStream::connect(srv.addr()).unwrap(); let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
@ -313,7 +330,8 @@ async fn test_content_length() {
}; };
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::build().h1(|req: Request| { HttpService::build()
.h1(|req: Request| {
let indx: usize = req.uri().path()[1..].parse().unwrap(); let indx: usize = req.uri().path()[1..].parse().unwrap();
let statuses = [ let statuses = [
StatusCode::NO_CONTENT, StatusCode::NO_CONTENT,
@ -325,6 +343,7 @@ async fn test_content_length() {
]; ];
future::ok::<_, ()>(Response::new(statuses[indx])) future::ok::<_, ()>(Response::new(statuses[indx]))
}) })
.tcp()
}); });
let header = HeaderName::from_static("content-length"); let header = HeaderName::from_static("content-length");
@ -377,7 +396,7 @@ async fn test_h1_headers() {
); );
} }
future::ok::<_, ()>(builder.body(data.clone())) future::ok::<_, ()>(builder.body(data.clone()))
}) }).tcp()
}); });
let response = srv.get("/").send().await.unwrap(); let response = srv.get("/").send().await.unwrap();
@ -413,7 +432,9 @@ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
#[actix_rt::test] #[actix_rt::test]
async fn test_h1_body() { async fn test_h1_body() {
let mut srv = TestServer::start(|| { let mut srv = TestServer::start(|| {
HttpService::build().h1(|_| ok::<_, ()>(Response::Ok().body(STR))) HttpService::build()
.h1(|_| ok::<_, ()>(Response::Ok().body(STR)))
.tcp()
}); });
let response = srv.get("/").send().await.unwrap(); let response = srv.get("/").send().await.unwrap();
@ -427,7 +448,9 @@ async fn test_h1_body() {
#[actix_rt::test] #[actix_rt::test]
async fn test_h1_head_empty() { async fn test_h1_head_empty() {
let mut srv = TestServer::start(|| { let mut srv = TestServer::start(|| {
HttpService::build().h1(|_| ok::<_, ()>(Response::Ok().body(STR))) HttpService::build()
.h1(|_| ok::<_, ()>(Response::Ok().body(STR)))
.tcp()
}); });
let response = srv.head("/").send().await.unwrap(); let response = srv.head("/").send().await.unwrap();
@ -449,9 +472,11 @@ async fn test_h1_head_empty() {
#[actix_rt::test] #[actix_rt::test]
async fn test_h1_head_binary() { async fn test_h1_head_binary() {
let mut srv = TestServer::start(|| { let mut srv = TestServer::start(|| {
HttpService::build().h1(|_| { HttpService::build()
.h1(|_| {
ok::<_, ()>(Response::Ok().content_length(STR.len() as u64).body(STR)) ok::<_, ()>(Response::Ok().content_length(STR.len() as u64).body(STR))
}) })
.tcp()
}); });
let response = srv.head("/").send().await.unwrap(); let response = srv.head("/").send().await.unwrap();
@ -473,7 +498,9 @@ async fn test_h1_head_binary() {
#[actix_rt::test] #[actix_rt::test]
async fn test_h1_head_binary2() { async fn test_h1_head_binary2() {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::build().h1(|_| ok::<_, ()>(Response::Ok().body(STR))) HttpService::build()
.h1(|_| ok::<_, ()>(Response::Ok().body(STR)))
.tcp()
}); });
let response = srv.head("/").send().await.unwrap(); let response = srv.head("/").send().await.unwrap();
@ -491,12 +518,14 @@ async fn test_h1_head_binary2() {
#[actix_rt::test] #[actix_rt::test]
async fn test_h1_body_length() { async fn test_h1_body_length() {
let mut srv = TestServer::start(|| { let mut srv = TestServer::start(|| {
HttpService::build().h1(|_| { HttpService::build()
.h1(|_| {
let body = once(ok(Bytes::from_static(STR.as_ref()))); let body = once(ok(Bytes::from_static(STR.as_ref())));
ok::<_, ()>( ok::<_, ()>(
Response::Ok().body(body::SizedStream::new(STR.len() as u64, body)), Response::Ok().body(body::SizedStream::new(STR.len() as u64, body)),
) )
}) })
.tcp()
}); });
let response = srv.get("/").send().await.unwrap(); let response = srv.get("/").send().await.unwrap();
@ -510,7 +539,8 @@ async fn test_h1_body_length() {
#[actix_rt::test] #[actix_rt::test]
async fn test_h1_body_chunked_explicit() { async fn test_h1_body_chunked_explicit() {
let mut srv = TestServer::start(|| { let mut srv = TestServer::start(|| {
HttpService::build().h1(|_| { HttpService::build()
.h1(|_| {
let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref()))); let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref())));
ok::<_, ()>( ok::<_, ()>(
Response::Ok() Response::Ok()
@ -518,6 +548,7 @@ async fn test_h1_body_chunked_explicit() {
.streaming(body), .streaming(body),
) )
}) })
.tcp()
}); });
let response = srv.get("/").send().await.unwrap(); let response = srv.get("/").send().await.unwrap();
@ -542,10 +573,12 @@ async fn test_h1_body_chunked_explicit() {
#[actix_rt::test] #[actix_rt::test]
async fn test_h1_body_chunked_implicit() { async fn test_h1_body_chunked_implicit() {
let mut srv = TestServer::start(|| { let mut srv = TestServer::start(|| {
HttpService::build().h1(|_| { HttpService::build()
.h1(|_| {
let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref()))); let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref())));
ok::<_, ()>(Response::Ok().streaming(body)) ok::<_, ()>(Response::Ok().streaming(body))
}) })
.tcp()
}); });
let response = srv.get("/").send().await.unwrap(); let response = srv.get("/").send().await.unwrap();
@ -568,8 +601,8 @@ async fn test_h1_body_chunked_implicit() {
#[actix_rt::test] #[actix_rt::test]
async fn test_h1_response_http_error_handling() { async fn test_h1_response_http_error_handling() {
let mut srv = TestServer::start(|| { let mut srv = TestServer::start(|| {
HttpService::build().h1(factory_fn_cfg(|_: &ServerConfig| { HttpService::build()
ok::<_, ()>(pipeline(|_| { .h1(service_fn(|_| {
let broken_header = Bytes::from_static(b"\0\0\0"); let broken_header = Bytes::from_static(b"\0\0\0");
ok::<_, ()>( ok::<_, ()>(
Response::Ok() Response::Ok()
@ -577,7 +610,7 @@ async fn test_h1_response_http_error_handling() {
.body(STR), .body(STR),
) )
})) }))
})) .tcp()
}); });
let response = srv.get("/").send().await.unwrap(); let response = srv.get("/").send().await.unwrap();
@ -593,6 +626,7 @@ async fn test_h1_service_error() {
let mut srv = TestServer::start(|| { let mut srv = TestServer::start(|| {
HttpService::build() HttpService::build()
.h1(|_| future::err::<Response, Error>(error::ErrorBadRequest("error"))) .h1(|_| future::err::<Response, Error>(error::ErrorBadRequest("error")))
.tcp()
}); });
let response = srv.get("/").send().await.unwrap(); let response = srv.get("/").send().await.unwrap();
@ -612,6 +646,7 @@ async fn test_h1_on_connect() {
assert!(req.extensions().contains::<usize>()); assert!(req.extensions().contains::<usize>());
future::ok::<_, ()>(Response::Ok().finish()) future::ok::<_, ()>(Response::Ok().finish())
}) })
.tcp()
}); });
let response = srv.get("/").send().await.unwrap(); let response = srv.get("/").send().await.unwrap();

View File

@ -40,6 +40,7 @@ async fn test_simple() {
HttpService::build() HttpService::build()
.upgrade(actix_service::service_fn(ws_service)) .upgrade(actix_service::service_fn(ws_service))
.finish(|_| future::ok::<_, ()>(Response::NotFound())) .finish(|_| future::ok::<_, ()>(Response::NotFound()))
.tcp()
}); });
// client service // client service

View File

@ -78,6 +78,7 @@ async fn test_params() {
.service(put_param_test) .service(put_param_test)
.service(delete_param_test), .service(delete_param_test),
) )
.tcp()
}); });
let request = srv.request(http::Method::GET, srv.url("/test/it")); let request = srv.request(http::Method::GET, srv.url("/test/it"));
@ -107,6 +108,7 @@ async fn test_body() {
.service(patch_test) .service(patch_test)
.service(test), .service(test),
) )
.tcp()
}); });
let request = srv.request(http::Method::GET, srv.url("/test")); let request = srv.request(http::Method::GET, srv.url("/test"));
let response = request.send().await.unwrap(); let response = request.send().await.unwrap();
@ -149,7 +151,8 @@ async fn test_body() {
#[actix_rt::test] #[actix_rt::test]
async fn test_auto_async() { async fn test_auto_async() {
let srv = TestServer::start(|| HttpService::new(App::new().service(auto_async))); let srv =
TestServer::start(|| HttpService::new(App::new().service(auto_async)).tcp());
let request = srv.request(http::Method::GET, srv.url("/test")); let request = srv.request(http::Method::GET, srv.url("/test"));
let response = request.send().await.unwrap(); let response = request.send().await.unwrap();

View File

@ -67,7 +67,8 @@ actix-web = { version = "2.0.0-alpha.1", features=["openssl"] }
actix-http = { version = "0.3.0-alpha.1", features=["openssl"] } actix-http = { version = "0.3.0-alpha.1", features=["openssl"] }
actix-http-test = { version = "0.3.0-alpha.1", features=["openssl"] } actix-http-test = { version = "0.3.0-alpha.1", features=["openssl"] }
actix-utils = "0.5.0-alpha.1" actix-utils = "0.5.0-alpha.1"
actix-server = { version = "0.8.0-alpha.1", features=["openssl"] } actix-server = { version = "0.8.0-alpha.2" }
#actix-tls = { version = "0.1.0-alpha.1", features=["openssl"] }
brotli2 = { version="0.3.2" } brotli2 = { version="0.3.2" }
flate2 = { version="1.0.2" } flate2 = { version="1.0.2" }
env_logger = "0.6" env_logger = "0.6"

View File

@ -49,6 +49,7 @@ async fn test_simple() {
HttpService::new(App::new().service( HttpService::new(App::new().service(
web::resource("/").route(web::to(|| HttpResponse::Ok().body(STR))), web::resource("/").route(web::to(|| HttpResponse::Ok().body(STR))),
)) ))
.tcp()
}); });
let request = srv.get("/").header("x-test", "111").send(); let request = srv.get("/").header("x-test", "111").send();
@ -77,6 +78,7 @@ async fn test_json() {
HttpService::new(App::new().service( HttpService::new(App::new().service(
web::resource("/").route(web::to(|_: web::Json<String>| HttpResponse::Ok())), web::resource("/").route(web::to(|_: web::Json<String>| HttpResponse::Ok())),
)) ))
.tcp()
}); });
let request = srv let request = srv
@ -93,6 +95,7 @@ async fn test_form() {
HttpService::new(App::new().service(web::resource("/").route(web::to( HttpService::new(App::new().service(web::resource("/").route(web::to(
|_: web::Form<HashMap<String, String>>| HttpResponse::Ok(), |_: web::Form<HashMap<String, String>>| HttpResponse::Ok(),
)))) ))))
.tcp()
}); });
let mut data = HashMap::new(); let mut data = HashMap::new();
@ -112,6 +115,7 @@ async fn test_timeout() {
Ok::<_, Error>(HttpResponse::Ok().body(STR)) Ok::<_, Error>(HttpResponse::Ok().body(STR))
} }
})))) }))))
.tcp()
}); });
let connector = awc::Connector::new() let connector = awc::Connector::new()
@ -142,6 +146,7 @@ async fn test_timeout_override() {
Ok::<_, Error>(HttpResponse::Ok().body(STR)) Ok::<_, Error>(HttpResponse::Ok().body(STR))
} }
})))) }))))
.tcp()
}); });
let client = awc::Client::build() let client = awc::Client::build()
@ -168,9 +173,13 @@ async fn test_connection_reuse() {
num2.fetch_add(1, Ordering::Relaxed); num2.fetch_add(1, Ordering::Relaxed);
ok(io) ok(io)
}) })
.and_then(HttpService::new( .and_then(
App::new().service(web::resource("/").route(web::to(|| HttpResponse::Ok()))), HttpService::new(
)) App::new()
.service(web::resource("/").route(web::to(|| HttpResponse::Ok()))),
)
.tcp(),
)
}); });
let client = awc::Client::default(); let client = awc::Client::default();
@ -200,9 +209,13 @@ async fn test_connection_force_close() {
num2.fetch_add(1, Ordering::Relaxed); num2.fetch_add(1, Ordering::Relaxed);
ok(io) ok(io)
}) })
.and_then(HttpService::new( .and_then(
App::new().service(web::resource("/").route(web::to(|| HttpResponse::Ok()))), HttpService::new(
)) App::new()
.service(web::resource("/").route(web::to(|| HttpResponse::Ok()))),
)
.tcp(),
)
}); });
let client = awc::Client::default(); let client = awc::Client::default();
@ -232,12 +245,15 @@ async fn test_connection_server_close() {
num2.fetch_add(1, Ordering::Relaxed); num2.fetch_add(1, Ordering::Relaxed);
ok(io) ok(io)
}) })
.and_then(HttpService::new( .and_then(
HttpService::new(
App::new().service( App::new().service(
web::resource("/") web::resource("/")
.route(web::to(|| HttpResponse::Ok().force_close().finish())), .route(web::to(|| HttpResponse::Ok().force_close().finish())),
), ),
)) )
.tcp(),
)
}); });
let client = awc::Client::default(); let client = awc::Client::default();
@ -267,9 +283,12 @@ async fn test_connection_wait_queue() {
num2.fetch_add(1, Ordering::Relaxed); num2.fetch_add(1, Ordering::Relaxed);
ok(io) ok(io)
}) })
.and_then(HttpService::new(App::new().service( .and_then(
HttpService::new(App::new().service(
web::resource("/").route(web::to(|| HttpResponse::Ok().body(STR))), web::resource("/").route(web::to(|| HttpResponse::Ok().body(STR))),
))) ))
.tcp(),
)
}); });
let client = awc::Client::build() let client = awc::Client::build()
@ -308,12 +327,15 @@ async fn test_connection_wait_queue_force_close() {
num2.fetch_add(1, Ordering::Relaxed); num2.fetch_add(1, Ordering::Relaxed);
ok(io) ok(io)
}) })
.and_then(HttpService::new( .and_then(
HttpService::new(
App::new().service( App::new().service(
web::resource("/") web::resource("/")
.route(web::to(|| HttpResponse::Ok().force_close().body(STR))), .route(web::to(|| HttpResponse::Ok().force_close().body(STR))),
), ),
)) )
.tcp(),
)
}); });
let client = awc::Client::build() let client = awc::Client::build()
@ -353,6 +375,7 @@ async fn test_with_query_parameter() {
} }
}, },
))) )))
.tcp()
}); });
let res = awc::Client::new() let res = awc::Client::new()
@ -373,6 +396,7 @@ async fn test_no_decompress() {
res res
})), })),
)) ))
.tcp()
}); });
let mut res = awc::Client::new() let mut res = awc::Client::new()
@ -419,6 +443,7 @@ async fn test_client_gzip_encoding() {
.header("content-encoding", "gzip") .header("content-encoding", "gzip")
.body(data) .body(data)
})))) }))))
.tcp()
}); });
// client request // client request
@ -442,6 +467,7 @@ async fn test_client_gzip_encoding_large() {
.header("content-encoding", "gzip") .header("content-encoding", "gzip")
.body(data) .body(data)
})))) }))))
.tcp()
}); });
// client request // client request
@ -471,6 +497,7 @@ async fn test_client_gzip_encoding_large_random() {
.body(data) .body(data)
}, },
)))) ))))
.tcp()
}); });
// client request // client request
@ -495,6 +522,7 @@ async fn test_client_brotli_encoding() {
.body(data) .body(data)
}, },
)))) ))))
.tcp()
}); });
// client request // client request
@ -707,6 +735,7 @@ async fn test_client_cookie_handling() {
} }
}), }),
)) ))
.tcp()
}); });
let request = srv.get("/").cookie(cookie1.clone()).cookie(cookie2.clone()); let request = srv.get("/").cookie(cookie1.clone()).cookie(cookie2.clone());
@ -768,6 +797,7 @@ async fn client_basic_auth() {
} }
}), }),
)) ))
.tcp()
}); });
// set authorization header to Basic <base64 encoded username:password> // set authorization header to Basic <base64 encoded username:password>
@ -796,6 +826,7 @@ async fn client_bearer_auth() {
} }
}), }),
)) ))
.tcp()
}); });
// set authorization header to Bearer <token> // set authorization header to Bearer <token>

View File

@ -1,20 +1,16 @@
#![cfg(feature = "openssl")] #![cfg(feature = "openssl")]
use open_ssl::ssl::{SslAcceptor, SslConnector, SslFiletype, SslMethod, SslVerifyMode};
use std::io::Result;
use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc; use std::sync::Arc;
use actix_codec::{AsyncRead, AsyncWrite};
use actix_http::HttpService; use actix_http::HttpService;
use actix_http_test::TestServer; use actix_http_test::TestServer;
use actix_server::ssl::OpensslAcceptor;
use actix_service::{pipeline_factory, ServiceFactory}; use actix_service::{pipeline_factory, ServiceFactory};
use actix_web::http::Version; use actix_web::http::Version;
use actix_web::{web, App, HttpResponse}; use actix_web::{web, App, HttpResponse};
use futures::future::ok; use futures::future::ok;
use open_ssl::ssl::{SslAcceptor, SslConnector, SslFiletype, SslMethod, SslVerifyMode};
fn ssl_acceptor<T: AsyncRead + AsyncWrite>() -> Result<OpensslAcceptor<T, ()>> { fn ssl_acceptor() -> SslAcceptor {
// load ssl keys // load ssl keys
let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap(); let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
builder builder
@ -31,13 +27,12 @@ fn ssl_acceptor<T: AsyncRead + AsyncWrite>() -> Result<OpensslAcceptor<T, ()>> {
Err(open_ssl::ssl::AlpnError::NOACK) Err(open_ssl::ssl::AlpnError::NOACK)
} }
}); });
builder.set_alpn_protos(b"\x02h2")?; builder.set_alpn_protos(b"\x02h2").unwrap();
Ok(actix_server::ssl::OpensslAcceptor::new(builder.build())) builder.build()
} }
#[actix_rt::test] #[actix_rt::test]
async fn test_connection_reuse_h2() { async fn test_connection_reuse_h2() {
let openssl = ssl_acceptor().unwrap();
let num = Arc::new(AtomicUsize::new(0)); let num = Arc::new(AtomicUsize::new(0));
let num2 = num.clone(); let num2 = num.clone();
@ -47,15 +42,11 @@ async fn test_connection_reuse_h2() {
num2.fetch_add(1, Ordering::Relaxed); num2.fetch_add(1, Ordering::Relaxed);
ok(io) ok(io)
}) })
.and_then(
openssl
.clone()
.map_err(|e| println!("Openssl error: {}", e)),
)
.and_then( .and_then(
HttpService::build() HttpService::build()
.h2(App::new() .h2(App::new()
.service(web::resource("/").route(web::to(|| HttpResponse::Ok())))) .service(web::resource("/").route(web::to(|| HttpResponse::Ok()))))
.openssl(ssl_acceptor())
.map_err(|_| ()), .map_err(|_| ()),
) )
}); });

View File

@ -46,6 +46,7 @@ async fn test_simple() {
} }
}) })
.finish(|_| ok::<_, Error>(Response::NotFound())) .finish(|_| ok::<_, Error>(Response::NotFound()))
.tcp()
}); });
// client service // client service

View File

@ -7,7 +7,6 @@ use std::task::{Context, Poll};
use actix_http::{Extensions, Request, Response}; use actix_http::{Extensions, Request, Response};
use actix_router::{Path, ResourceDef, ResourceInfo, Router, Url}; use actix_router::{Path, ResourceDef, ResourceInfo, Router, Url};
use actix_server_config::ServerConfig;
use actix_service::boxed::{self, BoxService, BoxServiceFactory}; use actix_service::boxed::{self, BoxService, BoxServiceFactory};
use actix_service::{service_fn, Service, ServiceFactory}; use actix_service::{service_fn, Service, ServiceFactory};
use futures::future::{ok, FutureExt, LocalBoxFuture}; use futures::future::{ok, FutureExt, LocalBoxFuture};
@ -59,7 +58,7 @@ where
InitError = (), InitError = (),
>, >,
{ {
type Config = ServerConfig; type Config = ();
type Request = Request; type Request = Request;
type Response = ServiceResponse<B>; type Response = ServiceResponse<B>;
type Error = T::Error; type Error = T::Error;
@ -67,7 +66,7 @@ where
type Service = AppInitService<T::Service, B>; type Service = AppInitService<T::Service, B>;
type Future = AppInitResult<T, B>; type Future = AppInitResult<T, B>;
fn new_service(&self, cfg: &ServerConfig) -> Self::Future { fn new_service(&self, _: &()) -> Self::Future {
// update resource default service // update resource default service
let default = self.default.clone().unwrap_or_else(|| { let default = self.default.clone().unwrap_or_else(|| {
Rc::new(boxed::factory(service_fn(|req: ServiceRequest| { Rc::new(boxed::factory(service_fn(|req: ServiceRequest| {
@ -76,13 +75,6 @@ where
}); });
// App config // App config
{
let mut c = self.config.borrow_mut();
let loc_cfg = Rc::get_mut(&mut c.0).unwrap();
loc_cfg.secure = cfg.secure();
loc_cfg.addr = cfg.local_addr();
}
let mut config = AppService::new( let mut config = AppService::new(
self.config.borrow().clone(), self.config.borrow().clone(),
default.clone(), default.clone(),

View File

@ -2,11 +2,13 @@ use std::marker::PhantomData;
use std::sync::Arc; use std::sync::Arc;
use std::{fmt, io, net}; use std::{fmt, io, net};
use actix_http::{body::MessageBody, Error, HttpService, KeepAlive, Request, Response}; use actix_http::{
body::MessageBody, Error, HttpService, KeepAlive, Protocol, Request, Response,
};
use actix_rt::System; use actix_rt::System;
use actix_server::{Server, ServerBuilder}; use actix_server::{Server, ServerBuilder};
use actix_server_config::ServerConfig; use actix_service::{pipeline_factory, IntoServiceFactory, Service, ServiceFactory};
use actix_service::{IntoServiceFactory, Service, ServiceFactory}; use futures::future::ok;
use parking_lot::Mutex; use parking_lot::Mutex;
use net2::TcpBuilder; use net2::TcpBuilder;
@ -52,7 +54,7 @@ pub struct HttpServer<F, I, S, B>
where where
F: Fn() -> I + Send + Clone + 'static, F: Fn() -> I + Send + Clone + 'static,
I: IntoServiceFactory<S>, I: IntoServiceFactory<S>,
S: ServiceFactory<Config = ServerConfig, Request = Request>, S: ServiceFactory<Config = (), Request = Request>,
S::Error: Into<Error>, S::Error: Into<Error>,
S::InitError: fmt::Debug, S::InitError: fmt::Debug,
S::Response: Into<Response<B>>, S::Response: Into<Response<B>>,
@ -71,7 +73,7 @@ impl<F, I, S, B> HttpServer<F, I, S, B>
where where
F: Fn() -> I + Send + Clone + 'static, F: Fn() -> I + Send + Clone + 'static,
I: IntoServiceFactory<S>, I: IntoServiceFactory<S>,
S: ServiceFactory<Config = ServerConfig, Request = Request>, S: ServiceFactory<Config = (), Request = Request>,
S::Error: Into<Error> + 'static, S::Error: Into<Error> + 'static,
S::InitError: fmt::Debug, S::InitError: fmt::Debug,
S::Response: Into<Response<B>> + 'static, S::Response: Into<Response<B>> + 'static,
@ -137,8 +139,8 @@ where
/// can be used to limit the global SSL CPU usage. /// can be used to limit the global SSL CPU usage.
/// ///
/// By default max connections is set to a 256. /// By default max connections is set to a 256.
pub fn maxconnrate(mut self, num: usize) -> Self { pub fn maxconnrate(self, num: usize) -> Self {
self.builder = self.builder.maxconnrate(num); actix_tls::max_concurrent_ssl_connect(num);
self self
} }
@ -247,7 +249,9 @@ where
HttpService::build() HttpService::build()
.keep_alive(c.keep_alive) .keep_alive(c.keep_alive)
.client_timeout(c.client_timeout) .client_timeout(c.client_timeout)
.local_addr(addr)
.finish(factory()) .finish(factory())
.tcp()
}, },
)?; )?;
Ok(self) Ok(self)
@ -271,10 +275,6 @@ where
lst: net::TcpListener, lst: net::TcpListener,
acceptor: SslAcceptor, acceptor: SslAcceptor,
) -> io::Result<Self> { ) -> io::Result<Self> {
use actix_server::ssl::{OpensslAcceptor, SslError};
use actix_service::pipeline_factory;
let acceptor = OpensslAcceptor::new(acceptor);
let factory = self.factory.clone(); let factory = self.factory.clone();
let cfg = self.config.clone(); let cfg = self.config.clone();
let addr = lst.local_addr().unwrap(); let addr = lst.local_addr().unwrap();
@ -288,15 +288,12 @@ where
lst, lst,
move || { move || {
let c = cfg.lock(); let c = cfg.lock();
pipeline_factory(acceptor.clone().map_err(SslError::Ssl)).and_then(
HttpService::build() HttpService::build()
.keep_alive(c.keep_alive) .keep_alive(c.keep_alive)
.client_timeout(c.client_timeout) .client_timeout(c.client_timeout)
.client_disconnect(c.client_shutdown) .client_disconnect(c.client_shutdown)
.finish(factory()) .finish(factory())
.map_err(SslError::Service) .openssl(acceptor.clone())
.map_init_err(|_| ()),
)
}, },
)?; )?;
Ok(self) Ok(self)
@ -444,6 +441,8 @@ where
mut self, mut self,
lst: std::os::unix::net::UnixListener, lst: std::os::unix::net::UnixListener,
) -> io::Result<Self> { ) -> io::Result<Self> {
use actix_rt::net::UnixStream;
let cfg = self.config.clone(); let cfg = self.config.clone();
let factory = self.factory.clone(); let factory = self.factory.clone();
// todo duplicated: // todo duplicated:
@ -459,10 +458,12 @@ where
self.builder = self.builder.listen_uds(addr, lst, move || { self.builder = self.builder.listen_uds(addr, lst, move || {
let c = cfg.lock(); let c = cfg.lock();
pipeline_factory(|io: UnixStream| ok((io, Protocol::Http1, None))).and_then(
HttpService::build() HttpService::build()
.keep_alive(c.keep_alive) .keep_alive(c.keep_alive)
.client_timeout(c.client_timeout) .client_timeout(c.client_timeout)
.finish(factory()) .finish(factory()),
)
})?; })?;
Ok(self) Ok(self)
} }
@ -475,6 +476,8 @@ where
where where
A: AsRef<std::path::Path>, A: AsRef<std::path::Path>,
{ {
use actix_rt::net::UnixStream;
let cfg = self.config.clone(); let cfg = self.config.clone();
let factory = self.factory.clone(); let factory = self.factory.clone();
self.sockets.push(Socket { self.sockets.push(Socket {
@ -490,10 +493,13 @@ where
addr, addr,
move || { move || {
let c = cfg.lock(); let c = cfg.lock();
pipeline_factory(|io: UnixStream| ok((io, Protocol::Http1, None)))
.and_then(
HttpService::build() HttpService::build()
.keep_alive(c.keep_alive) .keep_alive(c.keep_alive)
.client_timeout(c.client_timeout) .client_timeout(c.client_timeout)
.finish(factory()) .finish(factory()),
)
}, },
)?; )?;
Ok(self) Ok(self)
@ -504,7 +510,7 @@ impl<F, I, S, B> HttpServer<F, I, S, B>
where where
F: Fn() -> I + Send + Clone + 'static, F: Fn() -> I + Send + Clone + 'static,
I: IntoServiceFactory<S>, I: IntoServiceFactory<S>,
S: ServiceFactory<Config = ServerConfig, Request = Request>, S: ServiceFactory<Config = (), Request = Request>,
S::Error: Into<Error>, S::Error: Into<Error>,
S::InitError: fmt::Debug, S::InitError: fmt::Debug,
S::Response: Into<Response<B>>, S::Response: Into<Response<B>>,
@ -585,8 +591,11 @@ fn openssl_acceptor(mut builder: SslAcceptorBuilder) -> io::Result<SslAcceptor>
builder.set_alpn_select_callback(|_, protos| { builder.set_alpn_select_callback(|_, protos| {
const H2: &[u8] = b"\x02h2"; const H2: &[u8] = b"\x02h2";
const H11: &[u8] = b"\x08http/1.1";
if protos.windows(3).any(|window| window == H2) { if protos.windows(3).any(|window| window == H2) {
Ok(b"h2") Ok(b"h2")
} else if protos.windows(9).any(|window| window == H11) {
Ok(b"http/1.1")
} else { } else {
Err(AlpnError::NOACK) Err(AlpnError::NOACK)
} }

View File

@ -6,7 +6,6 @@ use actix_http::http::{HttpTryFrom, Method, StatusCode, Uri, Version};
use actix_http::test::TestRequest as HttpTestRequest; use actix_http::test::TestRequest as HttpTestRequest;
use actix_http::{cookie::Cookie, Extensions, Request}; use actix_http::{cookie::Cookie, Extensions, Request};
use actix_router::{Path, ResourceDef, Url}; use actix_router::{Path, ResourceDef, Url};
use actix_server_config::ServerConfig;
use actix_service::{IntoService, IntoServiceFactory, Service, ServiceFactory}; use actix_service::{IntoService, IntoServiceFactory, Service, ServiceFactory};
use bytes::{Bytes, BytesMut}; use bytes::{Bytes, BytesMut};
use futures::future::ok; use futures::future::ok;
@ -71,16 +70,15 @@ pub async fn init_service<R, S, B, E>(
where where
R: IntoServiceFactory<S>, R: IntoServiceFactory<S>,
S: ServiceFactory< S: ServiceFactory<
Config = ServerConfig, Config = (),
Request = Request, Request = Request,
Response = ServiceResponse<B>, Response = ServiceResponse<B>,
Error = E, Error = E,
>, >,
S::InitError: std::fmt::Debug, S::InitError: std::fmt::Debug,
{ {
let cfg = ServerConfig::new("127.0.0.1:8080".parse().unwrap());
let srv = app.into_factory(); let srv = app.into_factory();
srv.new_service(&cfg).await.unwrap() srv.new_service(&()).await.unwrap()
} }
/// Calls service and waits for response future completion. /// Calls service and waits for response future completion.

View File

@ -27,7 +27,7 @@ path = "src/lib.rs"
default = [] default = []
# openssl # openssl
openssl = ["open-ssl", "actix-server/openssl", "awc/openssl"] openssl = ["open-ssl", "awc/openssl", ] # "actix-tls/openssl"]
[dependencies] [dependencies]
actix-service = "1.0.0-alpha.1" actix-service = "1.0.0-alpha.1"
@ -36,7 +36,6 @@ actix-connect = "1.0.0-alpha.1"
actix-utils = "0.5.0-alpha.1" actix-utils = "0.5.0-alpha.1"
actix-rt = "1.0.0-alpha.1" actix-rt = "1.0.0-alpha.1"
actix-server = "0.8.0-alpha.1" actix-server = "0.8.0-alpha.1"
actix-server-config = "0.3.0-alpha.1"
actix-testing = "0.3.0-alpha.1" actix-testing = "0.3.0-alpha.1"
awc = "0.3.0-alpha.1" awc = "0.3.0-alpha.1"

View File

@ -4,7 +4,7 @@ use actix_http::http::header::{
ContentEncoding, ACCEPT_ENCODING, CONTENT_ENCODING, CONTENT_LENGTH, ContentEncoding, ACCEPT_ENCODING, CONTENT_ENCODING, CONTENT_LENGTH,
TRANSFER_ENCODING, TRANSFER_ENCODING,
}; };
use actix_http::{h1, Error, HttpService, Response}; use actix_http::{Error, HttpService, Response};
use actix_http_test::TestServer; use actix_http_test::TestServer;
use brotli2::write::{BrotliDecoder, BrotliEncoder}; use brotli2::write::{BrotliDecoder, BrotliEncoder};
use bytes::Bytes; use bytes::Bytes;
@ -42,10 +42,10 @@ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
#[actix_rt::test] #[actix_rt::test]
async fn test_body() { async fn test_body() {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
h1::H1Service::new( HttpService::build()
App::new() .h1(App::new()
.service(web::resource("/").route(web::to(|| Response::Ok().body(STR)))), .service(web::resource("/").route(web::to(|| Response::Ok().body(STR)))))
) .tcp()
}); });
let mut response = srv.get("/").send().await.unwrap(); let mut response = srv.get("/").send().await.unwrap();
@ -60,11 +60,11 @@ async fn test_body() {
#[actix_rt::test] #[actix_rt::test]
async fn test_body_gzip() { async fn test_body_gzip() {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
h1::H1Service::new( HttpService::build()
App::new() .h1(App::new()
.wrap(Compress::new(ContentEncoding::Gzip)) .wrap(Compress::new(ContentEncoding::Gzip))
.service(web::resource("/").route(web::to(|| Response::Ok().body(STR)))), .service(web::resource("/").route(web::to(|| Response::Ok().body(STR)))))
) .tcp()
}); });
let mut response = srv let mut response = srv
@ -90,13 +90,13 @@ async fn test_body_gzip() {
#[actix_rt::test] #[actix_rt::test]
async fn test_body_gzip2() { async fn test_body_gzip2() {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
h1::H1Service::new( HttpService::build()
App::new() .h1(App::new()
.wrap(Compress::new(ContentEncoding::Gzip)) .wrap(Compress::new(ContentEncoding::Gzip))
.service(web::resource("/").route(web::to(|| { .service(web::resource("/").route(web::to(|| {
Response::Ok().body(STR).into_body::<dev::Body>() Response::Ok().body(STR).into_body::<dev::Body>()
}))), }))))
) .tcp()
}); });
let mut response = srv let mut response = srv
@ -122,8 +122,8 @@ async fn test_body_gzip2() {
#[actix_rt::test] #[actix_rt::test]
async fn test_body_encoding_override() { async fn test_body_encoding_override() {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
h1::H1Service::new( HttpService::build()
App::new() .h1(App::new()
.wrap(Compress::new(ContentEncoding::Gzip)) .wrap(Compress::new(ContentEncoding::Gzip))
.service(web::resource("/").route(web::to(|| { .service(web::resource("/").route(web::to(|| {
Response::Ok().encoding(ContentEncoding::Deflate).body(STR) Response::Ok().encoding(ContentEncoding::Deflate).body(STR)
@ -136,8 +136,8 @@ async fn test_body_encoding_override() {
response.encoding(ContentEncoding::Deflate); response.encoding(ContentEncoding::Deflate);
response response
}))), }))))
) .tcp()
}); });
// Builder // Builder
@ -187,14 +187,14 @@ async fn test_body_gzip_large() {
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
let data = srv_data.clone(); let data = srv_data.clone();
h1::H1Service::new( HttpService::build()
App::new() .h1(App::new()
.wrap(Compress::new(ContentEncoding::Gzip)) .wrap(Compress::new(ContentEncoding::Gzip))
.service( .service(
web::resource("/") web::resource("/")
.route(web::to(move || Response::Ok().body(data.clone()))), .route(web::to(move || Response::Ok().body(data.clone()))),
), ))
) .tcp()
}); });
let mut response = srv let mut response = srv
@ -227,14 +227,14 @@ async fn test_body_gzip_large_random() {
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
let data = srv_data.clone(); let data = srv_data.clone();
h1::H1Service::new( HttpService::build()
App::new() .h1(App::new()
.wrap(Compress::new(ContentEncoding::Gzip)) .wrap(Compress::new(ContentEncoding::Gzip))
.service( .service(
web::resource("/") web::resource("/")
.route(web::to(move || Response::Ok().body(data.clone()))), .route(web::to(move || Response::Ok().body(data.clone()))),
), ))
) .tcp()
}); });
let mut response = srv let mut response = srv
@ -261,15 +261,15 @@ async fn test_body_gzip_large_random() {
#[actix_rt::test] #[actix_rt::test]
async fn test_body_chunked_implicit() { async fn test_body_chunked_implicit() {
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
h1::H1Service::new( HttpService::build()
App::new() .h1(App::new()
.wrap(Compress::new(ContentEncoding::Gzip)) .wrap(Compress::new(ContentEncoding::Gzip))
.service(web::resource("/").route(web::get().to(move || { .service(web::resource("/").route(web::get().to(move || {
Response::Ok().streaming(once(ok::<_, Error>(Bytes::from_static( Response::Ok().streaming(once(ok::<_, Error>(Bytes::from_static(
STR.as_ref(), STR.as_ref(),
)))) ))))
}))), }))))
) .tcp()
}); });
let mut response = srv let mut response = srv
@ -299,12 +299,15 @@ async fn test_body_chunked_implicit() {
#[cfg(feature = "brotli")] #[cfg(feature = "brotli")]
async fn test_body_br_streaming() { async fn test_body_br_streaming() {
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
h1::H1Service::new(App::new().wrap(Compress::new(ContentEncoding::Br)).service( HttpService::build()
.h1(App::new().wrap(Compress::new(ContentEncoding::Br)).service(
web::resource("/").route(web::to(move || { web::resource("/").route(web::to(move || {
Response::Ok() Response::Ok().streaming(once(ok::<_, Error>(Bytes::from_static(
.streaming(once(ok::<_, Error>(Bytes::from_static(STR.as_ref())))) STR.as_ref(),
))))
})), })),
)) ))
.tcp()
}); });
let mut response = srv let mut response = srv
@ -329,9 +332,11 @@ async fn test_body_br_streaming() {
#[actix_rt::test] #[actix_rt::test]
async fn test_head_binary() { async fn test_head_binary() {
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
h1::H1Service::new(App::new().service(web::resource("/").route( HttpService::build()
.h1(App::new().service(web::resource("/").route(
web::head().to(move || Response::Ok().content_length(100).body(STR)), web::head().to(move || Response::Ok().content_length(100).body(STR)),
))) )))
.tcp()
}); });
let mut response = srv.head("/").send().await.unwrap(); let mut response = srv.head("/").send().await.unwrap();
@ -350,14 +355,18 @@ async fn test_head_binary() {
#[actix_rt::test] #[actix_rt::test]
async fn test_no_chunking() { async fn test_no_chunking() {
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
h1::H1Service::new(App::new().service(web::resource("/").route(web::to( HttpService::build()
move || { .h1(
App::new().service(web::resource("/").route(web::to(move || {
Response::Ok() Response::Ok()
.no_chunking() .no_chunking()
.content_length(STR.len() as u64) .content_length(STR.len() as u64)
.streaming(once(ok::<_, Error>(Bytes::from_static(STR.as_ref())))) .streaming(once(ok::<_, Error>(Bytes::from_static(
}, STR.as_ref(),
)))) ))))
}))),
)
.tcp()
}); });
let mut response = srv.get("/").send().await.unwrap(); let mut response = srv.get("/").send().await.unwrap();
@ -373,13 +382,13 @@ async fn test_no_chunking() {
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))] #[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]
async fn test_body_deflate() { async fn test_body_deflate() {
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
h1::H1Service::new( HttpService::build()
App::new() .h1(App::new()
.wrap(Compress::new(ContentEncoding::Deflate)) .wrap(Compress::new(ContentEncoding::Deflate))
.service( .service(
web::resource("/").route(web::to(move || Response::Ok().body(STR))), web::resource("/").route(web::to(move || Response::Ok().body(STR))),
), ))
) .tcp()
}); });
// client request // client request
@ -405,9 +414,11 @@ async fn test_body_deflate() {
#[cfg(any(feature = "brotli"))] #[cfg(any(feature = "brotli"))]
async fn test_body_brotli() { async fn test_body_brotli() {
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
h1::H1Service::new(App::new().wrap(Compress::new(ContentEncoding::Br)).service( HttpService::build()
.h1(App::new().wrap(Compress::new(ContentEncoding::Br)).service(
web::resource("/").route(web::to(move || Response::Ok().body(STR))), web::resource("/").route(web::to(move || Response::Ok().body(STR))),
)) ))
.tcp()
}); });
// client request // client request
@ -434,12 +445,12 @@ async fn test_body_brotli() {
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))] #[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]
async fn test_encoding() { async fn test_encoding() {
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
HttpService::new( HttpService::build()
App::new().wrap(Compress::default()).service( .h1(App::new().wrap(Compress::default()).service(
web::resource("/") web::resource("/")
.route(web::to(move |body: Bytes| Response::Ok().body(body))), .route(web::to(move |body: Bytes| Response::Ok().body(body))),
), ))
) .tcp()
}); });
// client request // client request
@ -463,12 +474,12 @@ async fn test_encoding() {
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))] #[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]
async fn test_gzip_encoding() { async fn test_gzip_encoding() {
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
HttpService::new( HttpService::build()
App::new().service( .h1(App::new().service(
web::resource("/") web::resource("/")
.route(web::to(move |body: Bytes| Response::Ok().body(body))), .route(web::to(move |body: Bytes| Response::Ok().body(body))),
), ))
) .tcp()
}); });
// client request // client request
@ -493,12 +504,12 @@ async fn test_gzip_encoding() {
async fn test_gzip_encoding_large() { async fn test_gzip_encoding_large() {
let data = STR.repeat(10); let data = STR.repeat(10);
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
h1::H1Service::new( HttpService::build()
App::new().service( .h1(App::new().service(
web::resource("/") web::resource("/")
.route(web::to(move |body: Bytes| Response::Ok().body(body))), .route(web::to(move |body: Bytes| Response::Ok().body(body))),
), ))
) .tcp()
}); });
// client request // client request
@ -527,12 +538,12 @@ async fn test_reading_gzip_encoding_large_random() {
.collect::<String>(); .collect::<String>();
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
HttpService::new( HttpService::build()
App::new().service( .h1(App::new().service(
web::resource("/") web::resource("/")
.route(web::to(move |body: Bytes| Response::Ok().body(body))), .route(web::to(move |body: Bytes| Response::Ok().body(body))),
), ))
) .tcp()
}); });
// client request // client request
@ -557,12 +568,12 @@ async fn test_reading_gzip_encoding_large_random() {
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))] #[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]
async fn test_reading_deflate_encoding() { async fn test_reading_deflate_encoding() {
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
h1::H1Service::new( HttpService::build()
App::new().service( .h1(App::new().service(
web::resource("/") web::resource("/")
.route(web::to(move |body: Bytes| Response::Ok().body(body))), .route(web::to(move |body: Bytes| Response::Ok().body(body))),
), ))
) .tcp()
}); });
let mut e = ZlibEncoder::new(Vec::new(), Compression::default()); let mut e = ZlibEncoder::new(Vec::new(), Compression::default());
@ -587,12 +598,12 @@ async fn test_reading_deflate_encoding() {
async fn test_reading_deflate_encoding_large() { async fn test_reading_deflate_encoding_large() {
let data = STR.repeat(10); let data = STR.repeat(10);
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
h1::H1Service::new( HttpService::build()
App::new().service( .h1(App::new().service(
web::resource("/") web::resource("/")
.route(web::to(move |body: Bytes| Response::Ok().body(body))), .route(web::to(move |body: Bytes| Response::Ok().body(body))),
), ))
) .tcp()
}); });
let mut e = ZlibEncoder::new(Vec::new(), Compression::default()); let mut e = ZlibEncoder::new(Vec::new(), Compression::default());
@ -621,12 +632,12 @@ async fn test_reading_deflate_encoding_large_random() {
.collect::<String>(); .collect::<String>();
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
h1::H1Service::new( HttpService::build()
App::new().service( .h1(App::new().service(
web::resource("/") web::resource("/")
.route(web::to(move |body: Bytes| Response::Ok().body(body))), .route(web::to(move |body: Bytes| Response::Ok().body(body))),
), ))
) .tcp()
}); });
let mut e = ZlibEncoder::new(Vec::new(), Compression::default()); let mut e = ZlibEncoder::new(Vec::new(), Compression::default());
@ -651,12 +662,12 @@ async fn test_reading_deflate_encoding_large_random() {
#[cfg(feature = "brotli")] #[cfg(feature = "brotli")]
async fn test_brotli_encoding() { async fn test_brotli_encoding() {
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
h1::H1Service::new( HttpService::build()
App::new().service( .h1(App::new().service(
web::resource("/") web::resource("/")
.route(web::to(move |body: Bytes| Response::Ok().body(body))), .route(web::to(move |body: Bytes| Response::Ok().body(body))),
), ))
) .tcp()
}); });
let mut e = BrotliEncoder::new(Vec::new(), 5); let mut e = BrotliEncoder::new(Vec::new(), 5);
@ -681,12 +692,12 @@ async fn test_brotli_encoding() {
async fn test_brotli_encoding_large() { async fn test_brotli_encoding_large() {
let data = STR.repeat(10); let data = STR.repeat(10);
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
h1::H1Service::new( HttpService::build()
App::new().service( .h1(App::new().service(
web::resource("/") web::resource("/")
.route(web::to(move |body: Bytes| Response::Ok().body(body))), .route(web::to(move |body: Bytes| Response::Ok().body(body))),
), ))
) .tcp()
}); });
let mut e = BrotliEncoder::new(Vec::new(), 5); let mut e = BrotliEncoder::new(Vec::new(), 5);