#1736 Trying to improve the documentation for App::data()

Open lfrancke
Coverage Reach
actix-http/src/h1/dispatcher.rs actix-http/src/h1/decoder.rs actix-http/src/h1/encoder.rs actix-http/src/h1/service.rs actix-http/src/h1/client.rs actix-http/src/h1/codec.rs actix-http/src/h1/payload.rs actix-http/src/h1/utils.rs actix-http/src/h1/mod.rs actix-http/src/h1/expect.rs actix-http/src/h1/upgrade.rs actix-http/src/header/common/content_disposition.rs actix-http/src/header/common/range.rs actix-http/src/header/common/content_range.rs actix-http/src/header/common/cache_control.rs actix-http/src/header/common/if_range.rs actix-http/src/header/common/mod.rs actix-http/src/header/common/content_type.rs actix-http/src/header/common/accept.rs actix-http/src/header/common/date.rs actix-http/src/header/common/last_modified.rs actix-http/src/header/common/allow.rs actix-http/src/header/shared/charset.rs actix-http/src/header/shared/entity.rs actix-http/src/header/shared/quality_item.rs actix-http/src/header/shared/httpdate.rs actix-http/src/header/shared/encoding.rs actix-http/src/header/map.rs actix-http/src/header/mod.rs actix-http/src/client/pool.rs actix-http/src/client/connector.rs actix-http/src/client/h1proto.rs actix-http/src/client/h2proto.rs actix-http/src/client/connection.rs actix-http/src/client/error.rs actix-http/src/client/config.rs actix-http/src/ws/codec.rs actix-http/src/ws/frame.rs actix-http/src/ws/proto.rs actix-http/src/ws/mod.rs actix-http/src/ws/mask.rs actix-http/src/ws/dispatcher.rs actix-http/src/response.rs actix-http/src/encoding/encoder.rs actix-http/src/encoding/decoder.rs actix-http/src/encoding/mod.rs actix-http/src/h2/dispatcher.rs actix-http/src/h2/service.rs actix-http/src/h2/mod.rs actix-http/src/message.rs actix-http/src/service.rs actix-http/src/body.rs actix-http/src/error.rs actix-http/src/config.rs actix-http/src/test.rs actix-http/src/builder.rs actix-http/src/request.rs actix-http/src/httpmessage.rs actix-http/src/helpers.rs actix-http/src/extensions.rs actix-http/src/time_parser.rs actix-http/src/payload.rs actix-http/src/cloneable.rs actix-http/src/httpcodes.rs actix-http/src/macros.rs src/types/json.rs src/types/payload.rs src/types/form.rs src/types/path.rs src/types/readlines.rs src/types/query.rs src/middleware/logger.rs src/middleware/normalize.rs src/middleware/defaultheaders.rs src/middleware/compress.rs src/middleware/errhandlers.rs src/middleware/condition.rs src/scope.rs src/test.rs src/request.rs src/resource.rs src/service.rs src/server.rs src/app.rs src/rmap.rs src/responder.rs src/guard.rs src/app_service.rs src/data.rs src/info.rs src/config.rs src/route.rs src/extract.rs src/request_data.rs src/handler.rs src/error.rs src/web.rs src/lib.rs awc/src/request.rs awc/src/ws.rs awc/src/sender.rs awc/src/response.rs awc/src/frozen.rs awc/src/builder.rs awc/src/connect.rs awc/src/test.rs awc/src/lib.rs awc/src/error.rs actix-files/src/named.rs actix-files/src/files.rs actix-files/src/service.rs actix-files/src/range.rs actix-files/src/chunked.rs actix-files/src/path_buf.rs actix-files/src/directory.rs actix-files/src/error.rs actix-files/src/lib.rs tests/test_server.rs tests/test_httpserver.rs actix-multipart/src/server.rs actix-multipart/src/extractor.rs actix-multipart/src/error.rs actix-web-actors/src/ws.rs actix-web-actors/src/context.rs actix-web-codegen/src/route.rs

No flags found

Use flags to group coverage reports by test type, project and/or folders.
Then setup custom commit statuses and notifications for each flag.

e.g., #unittest #integration

#production #enterprise

#frontend #backend

