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/data.rs

304 lines
8.4 KiB
Rust
Raw Normal View History

2019-03-02 06:51:32 +00:00
use std::ops::Deref;
2019-03-06 18:03:18 +00:00
use std::sync::Arc;
2019-03-02 06:51:32 +00:00
use actix_http::error::{Error, ErrorInternalServerError};
use actix_http::Extensions;
use futures::{Async, Future, IntoFuture, Poll};
2019-04-07 21:43:07 +00:00
use crate::dev::Payload;
use crate::extract::FromRequest;
2019-04-07 21:43:07 +00:00
use crate::request::HttpRequest;
2019-03-02 06:51:32 +00:00
2019-03-17 03:17:27 +00:00
/// Application data factory
pub(crate) trait DataFactory {
fn construct(&self) -> Box<DataFactoryResult>;
2019-03-02 06:51:32 +00:00
}
2019-03-17 03:17:27 +00:00
pub(crate) trait DataFactoryResult {
2019-03-02 06:51:32 +00:00
fn poll_result(&mut self, extensions: &mut Extensions) -> Poll<(), ()>;
}
2019-03-17 04:09:11 +00:00
/// Application data.
///
/// Application data is an arbitrary data attached to the app.
/// Application data is available to all routes and could be added
/// during application configuration process
/// with `App::data()` method.
///
/// Application data could be accessed by using `Data<T>`
2019-03-17 04:09:11 +00:00
/// extractor where `T` is data type.
///
/// **Note**: http server accepts an application factory rather than
/// an application instance. Http server constructs an application
/// instance for each thread, thus application data must be constructed
/// multiple times. If you want to share data between different
/// threads, a shared object should be used, e.g. `Arc`. Application
/// data does not need to be `Send` or `Sync`.
///
2019-03-17 04:13:16 +00:00
/// If route data is not set for a handler, using `Data<T>` extractor would
/// cause *Internal Server Error* response.
///
2019-03-17 04:09:11 +00:00
/// ```rust
/// use std::cell::Cell;
/// use actix_web::{web, App};
///
/// struct MyData {
/// counter: Cell<usize>,
/// }
///
/// /// Use `Data<T>` extractor to access data in handler.
/// fn index(data: web::Data<MyData>) {
/// data.counter.set(data.counter.get() + 1);
/// }
///
/// fn main() {
/// let app = App::new()
/// // Store `MyData` in application storage.
/// .data(MyData{ counter: Cell::new(0) })
/// .service(
/// web::resource("/index.html").route(
/// web::get().to(index)));
/// }
/// ```
2019-03-17 03:17:27 +00:00
pub struct Data<T>(Arc<T>);
2019-03-02 06:51:32 +00:00
2019-03-17 03:17:27 +00:00
impl<T> Data<T> {
pub(crate) fn new(state: T) -> Data<T> {
Data(Arc::new(state))
2019-03-02 06:51:32 +00:00
}
2019-03-17 04:09:11 +00:00
/// Get referecnce to inner app data.
2019-03-03 22:45:56 +00:00
pub fn get_ref(&self) -> &T {
2019-03-02 06:51:32 +00:00
self.0.as_ref()
}
}
2019-03-17 03:17:27 +00:00
impl<T> Deref for Data<T> {
2019-03-03 22:45:56 +00:00
type Target = T;
2019-03-02 06:51:32 +00:00
2019-03-03 22:45:56 +00:00
fn deref(&self) -> &T {
2019-03-02 06:51:32 +00:00
self.0.as_ref()
}
}
2019-03-17 03:17:27 +00:00
impl<T> Clone for Data<T> {
fn clone(&self) -> Data<T> {
Data(self.0.clone())
2019-03-02 06:51:32 +00:00
}
}
2019-03-17 03:17:27 +00:00
impl<T: 'static, P> FromRequest<P> for Data<T> {
2019-03-02 06:51:32 +00:00
type Error = Error;
2019-03-03 22:45:56 +00:00
type Future = Result<Self, Error>;
2019-03-02 06:51:32 +00:00
#[inline]
2019-04-07 21:43:07 +00:00
fn from_request(req: &HttpRequest, _: &mut Payload<P>) -> Self::Future {
if let Some(st) = req.app_config().extensions().get::<Data<T>>() {
2019-03-03 22:45:56 +00:00
Ok(st.clone())
2019-03-02 06:51:32 +00:00
} else {
log::debug!("Failed to construct App-level Data extractor. \
Request path: {:?}", req.path());
2019-03-03 22:45:56 +00:00
Err(ErrorInternalServerError(
2019-03-17 04:09:11 +00:00
"App data is not configured, to configure use App::data()",
2019-03-02 06:51:32 +00:00
))
}
}
}
2019-03-17 03:17:27 +00:00
impl<T: 'static> DataFactory for Data<T> {
fn construct(&self) -> Box<DataFactoryResult> {
Box::new(DataFut { st: self.clone() })
2019-03-02 06:51:32 +00:00
}
}
2019-03-17 03:17:27 +00:00
struct DataFut<T> {
st: Data<T>,
2019-03-02 06:51:32 +00:00
}
2019-03-17 03:17:27 +00:00
impl<T: 'static> DataFactoryResult for DataFut<T> {
2019-03-02 06:51:32 +00:00
fn poll_result(&mut self, extensions: &mut Extensions) -> Poll<(), ()> {
extensions.insert(self.st.clone());
Ok(Async::Ready(()))
}
}
2019-03-17 03:17:27 +00:00
impl<F, Out> DataFactory for F
2019-03-02 06:51:32 +00:00
where
F: Fn() -> Out + 'static,
Out: IntoFuture + 'static,
Out::Error: std::fmt::Debug,
{
2019-03-17 03:17:27 +00:00
fn construct(&self) -> Box<DataFactoryResult> {
Box::new(DataFactoryFut {
2019-03-02 06:51:32 +00:00
fut: (*self)().into_future(),
})
}
}
2019-03-17 03:17:27 +00:00
struct DataFactoryFut<T, F>
2019-03-02 06:51:32 +00:00
where
2019-03-03 22:45:56 +00:00
F: Future<Item = T>,
2019-03-02 06:51:32 +00:00
F::Error: std::fmt::Debug,
{
fut: F,
}
2019-03-17 03:17:27 +00:00
impl<T: 'static, F> DataFactoryResult for DataFactoryFut<T, F>
2019-03-02 06:51:32 +00:00
where
2019-03-03 22:45:56 +00:00
F: Future<Item = T>,
2019-03-02 06:51:32 +00:00
F::Error: std::fmt::Debug,
{
fn poll_result(&mut self, extensions: &mut Extensions) -> Poll<(), ()> {
match self.fut.poll() {
Ok(Async::Ready(s)) => {
2019-03-17 03:17:27 +00:00
extensions.insert(Data::new(s));
2019-03-02 06:51:32 +00:00
Ok(Async::Ready(()))
}
Ok(Async::NotReady) => Ok(Async::NotReady),
Err(e) => {
log::error!("Can not construct application state: {:?}", e);
Err(())
}
}
}
}
2019-03-17 04:09:11 +00:00
/// Route data.
///
/// Route data is an arbitrary data attached to specific route.
/// Route data could be added to route during route configuration process
/// with `Route::data()` method. Route data is also used as an extractor
/// configuration storage. Route data could be accessed in handler
/// via `RouteData<T>` extractor.
///
2019-03-17 04:13:16 +00:00
/// If route data is not set for a handler, using `RouteData` extractor
/// would cause *Internal Server Error* response.
///
2019-03-17 04:09:11 +00:00
/// ```rust
/// # use std::cell::Cell;
/// use actix_web::{web, App};
///
/// struct MyData {
/// counter: Cell<usize>,
/// }
///
/// /// Use `RouteData<T>` extractor to access data in handler.
/// fn index(data: web::RouteData<MyData>) {
/// data.counter.set(data.counter.get() + 1);
/// }
///
/// fn main() {
/// let app = App::new().service(
/// web::resource("/index.html").route(
/// web::get()
/// // Store `MyData` in route storage
/// .data(MyData{ counter: Cell::new(0) })
/// // Route data could be used as extractor configuration storage,
/// // limit size of the payload
/// .data(web::PayloadConfig::new(4096))
/// // register handler
/// .to(index)
/// ));
/// }
/// ```
pub struct RouteData<T>(Arc<T>);
impl<T> RouteData<T> {
pub(crate) fn new(state: T) -> RouteData<T> {
RouteData(Arc::new(state))
}
/// Get referecnce to inner data object.
pub fn get_ref(&self) -> &T {
self.0.as_ref()
}
}
impl<T> Deref for RouteData<T> {
type Target = T;
fn deref(&self) -> &T {
self.0.as_ref()
}
}
impl<T> Clone for RouteData<T> {
fn clone(&self) -> RouteData<T> {
RouteData(self.0.clone())
}
}
impl<T: 'static, P> FromRequest<P> for RouteData<T> {
type Error = Error;
type Future = Result<Self, Error>;
#[inline]
2019-04-07 21:43:07 +00:00
fn from_request(req: &HttpRequest, _: &mut Payload<P>) -> Self::Future {
2019-03-17 04:09:11 +00:00
if let Some(st) = req.route_data::<T>() {
Ok(st.clone())
} else {
log::debug!("Failed to construct Route-level Data extractor");
2019-03-17 04:09:11 +00:00
Err(ErrorInternalServerError(
"Route data is not configured, to configure use Route::data()",
))
}
}
}
#[cfg(test)]
mod tests {
use actix_service::Service;
use crate::http::StatusCode;
use crate::test::{block_on, init_service, TestRequest};
use crate::{web, App, HttpResponse};
#[test]
fn test_data_extractor() {
let mut srv =
init_service(App::new().data(10usize).service(
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
));
let req = TestRequest::default().to_request();
let resp = block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let mut srv =
init_service(App::new().data(10u32).service(
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
));
let req = TestRequest::default().to_request();
let resp = block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
#[test]
fn test_route_data_extractor() {
let mut srv = init_service(App::new().service(web::resource("/").route(
web::get().data(10usize).to(|data: web::RouteData<usize>| {
let _ = data.clone();
HttpResponse::Ok()
}),
)));
let req = TestRequest::default().to_request();
let resp = block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::OK);
// different type
let mut srv = init_service(
App::new().service(
web::resource("/").route(
web::get()
.data(10u32)
.to(|_: web::RouteData<usize>| HttpResponse::Ok()),
),
),
);
let req = TestRequest::default().to_request();
let resp = block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
}