Skip to main content

ntex/web/
state.rs

1use super::error::DefaultError;
2
3/// Application state used by web services.
4///
5/// A [`web::App`](super::App) is parameterized by a type that implements this
6/// trait. The state is available to handlers registered with
7/// [`Route::to_with_state()`](super::Route::to_with_state), and to filters,
8/// middleware, and services through their service context.
9///
10/// The associated `Error` type selects the application's error domain, which
11/// is used by [`WebError`](super::WebError) and
12/// [`WebResponseError`](super::WebResponseError). Most applications use
13/// [`DefaultError`].
14///
15/// The trait does not require `Clone`, but serving an application does:
16/// the server and [`HttpService`](crate::http::HttpService) clone the state
17/// for each connection.
18///
19/// ```rust
20/// use ntex::web;
21///
22/// #[derive(Clone)]
23/// struct ApplicationState {
24///     greeting: String,
25/// }
26///
27/// impl web::State for ApplicationState {
28///     type Error = web::DefaultError;
29/// }
30/// ```
31#[diagnostic::on_unimplemented(
32    message = "`{Self}` is not a web application state",
33    label = "does not implement `web::State`",
34    note = "implement `web::State` for `{Self}` with `type Error = web::DefaultError;`, or wrap it in `web::AppState<{Self}>`"
35)]
36pub trait State: 'static {
37    /// Error domain used by the application.
38    type Error;
39}
40
41impl State for () {
42    type Error = DefaultError;
43}
44
45/// Wraps a value so it can be used as application state with [`DefaultError`].
46///
47/// `AppState<T>` implements [`State`] for any `'static` `T`, so a separate
48/// `State` implementation is not needed. It dereferences to the wrapped value
49/// and implements `Clone` and `Default` when `T` does.
50///
51/// Extractor configuration such as
52/// [`JsonConfig`](super::types::JsonConfig) is not read from application
53/// state; store it with
54/// [`WebAppConfig::set_value()`](super::WebAppConfig::set_value) instead.
55///
56/// ```rust
57/// use ntex::web;
58///
59/// #[derive(Clone)]
60/// struct Settings {
61///     service_name: &'static str,
62/// }
63///
64/// let state = web::AppState::new(Settings { service_name: "users" });
65/// assert_eq!(state.service_name, "users");
66/// ```
67#[derive(Clone, Default)]
68#[doc(alias = "Data")]
69pub struct AppState<T> {
70    state: T,
71}
72
73impl<T> AppState<T> {
74    /// Creates application state that wraps `state`.
75    pub fn new(state: T) -> Self {
76        AppState { state }
77    }
78
79    /// Returns a reference to the wrapped value.
80    pub fn st(&self) -> &T {
81        &self.state
82    }
83}
84
85impl<T: 'static> State for AppState<T> {
86    type Error = DefaultError;
87}
88
89impl<T> std::ops::Deref for AppState<T> {
90    type Target = T;
91
92    fn deref(&self) -> &T {
93        &self.state
94    }
95}
96
97#[cfg(test)]
98mod tests {
99    use std::{cell::Cell, convert::Infallible, rc::Rc};
100
101    use super::*;
102    use crate::http::{Method, StatusCode};
103    use crate::service::ServiceFactory;
104    use crate::web::test::{TestRequest, init_service_st, read_body};
105    use crate::web::{self, App, HttpRequest, WebRequest, types::Path};
106
107    #[derive(Clone, Default)]
108    struct Counter {
109        name: &'static str,
110        hits: Rc<Cell<usize>>,
111    }
112
113    type St = AppState<Counter>;
114
115    async fn index(st: &St, (): ()) -> String {
116        st.hits.set(st.hits.get() + 1);
117        format!("index:{}", st.name)
118    }
119
120    async fn item(st: &St, (): (), id: Path<u32>) -> String {
121        format!("item:{}:{}", st.st().name, id.into_inner())
122    }
123
124    async fn fallback(st: &St, (): (), req: HttpRequest) -> String {
125        format!("fallback:{}:{}", st.name, req.method())
126    }
127
128    async fn filtered(_: &St, n: usize) -> String {
129        format!("filtered:{n}")
130    }
131
132    /// STATEMENT: State-aware handlers compose with extractors, method routes, fallbacks, and filters.
133    ///
134    /// HOW:
135    /// - Build handlers sharing named counter state, a numeric path extractor, and a state-mapping filter.
136    /// - Assert exact statuses and bodies for valid/invalid paths, method-specific handlers, and fallbacks.
137    /// - Assert the filter supplies numeric input and exactly three calls increment shared state.
138    #[crate::rt_test]
139    async fn state_handlers() {
140        let st = AppState::new(Counter {
141            name: "app",
142            ..Counter::default()
143        });
144        let srv = init_service_st(
145            st.clone(),
146            App::<St>::new()
147                .service(web::resource("/index").to_with_state(index))
148                .service(web::resource("/item/{id}").to_with_state(item))
149                .service(
150                    web::resource("/multi")
151                        .route(web::get().to(async || "get"))
152                        .route(web::delete().to_with_state(index))
153                        .to(async || "any"),
154                )
155                .service(
156                    web::resource("/fallback")
157                        .route(web::get().to(async || "get"))
158                        .to_with_state(fallback),
159                )
160                .service(
161                    web::resource("/filtered")
162                        .filter(async |req: WebRequest<()>| {
163                            Ok::<_, Infallible>(req.map_state(|()| 7usize))
164                        })
165                        .to_with_state(filtered),
166                )
167                .route("/route", web::to_with_state(index))
168                .build(),
169        )
170        .await;
171
172        let check = async |method: Method, uri: &str, status: StatusCode, body: &str| {
173            let req = TestRequest::with_uri(uri).method(method).to_request();
174            let resp = srv.call(req).await.unwrap();
175            assert_eq!(resp.status(), status, "{uri}");
176            assert_eq!(read_body(resp).await, body.as_bytes(), "{uri}");
177        };
178
179        check(Method::GET, "/index", StatusCode::OK, "index:app").await;
180        check(Method::GET, "/item/10", StatusCode::OK, "item:app:10").await;
181        check(
182            Method::GET,
183            "/item/abc",
184            StatusCode::NOT_FOUND,
185            "Path deserialize error: can not parse \"abc\" to a u32",
186        )
187        .await;
188        check(Method::GET, "/multi", StatusCode::OK, "get").await;
189        check(Method::DELETE, "/multi", StatusCode::OK, "index:app").await;
190        check(Method::POST, "/multi", StatusCode::OK, "any").await;
191        check(Method::GET, "/fallback", StatusCode::OK, "get").await;
192        check(
193            Method::POST,
194            "/fallback",
195            StatusCode::OK,
196            "fallback:app:POST",
197        )
198        .await;
199        check(Method::GET, "/filtered", StatusCode::OK, "filtered:7").await;
200        check(Method::PUT, "/route", StatusCode::OK, "index:app").await;
201        assert_eq!(st.hits.get(), 3);
202    }
203
204    /// STATEMENT: `build_with` supplies fixed handler state independently of the pipeline's state type.
205    ///
206    /// HOW:
207    /// - Build a counter-state application with a `usize` pipeline state.
208    /// - Assert the registered route is OK, a missing path is 404, and the fixed counter increments once.
209    #[crate::rt_test]
210    async fn build_with() {
211        let st = AppState::new(Counter {
212            name: "fixed",
213            ..Counter::default()
214        });
215        let srv = App::<St>::new()
216            .route("/", web::get().to_with_state(index))
217            .build_with::<usize>(st.clone())
218            .pipeline(1usize)
219            .await
220            .unwrap();
221
222        let resp = srv.call(TestRequest::default().to_request()).await.unwrap();
223        assert_eq!(resp.status(), StatusCode::OK);
224        let resp = srv
225            .call(TestRequest::with_uri("/missing").to_request())
226            .await
227            .unwrap();
228        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
229        assert_eq!(st.hits.get(), 1);
230    }
231}