Learn more about Codecov Flags here.

Showing 2 of 2 files from the diff.

@@ -18,49 +18,11 @@
Loading
18 18
pub(crate) type FnDataFactory =
19 19
    Box<dyn Fn() -> LocalBoxFuture<'static, Result<Box<dyn DataFactory>, ()>>>;
20 20
21 -
/// Application data.
21 +
/// Wrapper for a piece of data.
22 22
///
23 -
/// Application level data is a piece of arbitrary data attached to the app, scope, or resource.
24 -
/// Application data is available to all routes and can be added during the application
25 -
/// configuration process via `App::data()`.
23 +
/// Internally it wraps the data in an `Arc`.
26 24
///
27 -
/// Application data can be accessed by using `Data<T>` extractor where `T` is data type.
28 -
///
29 -
/// **Note**: http server accepts an application factory rather than an application instance. HTTP
30 -
/// server constructs an application instance for each thread, thus application data must be
31 -
/// constructed multiple times. If you want to share data between different threads, a shareable
32 -
/// object should be used, e.g. `Send + Sync`. Application data does not need to be `Send`
33 -
/// or `Sync`. Internally `Data` uses `Arc`.
34 -
///
35 -
/// If route data is not set for a handler, using `Data<T>` extractor would cause *Internal
36 -
/// Server Error* response.
37 -
///
38 -
/// ```rust
39 -
/// use std::sync::Mutex;
40 -
/// use actix_web::{web, App, HttpResponse, Responder};
41 -
///
42 -
/// struct MyData {
43 -
///     counter: usize,
44 -
/// }
45 -
///
46 -
/// /// Use the `Data<T>` extractor to access data in a handler.
47 -
/// async fn index(data: web::Data<Mutex<MyData>>) -> impl Responder {
48 -
///     let mut data = data.lock().unwrap();
49 -
///     data.counter += 1;
50 -
///     HttpResponse::Ok()
51 -
/// }
52 -
///
53 -
/// fn main() {
54 -
///     let data = web::Data::new(Mutex::new(MyData{ counter: 0 }));
55 -
///
56 -
///     let app = App::new()
57 -
///         // Store `MyData` in application storage.
58 -
///         .app_data(data.clone())
59 -
///         .service(
60 -
///             web::resource("/index.html").route(
61 -
///                 web::get().to(index)));
62 -
/// }
63 -
/// ```
25 +
/// See `App::data()` and `App::app_data()` for when and how to use this.
64 26
#[derive(Debug)]
65 27
pub struct Data<T: ?Sized>(Arc<T>);
66 28

@@ -70,16 +70,28 @@
Loading
70 70
        InitError = (),
71 71
    >,
72 72
{
73 -
    /// Set application data. Application data could be accessed
74 -
    /// by using `Data<T>` extractor where `T` is data type.
73 +
    /// Adds an arbirtraty application level data item.
75 74
    ///
76 -
    /// **Note**: http server accepts an application factory rather than
77 -
    /// an application instance. Http server constructs an application
78 -
    /// instance for each thread, thus application data must be constructed
79 -
    /// multiple times. If you want to share data between different
80 -
    /// threads, a shared object should be used, e.g. `Arc`. Internally `Data` type
81 -
    /// uses `Arc` so data could be created outside of app factory and clones could
82 -
    /// be stored via `App::app_data()` method.
75 +
    /// Application data can be accessed by using a `Data<T>` extractor where `T` is the data type.
76 +
    ///
77 +
    /// The state is managed on a per-type basis and as such there can be
78 +
    /// at most one value for any given type.
79 +
    /// This means that only the first invocation of this function per type will have an effect,
80 +
    /// all later ones will be ignored.
81 +
    ///
82 +
    /// Internally the data will be wrapped in an `Arc`.
83 +
    /// If your data is already wrapped in an `Arc`
84 +
    /// you can instead store it directly using the `App::app_data()` function.
85 +
    ///
86 +
    /// **Note**: `HttpServer` accepts an application factory (closure) rather than
87 +
    /// an application instance (`App`).
88 +
    /// `HttpServer` constructs an application instance for each thread
89 +
    /// by calling this factory closure thus application data must be constructed multiple times.
90 +
    /// If you want to share data between different threads,
91 +
    /// a shared object should be used, e.g. `Arc`.
92 +
    ///
93 +
    /// If route data is not set for a handler, using `Data<T>` extractor would cause an *Internal
94 +
    /// Server Error* response.
83 95
    ///
84 96
    /// ```rust
85 97
    /// use std::cell::Cell;
@@ -136,13 +148,60 @@
Loading
136 148
        self
137 149
    }
