2020-10-20 18:35:34 +02:00
|
|
|
use std::any::type_name;
|
2019-03-02 07:51:32 +01:00
|
|
|
use std::ops::Deref;
|
2019-03-06 19:03:18 +01:00
|
|
|
use std::sync::Arc;
|
2019-03-02 07:51:32 +01:00
|
|
|
|
|
|
|
use actix_http::error::{Error, ErrorInternalServerError};
|
|
|
|
use actix_http::Extensions;
|
2020-05-18 04:47:20 +02:00
|
|
|
use futures_util::future::{err, ok, LocalBoxFuture, Ready};
|
2019-03-02 07:51:32 +01:00
|
|
|
|
2019-04-07 23:43:07 +02:00
|
|
|
use crate::dev::Payload;
|
2019-03-03 22:53:31 +01:00
|
|
|
use crate::extract::FromRequest;
|
2019-04-07 23:43:07 +02:00
|
|
|
use crate::request::HttpRequest;
|
2019-03-02 07:51:32 +01:00
|
|
|
|
2019-03-17 04:17:27 +01:00
|
|
|
/// Application data factory
|
|
|
|
pub(crate) trait DataFactory {
|
2019-05-05 04:43:49 +02:00
|
|
|
fn create(&self, extensions: &mut Extensions) -> bool;
|
2019-03-02 07:51:32 +01:00
|
|
|
}
|
|
|
|
|
2020-04-29 19:20:47 +02:00
|
|
|
pub(crate) type FnDataFactory =
|
|
|
|
Box<dyn Fn() -> LocalBoxFuture<'static, Result<Box<dyn DataFactory>, ()>>>;
|
|
|
|
|
2019-03-17 05:09:11 +01: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.
|
|
|
|
///
|
2019-04-10 21:43:31 +02:00
|
|
|
/// Application data could be accessed by using `Data<T>`
|
2019-03-17 05:09:11 +01: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
|
2019-04-11 05:47:28 +02:00
|
|
|
/// threads, a shareable object should be used, e.g. `Send + Sync`. Application
|
2019-04-29 18:26:12 +02:00
|
|
|
/// data does not need to be `Send` or `Sync`. Internally `Data` type
|
|
|
|
/// uses `Arc`. if your data implements `Send` + `Sync` traits you can
|
|
|
|
/// use `web::Data::new()` and avoid double `Arc`.
|
2019-03-17 05:09:11 +01:00
|
|
|
///
|
2019-03-17 05:13:16 +01:00
|
|
|
/// If route data is not set for a handler, using `Data<T>` extractor would
|
|
|
|
/// cause *Internal Server Error* response.
|
|
|
|
///
|
2019-03-17 05:09:11 +01:00
|
|
|
/// ```rust
|
2019-04-29 18:26:12 +02:00
|
|
|
/// use std::sync::Mutex;
|
2019-11-20 05:05:16 +01:00
|
|
|
/// use actix_web::{web, App, HttpResponse, Responder};
|
2019-03-17 05:09:11 +01:00
|
|
|
///
|
|
|
|
/// struct MyData {
|
2019-04-29 18:26:12 +02:00
|
|
|
/// counter: usize,
|
2019-03-17 05:09:11 +01:00
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// /// Use `Data<T>` extractor to access data in handler.
|
2019-11-20 05:05:16 +01:00
|
|
|
/// async fn index(data: web::Data<Mutex<MyData>>) -> impl Responder {
|
2019-04-29 18:26:12 +02:00
|
|
|
/// let mut data = data.lock().unwrap();
|
|
|
|
/// data.counter += 1;
|
2019-11-20 05:05:16 +01:00
|
|
|
/// HttpResponse::Ok()
|
2019-03-17 05:09:11 +01:00
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// fn main() {
|
2019-04-29 18:26:12 +02:00
|
|
|
/// let data = web::Data::new(Mutex::new(MyData{ counter: 0 }));
|
|
|
|
///
|
2019-03-17 05:09:11 +01:00
|
|
|
/// let app = App::new()
|
|
|
|
/// // Store `MyData` in application storage.
|
2019-12-20 12:13:09 +01:00
|
|
|
/// .app_data(data.clone())
|
2019-03-17 05:09:11 +01:00
|
|
|
/// .service(
|
|
|
|
/// web::resource("/index.html").route(
|
|
|
|
/// web::get().to(index)));
|
|
|
|
/// }
|
|
|
|
/// ```
|
2019-04-15 04:52:12 +02:00
|
|
|
#[derive(Debug)]
|
2020-09-29 23:44:12 +02:00
|
|
|
pub struct Data<T: ?Sized>(Arc<T>);
|
2019-03-02 07:51:32 +01:00
|
|
|
|
2019-03-17 04:17:27 +01:00
|
|
|
impl<T> Data<T> {
|
2019-04-29 18:26:12 +02:00
|
|
|
/// Create new `Data` instance.
|
|
|
|
///
|
|
|
|
/// Internally `Data` type uses `Arc`. if your data implements
|
|
|
|
/// `Send` + `Sync` traits you can use `web::Data::new()` and
|
|
|
|
/// avoid double `Arc`.
|
|
|
|
pub fn new(state: T) -> Data<T> {
|
2019-03-17 04:17:27 +01:00
|
|
|
Data(Arc::new(state))
|
2019-03-02 07:51:32 +01:00
|
|
|
}
|
|
|
|
|
2019-06-18 03:27:23 +02:00
|
|
|
/// Get reference to inner app data.
|
2019-03-03 23:45:56 +01:00
|
|
|
pub fn get_ref(&self) -> &T {
|
2019-03-02 07:51:32 +01:00
|
|
|
self.0.as_ref()
|
|
|
|
}
|
2019-08-23 17:02:03 +02:00
|
|
|
|
|
|
|
/// Convert to the internal Arc<T>
|
|
|
|
pub fn into_inner(self) -> Arc<T> {
|
|
|
|
self.0
|
|
|
|
}
|
2019-03-02 07:51:32 +01:00
|
|
|
}
|
|
|
|
|
2020-09-29 23:44:12 +02:00
|
|
|
impl<T: ?Sized> Deref for Data<T> {
|
2019-12-20 12:45:35 +01:00
|
|
|
type Target = Arc<T>;
|
2019-03-02 07:51:32 +01:00
|
|
|
|
2019-12-20 12:45:35 +01:00
|
|
|
fn deref(&self) -> &Arc<T> {
|
|
|
|
&self.0
|
2019-03-02 07:51:32 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-29 23:44:12 +02:00
|
|
|
impl<T: ?Sized> Clone for Data<T> {
|
2019-03-17 04:17:27 +01:00
|
|
|
fn clone(&self) -> Data<T> {
|
|
|
|
Data(self.0.clone())
|
2019-03-02 07:51:32 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-29 23:44:12 +02:00
|
|
|
impl<T: ?Sized> From<Arc<T>> for Data<T> {
|
2020-05-16 01:27:03 +02:00
|
|
|
fn from(arc: Arc<T>) -> Self {
|
|
|
|
Data(arc)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-29 23:44:12 +02:00
|
|
|
impl<T: ?Sized + 'static> FromRequest for Data<T> {
|
2019-04-14 01:35:25 +02:00
|
|
|
type Config = ();
|
2019-03-02 07:51:32 +01:00
|
|
|
type Error = Error;
|
2019-11-20 18:33:22 +01:00
|
|
|
type Future = Ready<Result<Self, Error>>;
|
2019-03-02 07:51:32 +01:00
|
|
|
|
|
|
|
#[inline]
|
2019-04-13 23:50:54 +02:00
|
|
|
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
|
2019-12-20 12:13:09 +01:00
|
|
|
if let Some(st) = req.app_data::<Data<T>>() {
|
|
|
|
ok(st.clone())
|
2019-03-02 07:51:32 +01:00
|
|
|
} else {
|
2019-04-11 00:05:03 +02:00
|
|
|
log::debug!(
|
|
|
|
"Failed to construct App-level Data extractor. \
|
2020-10-20 18:35:34 +02:00
|
|
|
Request path: {:?} (type: {})",
|
|
|
|
req.path(),
|
|
|
|
type_name::<T>(),
|
2019-04-11 00:05:03 +02:00
|
|
|
);
|
2019-11-20 18:33:22 +01:00
|
|
|
err(ErrorInternalServerError(
|
2019-03-17 05:09:11 +01:00
|
|
|
"App data is not configured, to configure use App::data()",
|
2019-03-02 07:51:32 +01:00
|
|
|
))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-29 23:44:12 +02:00
|
|
|
impl<T: ?Sized + 'static> DataFactory for Data<T> {
|
2019-05-05 04:43:49 +02:00
|
|
|
fn create(&self, extensions: &mut Extensions) -> bool {
|
|
|
|
if !extensions.contains::<Data<T>>() {
|
2019-07-17 08:58:42 +02:00
|
|
|
extensions.insert(Data(self.0.clone()));
|
2019-05-05 04:43:49 +02:00
|
|
|
true
|
2019-03-17 05:09:11 +01:00
|
|
|
} else {
|
2019-05-05 04:43:49 +02:00
|
|
|
false
|
2019-03-17 05:09:11 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use actix_service::Service;
|
2019-12-25 09:10:28 +01:00
|
|
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
2019-03-17 05:09:11 +01:00
|
|
|
|
2019-06-05 04:43:39 +02:00
|
|
|
use super::*;
|
2019-03-17 05:09:11 +01:00
|
|
|
use crate::http::StatusCode;
|
2019-12-25 09:10:28 +01:00
|
|
|
use crate::test::{self, init_service, TestRequest};
|
2019-03-17 05:09:11 +01:00
|
|
|
use crate::{web, App, HttpResponse};
|
|
|
|
|
2019-11-26 06:25:50 +01:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_data_extractor() {
|
2019-12-20 12:45:35 +01:00
|
|
|
let mut srv = init_service(App::new().data("TEST".to_string()).service(
|
|
|
|
web::resource("/").to(|data: web::Data<String>| {
|
|
|
|
assert_eq!(data.to_lowercase(), "test");
|
|
|
|
HttpResponse::Ok()
|
|
|
|
}),
|
|
|
|
))
|
|
|
|
.await;
|
2019-03-17 05:09:11 +01:00
|
|
|
|
2019-11-26 06:25:50 +01:00
|
|
|
let req = TestRequest::default().to_request();
|
|
|
|
let resp = srv.call(req).await.unwrap();
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
2019-03-17 05:09:11 +01:00
|
|
|
|
2019-11-26 06:25:50 +01:00
|
|
|
let mut srv =
|
|
|
|
init_service(App::new().data(10u32).service(
|
2019-03-17 05:09:11 +01:00
|
|
|
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
|
2019-11-20 18:33:22 +01:00
|
|
|
))
|
|
|
|
.await;
|
2019-11-26 06:25:50 +01:00
|
|
|
let req = TestRequest::default().to_request();
|
|
|
|
let resp = srv.call(req).await.unwrap();
|
|
|
|
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
2019-03-17 05:09:11 +01:00
|
|
|
}
|
|
|
|
|
2019-11-26 06:25:50 +01:00
|
|
|
#[actix_rt::test]
|
2019-12-20 12:13:09 +01:00
|
|
|
async fn test_app_data_extractor() {
|
2019-11-26 06:25:50 +01:00
|
|
|
let mut srv =
|
2019-12-20 12:13:09 +01:00
|
|
|
init_service(App::new().app_data(Data::new(10usize)).service(
|
2019-11-26 06:25:50 +01:00
|
|
|
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
|
2019-11-20 18:33:22 +01:00
|
|
|
))
|
|
|
|
.await;
|
|
|
|
|
2019-11-26 06:25:50 +01:00
|
|
|
let req = TestRequest::default().to_request();
|
|
|
|
let resp = srv.call(req).await.unwrap();
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
|
|
|
|
let mut srv =
|
2019-12-20 12:13:09 +01:00
|
|
|
init_service(App::new().app_data(Data::new(10u32)).service(
|
2019-11-26 06:25:50 +01:00
|
|
|
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
|
|
|
|
))
|
2019-11-20 18:33:22 +01:00
|
|
|
.await;
|
2019-11-26 06:25:50 +01:00
|
|
|
let req = TestRequest::default().to_request();
|
|
|
|
let resp = srv.call(req).await.unwrap();
|
|
|
|
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
2019-03-17 05:09:11 +01:00
|
|
|
}
|
2019-05-05 04:43:49 +02:00
|
|
|
|
2019-11-26 06:25:50 +01:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_route_data_extractor() {
|
2020-07-22 01:28:33 +02:00
|
|
|
let mut srv = init_service(
|
|
|
|
App::new().service(
|
|
|
|
web::resource("/")
|
|
|
|
.data(10usize)
|
|
|
|
.route(web::get().to(|_data: web::Data<usize>| HttpResponse::Ok())),
|
|
|
|
),
|
|
|
|
)
|
|
|
|
.await;
|
2019-11-20 18:33:22 +01:00
|
|
|
|
2019-11-26 06:25:50 +01:00
|
|
|
let req = TestRequest::default().to_request();
|
|
|
|
let resp = srv.call(req).await.unwrap();
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
|
|
|
|
// different type
|
|
|
|
let mut srv = init_service(
|
|
|
|
App::new().service(
|
|
|
|
web::resource("/")
|
|
|
|
.data(10u32)
|
|
|
|
.route(web::get().to(|_: web::Data<usize>| HttpResponse::Ok())),
|
|
|
|
),
|
|
|
|
)
|
|
|
|
.await;
|
|
|
|
let req = TestRequest::default().to_request();
|
|
|
|
let resp = srv.call(req).await.unwrap();
|
|
|
|
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_override_data() {
|
|
|
|
let mut srv = init_service(App::new().data(1usize).service(
|
|
|
|
web::resource("/").data(10usize).route(web::get().to(
|
|
|
|
|data: web::Data<usize>| {
|
2019-12-20 12:45:35 +01:00
|
|
|
assert_eq!(**data, 10);
|
2019-11-26 06:25:50 +01:00
|
|
|
HttpResponse::Ok()
|
|
|
|
},
|
|
|
|
)),
|
|
|
|
))
|
|
|
|
.await;
|
|
|
|
|
|
|
|
let req = TestRequest::default().to_request();
|
|
|
|
let resp = srv.call(req).await.unwrap();
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
2019-05-05 04:43:49 +02:00
|
|
|
}
|
2019-12-25 09:10:28 +01:00
|
|
|
|
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_data_drop() {
|
|
|
|
struct TestData(Arc<AtomicUsize>);
|
|
|
|
|
|
|
|
impl TestData {
|
|
|
|
fn new(inner: Arc<AtomicUsize>) -> Self {
|
|
|
|
let _ = inner.fetch_add(1, Ordering::SeqCst);
|
|
|
|
Self(inner)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Clone for TestData {
|
|
|
|
fn clone(&self) -> Self {
|
|
|
|
let inner = self.0.clone();
|
|
|
|
let _ = inner.fetch_add(1, Ordering::SeqCst);
|
|
|
|
Self(inner)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Drop for TestData {
|
|
|
|
fn drop(&mut self) {
|
|
|
|
let _ = self.0.fetch_sub(1, Ordering::SeqCst);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let num = Arc::new(AtomicUsize::new(0));
|
|
|
|
let data = TestData::new(num.clone());
|
|
|
|
assert_eq!(num.load(Ordering::SeqCst), 1);
|
|
|
|
|
|
|
|
let srv = test::start(move || {
|
|
|
|
let data = data.clone();
|
|
|
|
|
|
|
|
App::new()
|
|
|
|
.data(data)
|
|
|
|
.service(web::resource("/").to(|_data: Data<TestData>| async { "ok" }))
|
|
|
|
});
|
|
|
|
|
|
|
|
assert!(srv.get("/").send().await.unwrap().status().is_success());
|
|
|
|
srv.stop().await;
|
|
|
|
|
|
|
|
assert_eq!(num.load(Ordering::SeqCst), 0);
|
|
|
|
}
|
2020-05-16 01:27:03 +02:00
|
|
|
|
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_data_from_arc() {
|
|
|
|
let data_new = Data::new(String::from("test-123"));
|
|
|
|
let data_from_arc = Data::from(Arc::new(String::from("test-123")));
|
|
|
|
assert_eq!(data_new.0, data_from_arc.0)
|
|
|
|
}
|
2020-09-29 23:44:12 +02:00
|
|
|
|
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_data_from_dyn_arc() {
|
|
|
|
trait TestTrait {
|
|
|
|
fn get_num(&self) -> i32;
|
|
|
|
}
|
|
|
|
struct A {}
|
|
|
|
impl TestTrait for A {
|
|
|
|
fn get_num(&self) -> i32 {
|
|
|
|
42
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// This works when Sized is required
|
|
|
|
let dyn_arc_box: Arc<Box<dyn TestTrait>> = Arc::new(Box::new(A {}));
|
|
|
|
let data_arc_box = Data::from(dyn_arc_box);
|
|
|
|
// This works when Data Sized Bound is removed
|
|
|
|
let dyn_arc: Arc<dyn TestTrait> = Arc::new(A {});
|
|
|
|
let data_arc = Data::from(dyn_arc);
|
|
|
|
assert_eq!(data_arc_box.get_num(), data_arc.get_num())
|
|
|
|
}
|
2019-03-17 05:09:11 +01:00
|
|
|
}
|