Skip to content

add HttpServer::new_async #2413

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
161 changes: 92 additions & 69 deletions actix-web/src/server.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
use std::{
any::Any,
cmp, fmt, io,
marker::PhantomData,
net,
cmp, fmt,
future::Future,
io, net,
sync::{Arc, Mutex},
time::Duration,
};

use actix_http::{body::MessageBody, Extensions, HttpService, KeepAlive, Request, Response};
use actix_http::{
body::BoxBody, body::MessageBody, Extensions, HttpService, KeepAlive, Request, Response,
};
use actix_server::{Server, ServerBuilder};
use actix_service::{
map_config, IntoServiceFactory, Service, ServiceFactory, ServiceFactoryExt as _,
fn_factory_with_config, map_config, IntoServiceFactory, ServiceFactory,
ServiceFactoryExt as _,
};

#[cfg(feature = "openssl")]
Expand Down Expand Up @@ -49,42 +52,96 @@ struct Config {
/// .await
/// }
/// ```
pub struct HttpServer<F, I, S, B>
where
F: Fn() -> I + Send + Clone + 'static,
I: IntoServiceFactory<S, Request>,
S: ServiceFactory<Request, Config = AppConfig>,
S::Error: Into<Error>,
S::InitError: fmt::Debug,
S::Response: Into<Response<B>>,
B: MessageBody,
{
pub(super) factory: F,
pub struct HttpServer<SF> {
pub(super) factory: SF,
config: Arc<Mutex<Config>>,
backlog: u32,
sockets: Vec<Socket>,
builder: ServerBuilder,
#[allow(clippy::type_complexity)]
on_connect_fn: Option<Arc<dyn Fn(&dyn Any, &mut Extensions) + Send + Sync>>,
_phantom: PhantomData<(S, B)>,
}

impl<F, I, S, B> HttpServer<F, I, S, B>
where
F: Fn() -> I + Send + Clone + 'static,
I: IntoServiceFactory<S, Request>,
impl HttpServer<()> {
/// Create new HTTP server with application factory
pub fn new<F, I, SF, B>(
factory_fn: F,
) -> HttpServer<
impl ServiceFactory<
Request,
Config = AppConfig,
Error = Response<BoxBody>,
InitError = SF::InitError,
Response = Response<B>,
> + Send
+ Clone,
>
where
F: FnOnce() -> I + Send + Clone + 'static,
I: IntoServiceFactory<SF, Request>,
SF: ServiceFactory<Request, Config = AppConfig> + 'static,
SF::Error: Into<Error>,
SF::InitError: fmt::Debug,
SF::Response: Into<Response<B>>,
B: MessageBody + 'static,
{
let factory = fn_factory_with_config(move |cfg| {
let factory_fn = factory_fn.clone();
async move { factory_fn().into_factory().new_service(cfg).await }
})
.map(|resp| resp.into())
.map_err(|err| err.into().error_response().into());

HttpServer::new2(factory)
}

S: ServiceFactory<Request, Config = AppConfig> + 'static,
S::Error: Into<Error> + 'static,
S::InitError: fmt::Debug,
S::Response: Into<Response<B>> + 'static,
<S::Service as Service<Request>>::Future: 'static,
S::Service: 'static,
pub fn new_async<F, Fut, SF, B>(
factory_fn: F,
) -> HttpServer<
impl ServiceFactory<
Request,
Config = AppConfig,
Error = Response<BoxBody>,
InitError = SF::InitError,
Response = Response<B>,
> + Send
+ Clone,
>
where
F: FnOnce() -> Fut + Send + Clone + 'static,
Fut: Future,
Fut::Output: IntoServiceFactory<SF, Request>,
SF: ServiceFactory<Request, Config = AppConfig> + 'static,
SF::Error: Into<Error>,
SF::InitError: fmt::Debug,
SF::Response: Into<Response<B>>,
B: MessageBody + 'static,
{
let factory = fn_factory_with_config(move |cfg| {
let factory_fn = factory_fn.clone();
async move { factory_fn().await.into_factory().new_service(cfg).await }
})
.map(|resp| resp.into())
.map_err(|err| err.into().error_response().into());

HttpServer::new2(factory)
}
}

impl<SF, B> HttpServer<SF>
where
SF: ServiceFactory<
Request,
Config = AppConfig,
Response = Response<B>,
Error = Response<BoxBody>,
> + Send
+ Clone
+ 'static,
SF::InitError: fmt::Debug,
B: MessageBody + 'static,
{
/// Create new HTTP server with application factory
pub fn new(factory: F) -> Self {
fn new2(factory: SF) -> Self {
HttpServer {
factory,
config: Arc::new(Mutex::new(Config {
Expand All @@ -97,7 +154,6 @@ where
sockets: Vec::new(),
builder: ServerBuilder::default(),
on_connect_fn: None,
_phantom: PhantomData,
}
}

Expand All @@ -111,7 +167,7 @@ where
/// - `actix_web::rt::net::TcpStream` when no encryption is used.
///
/// See the `on_connect` example for additional details.
pub fn on_connect<CB>(self, f: CB) -> HttpServer<F, I, S, B>
pub fn on_connect<CB>(self, f: CB) -> Self
where
CB: Fn(&dyn Any, &mut Extensions) + Send + Sync + 'static,
{
Expand All @@ -122,7 +178,6 @@ where
sockets: self.sockets,
builder: self.builder,
on_connect_fn: Some(Arc::new(f)),
_phantom: PhantomData,
}
}

Expand Down Expand Up @@ -314,11 +369,7 @@ where
})
};

let fac = factory()
.into_factory()
.map_err(|err| err.into().error_response());

svc.finish(map_config(fac, move |_| {
svc.finish(map_config(factory.clone(), move |_| {
AppConfig::new(false, host.clone(), addr)
}))
.tcp()
Expand Down Expand Up @@ -372,11 +423,7 @@ where
svc
};

let fac = factory()
.into_factory()
.map_err(|err| err.into().error_response());

svc.finish(map_config(fac, move |_| {
svc.finish(map_config(factory.clone(), move |_| {
AppConfig::new(true, host.clone(), addr)
}))
.openssl(acceptor.clone())
Expand Down Expand Up @@ -430,11 +477,7 @@ where
svc
};

let fac = factory()
.into_factory()
.map_err(|err| err.into().error_response());

svc.finish(map_config(fac, move |_| {
svc.finish(map_config(factory.clone(), move |_| {
AppConfig::new(true, host.clone(), addr)
}))
.rustls(config.clone())
Expand Down Expand Up @@ -556,11 +599,7 @@ where
.on_connect_ext(move |io: &_, ext: _| (handler)(io as &dyn Any, ext));
}

let fac = factory()
.into_factory()
.map_err(|err| err.into().error_response());

svc.finish(map_config(fac, move |_| config.clone()))
svc.finish(map_config(factory.clone(), move |_| config.clone()))
})
})?;
Ok(self)
Expand Down Expand Up @@ -597,35 +636,19 @@ where
socket_addr,
);

let fac = factory()
.into_factory()
.map_err(|err| err.into().error_response());

fn_service(|io: UnixStream| async { Ok((io, Protocol::Http1, None)) }).and_then(
HttpService::build()
.keep_alive(c.keep_alive)
.client_request_timeout(c.client_request_timeout)
.client_disconnect_timeout(c.client_disconnect_timeout)
.finish(map_config(fac, move |_| config.clone())),
.finish(map_config(factory.clone(), move |_| config.clone())),
)
},
)?;

Ok(self)
}
}

impl<F, I, S, B> HttpServer<F, I, S, B>
where
F: Fn() -> I + Send + Clone + 'static,
I: IntoServiceFactory<S, Request>,
S: ServiceFactory<Request, Config = AppConfig>,
S::Error: Into<Error>,
S::InitError: fmt::Debug,
S::Response: Into<Response<B>>,
S::Service: 'static,
B: MessageBody,
{
/// Start listening for incoming connections.
///
/// This method starts number of HTTP workers in separate threads.
Expand Down