138 150
139 -
    /// Set application level arbitrary data item.
151 +
    /// Adds an arbirtraty application level data item.
152 +
    ///
153 +
    /// This data is available to all routes and can be added during the application.
154 +
    /// There are two ways to retrieve this data:
155 +
    ///
156 +
    /// 1. At runtime via the `HttpRequest::app_data()` method
157 +
    /// 2. If data of type `T` is stored wrapped in a `Data<T>` object
158 +
    ///    it can also be retrieved using a `Data<T>` extractor
140 159
    ///
141 -
    /// Application data stored with `App::app_data()` method is available
142 -
    /// via `HttpRequest::app_data()` method at runtime.
160 +
    /// The state is managed on a per-type basis and as such there can be
161 +
    /// at most one value for any given type.
162 +
    /// Later invocations overwrite earlier ones.
163 +
    /// This means that only the last invocation of this function per type will have an effect.
143 164
    ///
144 -
    /// This method could be used for storing `Data<T>` as well, in that case
145 -
    /// data could be accessed by using `Data<T>` extractor.
165 +
    /// **Note**: `HttpServer` accepts an application factory (closure) rather than
166 +
    /// an application instance (`App`).
167 +
    /// `HttpServer` constructs an application instance for each thread
168 +
    /// by calling this factory closure thus application data must be constructed multiple times.
169 +
    /// If you want to share data between different threads,
170 +
    /// a shared object should be used, e.g. `Arc`.
171 +
    ///
172 +
    /// ```rust
173 +
    /// use std::sync::Mutex;
174 +
    /// use actix_web::{web, App, HttpResponse, HttpRequest, Responder};
175 +
    ///
176 +
    /// struct MyData {
177 +
    ///     counter: usize,
178 +
    /// }
179 +
    ///
180 +
    /// /// Use the `Data<T>` extractor to access data in a handler.
181 +
    /// async fn index(data: web::Data<Mutex<MyData>>) -> impl Responder {
182 +
    ///     let mut data = data.lock().unwrap();
183 +
    ///     data.counter += 1;
184 +
    ///     HttpResponse::Ok().body(format!("{}", data.counter))
185 +
    /// }
186 +
    ///
187 +
    /// async fn hello(req: HttpRequest) -> impl Responder {
188 +
    ///    let data = req.app_data::<web::Data<Mutex<MyData>>>();
189 +
    ///    let mut data = data.unwrap().lock().unwrap();
190 +
    ///    data.counter += 1;
191 +
    ///    HttpResponse::Ok().body(format!("{}", data.counter))
192 +
    ///}
193 +
    ///
194 +
    /// fn main() {
195 +
    ///     let data = web::Data::new(Mutex::new(MyData{ counter: 0 }));
196 +
    ///
197 +
    ///     let app = App::new()
198 +
    ///         // Store `MyData` in application storage.
199 +
    ///         .app_data(data)
200 +
    ///         .service(
201 +
    ///             web::resource("/index.html").route(
202 +
    ///                 web::get().to(index)));
203 +
    /// }
204 +
    /// ```
146 205
    pub fn app_data<U: 'static>(mut self, ext: U) -> Self {
147 206
        self.extensions.insert(ext);
148 207
        self

Everything is accounted for!

No changes detected that need to be reviewed.
What changes does Codecov check for?
Lines, not adjusted in diff, that have changed coverage data.
Files that introduced coverage data that had none before.
Files that have missing coverage data that once were tracked.
Files Coverage
actix-files/src 0.00%
actix-http/src 37.87%
actix-multipart/src 0.00%
actix-web-actors/src 0.00%
awc/src 17.98%
src 87.02%
tests 100.00%
actix-web-codegen/src/route.rs 0.00%
Project Totals (125 files) 53.98%
Loading