1
0
mirror of https://github.com/fafhrd91/actix-web synced 2025-01-31 19:10:07 +01:00

More refactor of app_service (#1879)

This commit is contained in:
fakeshadow 2021-01-07 02:11:20 +08:00 committed by GitHub
parent 57da1d3c0f
commit 57a3722146
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,6 +1,4 @@
use std::cell::RefCell; use std::cell::RefCell;
use std::future::Future;
use std::pin::Pin;
use std::rc::Rc; use std::rc::Rc;
use std::task::{Context, Poll}; use std::task::{Context, Poll};
@ -216,111 +214,52 @@ pub struct AppRoutingFactory {
} }
impl ServiceFactory<ServiceRequest> for AppRoutingFactory { impl ServiceFactory<ServiceRequest> for AppRoutingFactory {
type Config = ();
type Response = ServiceResponse; type Response = ServiceResponse;
type Error = Error; type Error = Error;
type InitError = (); type Config = ();
type Service = AppRouting; type Service = AppRouting;
type Future = AppRoutingFactoryResponse; type InitError = ();
type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>;
fn new_service(&self, _: ()) -> Self::Future { fn new_service(&self, _: ()) -> Self::Future {
AppRoutingFactoryResponse { // construct all services factory future with it's resource def and guards.
fut: self let factory_fut =
.services join_all(self.services.iter().map(|(path, factory, guards)| {
.iter() let path = path.clone();
.map(|(path, service, guards)| { let guards = guards.borrow_mut().take();
CreateAppRoutingItem::Future( let factory_fut = factory.new_service(());
Some(path.clone()), async move {
guards.borrow_mut().take(), let service = factory_fut.await?;
Box::pin(service.new_service(())), Ok((path, guards, service))
) }
}) }));
.collect(),
default: None,
default_fut: Some(self.default.new_service(())),
}
}
}
type HttpServiceFut = LocalBoxFuture<'static, Result<HttpService, ()>>; // construct default service factory future
let default_fut = self.default.new_service(());
/// Create app service Box::pin(async move {
#[doc(hidden)] let default = default_fut.await?;
pub struct AppRoutingFactoryResponse {
fut: Vec<CreateAppRoutingItem>,
default: Option<HttpService>,
default_fut: Option<HttpServiceFut>,
}
enum CreateAppRoutingItem { // build router from the factory future result.
Future(Option<ResourceDef>, Option<Guards>, HttpServiceFut), let router = factory_fut
Service(ResourceDef, Option<Guards>, HttpService), .await
} .into_iter()
.collect::<Result<Vec<_>, _>>()?
impl Future for AppRoutingFactoryResponse {
type Output = Result<AppRouting, ()>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut done = true;
if let Some(ref mut fut) = self.default_fut {
match Pin::new(fut).poll(cx)? {
Poll::Ready(default) => self.default = Some(default),
Poll::Pending => done = false,
}
}
// poll http services
for item in &mut self.fut {
let res = match item {
CreateAppRoutingItem::Future(
ref mut path,
ref mut guards,
ref mut fut,
) => match Pin::new(fut).poll(cx) {
Poll::Ready(Ok(service)) => {
Some((path.take().unwrap(), guards.take(), service))
}
Poll::Ready(Err(_)) => return Poll::Ready(Err(())),
Poll::Pending => {
done = false;
None
}
},
CreateAppRoutingItem::Service(_, _, _) => continue,
};
if let Some((path, guards, service)) = res {
*item = CreateAppRoutingItem::Service(path, guards, service);
}
}
if done {
let router = self
.fut
.drain(..) .drain(..)
.fold(Router::build(), |mut router, item| { .fold(Router::build(), |mut router, (path, guards, service)| {
match item { router.rdef(path, service).2 = guards;
CreateAppRoutingItem::Service(path, guards, service) => {
router.rdef(path, service).2 = guards;
}
CreateAppRoutingItem::Future(_, _, _) => unreachable!(),
}
router router
}); })
Poll::Ready(Ok(AppRouting { .finish();
router: router.finish(),
default: self.default.take(), Ok(AppRouting { router, default })
})) })
} else {
Poll::Pending
}
} }
} }
pub struct AppRouting { pub struct AppRouting {
router: Router<HttpService, Guards>, router: Router<HttpService, Guards>,
default: Option<HttpService>, default: HttpService,
} }
impl Service<ServiceRequest> for AppRouting { impl Service<ServiceRequest> for AppRouting {
@ -344,13 +283,8 @@ impl Service<ServiceRequest> for AppRouting {
if let Some((srv, _info)) = res { if let Some((srv, _info)) = res {
srv.call(req) srv.call(req)
} else if let Some(ref mut default) = self.default {
default.call(req)
} else { } else {
let req = req.into_parts().0; self.default.call(req)
Box::pin(async {
Ok(ServiceResponse::new(req, Response::NotFound().finish()))
})
} }
} }
} }
@ -372,7 +306,7 @@ impl ServiceFactory<ServiceRequest> for AppEntry {
type Config = (); type Config = ();
type Service = AppRouting; type Service = AppRouting;
type InitError = (); type InitError = ();
type Future = AppRoutingFactoryResponse; type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>;
fn new_service(&self, _: ()) -> Self::Future { fn new_service(&self, _: ()) -> Self::Future {
self.factory.borrow_mut().as_mut().unwrap().new_service(()) self.factory.borrow_mut().as_mut().unwrap().new_service(())
@ -384,9 +318,10 @@ mod tests {
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc; use std::sync::Arc;
use actix_service::Service;
use crate::test::{init_service, TestRequest}; use crate::test::{init_service, TestRequest};
use crate::{web, App, HttpResponse}; use crate::{web, App, HttpResponse};
use actix_service::Service;
struct DropData(Arc<AtomicBool>); struct DropData(Arc<AtomicBool>);