1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-12-18 01:43:58 +01:00

refactor boxed route (#2033)

This commit is contained in:
fakeshadow 2021-02-27 13:00:36 -08:00 committed by GitHub
parent d242f57758
commit ebda60fd6b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,13 +1,13 @@
#![allow(clippy::rc_buffer)] // inner value is mutated before being shared (`Rc::get_mut`) #![allow(clippy::rc_buffer)] // inner value is mutated before being shared (`Rc::get_mut`)
use std::future::Future; use std::{future::Future, rc::Rc};
use std::pin::Pin;
use std::rc::Rc;
use std::task::{Context, Poll};
use actix_http::{http::Method, Error}; use actix_http::{http::Method, Error};
use actix_service::{Service, ServiceFactory}; use actix_service::{
use futures_util::future::{ready, FutureExt, LocalBoxFuture}; boxed::{self, BoxService, BoxServiceFactory},
Service, ServiceFactory,
};
use futures_core::future::LocalBoxFuture;
use crate::extract::FromRequest; use crate::extract::FromRequest;
use crate::guard::{self, Guard}; use crate::guard::{self, Guard};
@ -16,33 +16,12 @@ use crate::responder::Responder;
use crate::service::{ServiceRequest, ServiceResponse}; use crate::service::{ServiceRequest, ServiceResponse};
use crate::HttpResponse; use crate::HttpResponse;
type BoxedRouteService = Box<
dyn Service<
ServiceRequest,
Response = ServiceResponse,
Error = Error,
Future = LocalBoxFuture<'static, Result<ServiceResponse, Error>>,
>,
>;
type BoxedRouteNewService = Box<
dyn ServiceFactory<
ServiceRequest,
Config = (),
Response = ServiceResponse,
Error = Error,
InitError = (),
Service = BoxedRouteService,
Future = LocalBoxFuture<'static, Result<BoxedRouteService, ()>>,
>,
>;
/// Resource route definition /// Resource route definition
/// ///
/// Route uses builder-like pattern for configuration. /// Route uses builder-like pattern for configuration.
/// If handler is not explicitly set, default *404 Not Found* handler is used. /// If handler is not explicitly set, default *404 Not Found* handler is used.
pub struct Route { pub struct Route {
service: BoxedRouteNewService, service: BoxServiceFactory<(), ServiceRequest, ServiceResponse, Error, ()>,
guards: Rc<Vec<Box<dyn Guard>>>, guards: Rc<Vec<Box<dyn Guard>>>,
} }
@ -51,9 +30,7 @@ impl Route {
#[allow(clippy::new_without_default)] #[allow(clippy::new_without_default)]
pub fn new() -> Route { pub fn new() -> Route {
Route { Route {
service: Box::new(RouteNewService::new(HandlerService::new(|| { service: boxed::factory(HandlerService::new(HttpResponse::NotFound)),
ready(HttpResponse::NotFound())
}))),
guards: Rc::new(Vec::new()), guards: Rc::new(Vec::new()),
} }
} }
@ -64,44 +41,26 @@ impl Route {
} }
impl ServiceFactory<ServiceRequest> for Route { impl ServiceFactory<ServiceRequest> for Route {
type Config = ();
type Response = ServiceResponse; type Response = ServiceResponse;
type Error = Error; type Error = Error;
type InitError = (); type Config = ();
type Service = RouteService; type Service = RouteService;
type Future = CreateRouteService; type InitError = ();
type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>;
fn new_service(&self, _: ()) -> Self::Future { fn new_service(&self, _: ()) -> Self::Future {
CreateRouteService { let fut = self.service.new_service(());
fut: self.service.new_service(()), let guards = self.guards.clone();
guards: self.guards.clone(),
}
}
}
pub struct CreateRouteService { Box::pin(async move {
fut: LocalBoxFuture<'static, Result<BoxedRouteService, ()>>, let service = fut.await?;
guards: Rc<Vec<Box<dyn Guard>>>, Ok(RouteService { service, guards })
} })
impl Future for CreateRouteService {
type Output = Result<RouteService, ()>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.get_mut();
match this.fut.as_mut().poll(cx)? {
Poll::Ready(service) => Poll::Ready(Ok(RouteService {
service,
guards: this.guards.clone(),
})),
Poll::Pending => Poll::Pending,
}
} }
} }
pub struct RouteService { pub struct RouteService {
service: BoxedRouteService, service: BoxService<ServiceRequest, ServiceResponse, Error>,
guards: Rc<Vec<Box<dyn Guard>>>, guards: Rc<Vec<Box<dyn Guard>>>,
} }
@ -121,9 +80,7 @@ impl Service<ServiceRequest> for RouteService {
type Error = Error; type Error = Error;
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { actix_service::forward_ready!(service);
self.service.poll_ready(cx)
}
fn call(&self, req: ServiceRequest) -> Self::Future { fn call(&self, req: ServiceRequest) -> Self::Future {
self.service.call(req) self.service.call(req)
@ -224,80 +181,11 @@ impl Route {
R: Future + 'static, R: Future + 'static,
R::Output: Responder + 'static, R::Output: Responder + 'static,
{ {
self.service = Box::new(RouteNewService::new(HandlerService::new(handler))); self.service = boxed::factory(HandlerService::new(handler));
self self
} }
} }
struct RouteNewService<T>
where
T: ServiceFactory<ServiceRequest, Error = Error>,
{
service: T,
}
impl<T> RouteNewService<T>
where
T: ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse, Error = Error>,
T::Future: 'static,
T::Service: 'static,
<T::Service as Service<ServiceRequest>>::Future: 'static,
{
pub fn new(service: T) -> Self {
RouteNewService { service }
}
}
impl<T> ServiceFactory<ServiceRequest> for RouteNewService<T>
where
T: ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse, Error = Error>,
T::Future: 'static,
T::Service: 'static,
<T::Service as Service<ServiceRequest>>::Future: 'static,
{
type Response = ServiceResponse;
type Error = Error;
type Config = ();
type Service = BoxedRouteService;
type InitError = ();
type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>;
fn new_service(&self, _: ()) -> Self::Future {
self.service
.new_service(())
.map(|result| match result {
Ok(service) => {
let service = Box::new(RouteServiceWrapper { service }) as _;
Ok(service)
}
Err(_) => Err(()),
})
.boxed_local()
}
}
struct RouteServiceWrapper<T: Service<ServiceRequest>> {
service: T,
}
impl<T> Service<ServiceRequest> for RouteServiceWrapper<T>
where
T::Future: 'static,
T: Service<ServiceRequest, Response = ServiceResponse, Error = Error>,
{
type Response = ServiceResponse;
type Error = Error;
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.service.poll_ready(cx)
}
fn call(&self, req: ServiceRequest) -> Self::Future {
Box::pin(self.service.call(req))
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use std::time::Duration; use std::time::Duration;