1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-06-02 13:29:24 +00:00
actix-web/src/app_service.rs

371 lines
11 KiB
Rust
Raw Normal View History

use std::cell::RefCell;
use std::rc::Rc;
use actix_http::{Extensions, Request};
2021-01-06 11:35:30 +00:00
use actix_router::{Path, ResourceDef, Router, Url};
2019-11-26 05:25:50 +00:00
use actix_service::boxed::{self, BoxService, BoxServiceFactory};
2019-12-08 13:25:24 +00:00
use actix_service::{fn_service, Service, ServiceFactory};
2021-01-06 11:35:30 +00:00
use futures_core::future::LocalBoxFuture;
use futures_util::future::join_all;
use crate::data::FnDataFactory;
use crate::error::Error;
use crate::guard::Guard;
use crate::request::{HttpRequest, HttpRequestPool};
use crate::rmap::ResourceMap;
2019-11-20 17:33:22 +00:00
use crate::service::{AppServiceFactory, ServiceRequest, ServiceResponse};
use crate::{
config::{AppConfig, AppService},
HttpResponse,
};
2019-07-17 09:48:37 +00:00
type Guards = Vec<Box<dyn Guard>>;
2019-11-26 05:25:50 +00:00
type HttpService = BoxService<ServiceRequest, ServiceResponse, Error>;
type HttpNewService = BoxServiceFactory<(), ServiceRequest, ServiceResponse, Error, ()>;
/// Service factory to convert `Request` to a `ServiceRequest<S>`.
2019-03-17 03:17:27 +00:00
/// It also executes data factories.
pub struct AppInit<T, B>
where
2019-11-20 17:33:22 +00:00
T: ServiceFactory<
ServiceRequest,
2019-05-12 15:34:51 +00:00
Config = (),
Response = ServiceResponse<B>,
Error = Error,
InitError = (),
>,
{
pub(crate) endpoint: T,
pub(crate) extensions: RefCell<Option<Extensions>>,
2021-01-06 11:35:30 +00:00
pub(crate) async_data_factories: Rc<[FnDataFactory]>,
2019-11-20 17:33:22 +00:00
pub(crate) services: Rc<RefCell<Vec<Box<dyn AppServiceFactory>>>>,
pub(crate) default: Option<Rc<HttpNewService>>,
pub(crate) factory_ref: Rc<RefCell<Option<AppRoutingFactory>>>,
pub(crate) external: RefCell<Vec<ResourceDef>>,
}
impl<T, B> ServiceFactory<Request> for AppInit<T, B>
where
2019-11-20 17:33:22 +00:00
T: ServiceFactory<
ServiceRequest,
2019-05-12 15:34:51 +00:00
Config = (),
Response = ServiceResponse<B>,
Error = Error,
InitError = (),
>,
2021-01-06 11:35:30 +00:00
T::Future: 'static,
{
type Response = ServiceResponse<B>;
type Error = T::Error;
type Config = AppConfig;
type Service = AppInitService<T::Service, B>;
type InitError = T::InitError;
2021-01-06 11:35:30 +00:00
type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>;
fn new_service(&self, config: AppConfig) -> Self::Future {
2021-01-09 18:06:49 +00:00
// set AppService's default service to 404 NotFound
// if no user defined default service exists.
let default = self.default.clone().unwrap_or_else(|| {
2021-01-06 11:35:30 +00:00
Rc::new(boxed::factory(fn_service(|req: ServiceRequest| async {
Ok(req.into_response(HttpResponse::NotFound()))
})))
});
// App config
let mut config = AppService::new(config, default.clone());
// register services
2020-05-17 01:54:42 +00:00
std::mem::take(&mut *self.services.borrow_mut())
.into_iter()
.for_each(|mut srv| srv.register(&mut config));
let mut rmap = ResourceMap::new(ResourceDef::new(""));
let (config, services) = config.into_services();
2021-01-06 11:35:30 +00:00
// complete pipeline creation.
*self.factory_ref.borrow_mut() = Some(AppRoutingFactory {
default,
2020-10-10 00:26:05 +00:00
services: services
.into_iter()
.map(|(mut rdef, srv, guards, nested)| {
rmap.add(&mut rdef, nested);
(rdef, srv, RefCell::new(guards))
})
.collect::<Vec<_>>()
.into_boxed_slice()
.into(),
});
// external resources
2020-05-17 01:54:42 +00:00
for mut rdef in std::mem::take(&mut *self.external.borrow_mut()) {
rmap.add(&mut rdef, None);
}
// complete ResourceMap tree creation
let rmap = Rc::new(rmap);
rmap.finish(rmap.clone());
2021-01-06 11:35:30 +00:00
// construct all async data factory futures
let factory_futs = join_all(self.async_data_factories.iter().map(|f| f()));
2021-01-06 11:35:30 +00:00
// construct app service and middleware service factory future.
let endpoint_fut = self.endpoint.new_service(());
2021-01-06 11:35:30 +00:00
// take extensions or create new one as app data container.
let mut app_data = self
.extensions
.borrow_mut()
.take()
.unwrap_or_else(Extensions::new);
2021-01-06 11:35:30 +00:00
Box::pin(async move {
// async data factories
let async_data_factories = factory_futs
.await
.into_iter()
.collect::<Result<Vec<_>, _>>()
.map_err(|_| ())?;
2021-01-06 11:35:30 +00:00
// app service and middleware
let service = endpoint_fut.await?;
2021-01-06 11:35:30 +00:00
// populate app data container from (async) data factories.
async_data_factories.iter().for_each(|factory| {
factory.create(&mut app_data);
});
2021-01-06 11:35:30 +00:00
Ok(AppInitService {
service,
app_data: Rc::new(app_data),
app_state: AppInitServiceState::new(rmap, config),
2021-01-06 11:35:30 +00:00
})
})
}
}
2021-01-15 05:38:50 +00:00
/// Service that takes a [`Request`] and delegates to a service that take a [`ServiceRequest`].
pub struct AppInitService<T, B>
where
T: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
{
service: T,
app_data: Rc<Extensions>,
app_state: Rc<AppInitServiceState>,
}
2021-01-15 05:38:50 +00:00
/// A collection of [`AppInitService`] state that shared across `HttpRequest`s.
pub(crate) struct AppInitServiceState {
rmap: Rc<ResourceMap>,
config: AppConfig,
pool: HttpRequestPool,
}
impl AppInitServiceState {
pub(crate) fn new(rmap: Rc<ResourceMap>, config: AppConfig) -> Rc<Self> {
Rc::new(AppInitServiceState {
rmap,
config,
// TODO: AppConfig can be used to pass user defined HttpRequestPool capacity.
pool: HttpRequestPool::default(),
})
}
#[inline]
pub(crate) fn rmap(&self) -> &ResourceMap {
&*self.rmap
}
#[inline]
pub(crate) fn config(&self) -> &AppConfig {
&self.config
}
#[inline]
pub(crate) fn pool(&self) -> &HttpRequestPool {
&self.pool
}
}
impl<T, B> Service<Request> for AppInitService<T, B>
where
T: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
{
type Response = ServiceResponse<B>;
type Error = T::Error;
type Future = T::Future;
2021-01-11 01:29:16 +00:00
actix_service::forward_ready!(service);
fn call(&self, req: Request) -> Self::Future {
let (head, payload) = req.into_parts();
let req = if let Some(mut req) = self.app_state.pool().pop() {
let inner = Rc::get_mut(&mut req.inner).unwrap();
inner.path.get_mut().update(&head.uri);
inner.path.reset();
inner.head = head;
req
} else {
HttpRequest::new(
Path::new(Url::new(head.uri.clone())),
head,
self.app_state.clone(),
2021-01-06 11:35:30 +00:00
self.app_data.clone(),
)
};
2021-01-11 01:29:16 +00:00
self.service.call(ServiceRequest::new(req, payload))
}
}
impl<T, B> Drop for AppInitService<T, B>
where
T: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
{
fn drop(&mut self) {
self.app_state.pool().clear();
}
}
pub struct AppRoutingFactory {
2020-10-10 00:26:05 +00:00
services: Rc<[(ResourceDef, HttpNewService, RefCell<Option<Guards>>)]>,
default: Rc<HttpNewService>,
}
impl ServiceFactory<ServiceRequest> for AppRoutingFactory {
type Response = ServiceResponse;
type Error = Error;
2021-01-06 18:11:20 +00:00
type Config = ();
type Service = AppRouting;
2021-01-06 18:11:20 +00:00
type InitError = ();
type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>;
2019-12-02 15:37:13 +00:00
fn new_service(&self, _: ()) -> Self::Future {
2021-01-06 18:11:20 +00:00
// construct all services factory future with it's resource def and guards.
2021-02-11 23:03:17 +00:00
let factory_fut = join_all(self.services.iter().map(|(path, factory, guards)| {
let path = path.clone();
let guards = guards.borrow_mut().take();
let factory_fut = factory.new_service(());
async move {
let service = factory_fut.await?;
Ok((path, guards, service))
}
}));
2021-01-06 18:11:20 +00:00
// construct default service factory future
let default_fut = self.default.new_service(());
2021-01-06 18:11:20 +00:00
Box::pin(async move {
let default = default_fut.await?;
2021-01-06 18:11:20 +00:00
// build router from the factory future result.
let router = factory_fut
.await
.into_iter()
.collect::<Result<Vec<_>, _>>()?
.drain(..)
2021-01-06 18:11:20 +00:00
.fold(Router::build(), |mut router, (path, guards, service)| {
router.rdef(path, service).2 = guards;
router
2021-01-06 18:11:20 +00:00
})
.finish();
Ok(AppRouting { router, default })
})
}
}
pub struct AppRouting {
router: Router<HttpService, Guards>,
2021-01-06 18:11:20 +00:00
default: HttpService,
}
impl Service<ServiceRequest> for AppRouting {
type Response = ServiceResponse;
type Error = Error;
2021-01-06 11:35:30 +00:00
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
2021-01-06 11:35:30 +00:00
actix_service::always_ready!();
fn call(&self, mut req: ServiceRequest) -> Self::Future {
let res = self.router.recognize_checked(&mut req, |req, guards| {
if let Some(ref guards) = guards {
for f in guards {
if !f.check(req.head()) {
return false;
}
}
}
true
});
if let Some((srv, _info)) = res {
srv.call(req)
} else {
2021-01-06 18:11:20 +00:00
self.default.call(req)
}
}
}
/// Wrapper service for routing
pub struct AppEntry {
factory: Rc<RefCell<Option<AppRoutingFactory>>>,
}
impl AppEntry {
pub fn new(factory: Rc<RefCell<Option<AppRoutingFactory>>>) -> Self {
AppEntry { factory }
}
}
impl ServiceFactory<ServiceRequest> for AppEntry {
type Response = ServiceResponse;
type Error = Error;
2021-01-06 11:35:30 +00:00
type Config = ();
type Service = AppRouting;
2021-01-06 11:35:30 +00:00
type InitError = ();
2021-01-06 18:11:20 +00:00
type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>;
2019-12-02 15:37:13 +00:00
fn new_service(&self, _: ()) -> Self::Future {
self.factory.borrow_mut().as_mut().unwrap().new_service(())
}
}
#[cfg(test)]
mod tests {
2019-11-26 05:25:50 +00:00
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
2021-01-06 18:11:20 +00:00
use actix_service::Service;
2019-11-26 05:25:50 +00:00
use crate::test::{init_service, TestRequest};
use crate::{web, App, HttpResponse};
struct DropData(Arc<AtomicBool>);
impl Drop for DropData {
fn drop(&mut self) {
self.0.store(true, Ordering::Relaxed);
}
}
// allow deprecated App::data
#[allow(deprecated)]
2019-11-26 05:25:50 +00:00
#[actix_rt::test]
async fn test_drop_data() {
let data = Arc::new(AtomicBool::new(false));
2019-11-26 05:25:50 +00:00
{
let app = init_service(
App::new()
.data(DropData(data.clone()))
.service(web::resource("/test").to(HttpResponse::Ok)),
2019-11-20 17:33:22 +00:00
)
.await;
2019-11-26 05:25:50 +00:00
let req = TestRequest::with_uri("/test").to_request();
2019-11-20 17:33:22 +00:00
let _ = app.call(req).await.unwrap();
2019-11-26 05:25:50 +00:00
}
assert!(data.load(Ordering::Relaxed));
}
}