Skip to main content

ntex/web/
config.rs

1use std::{any::Any, any::TypeId, cell::RefCell, net::SocketAddr, rc::Rc};
2
3use urly::Url;
4
5use crate::service::cfg::{CfgContext, Configuration};
6use crate::{router::ResourceDef, util::ByteString, util::HashMap};
7
8use super::httprequest::{HttpRequest, HttpRequestInner};
9use super::service::{AppServiceFactory, ServiceFactoryWrapper, WebServiceFactory};
10use super::{ForwardedPolicy, Resource, Route, State};
11
12/// Application configuration
13#[derive(Debug)]
14pub struct WebAppConfig {
15    name: ByteString,
16    secure: bool,
17    host: String,
18    addr: SocketAddr,
19    forwarded: ForwardedPolicy,
20    config: CfgContext,
21    state: HashMap<TypeId, Box<dyn Any + Sync + Send>>,
22    pub(super) pool_size: usize,
23}
24
25impl Default for WebAppConfig {
26    fn default() -> Self {
27        WebAppConfig::new()
28    }
29}
30
31impl Configuration for WebAppConfig {
32    const NAME: &str = "Web app configuration";
33
34    fn ctx(&self) -> &CfgContext {
35        &self.config
36    }
37
38    fn set_ctx(&mut self, ctx: CfgContext) {
39        self.config = ctx;
40    }
41}
42
43impl WebAppConfig {
44    #[must_use]
45    /// Create an default `WebAppConfig` instance.
46    pub fn new() -> Self {
47        WebAppConfig::with(
48            "ntex:web",
49            false,
50            "127.0.0.1:8080".parse().unwrap(),
51            "localhost:8080".to_owned(),
52        )
53    }
54
55    #[must_use]
56    /// Create an `WebAppConfig` instance.
57    pub fn with(name: &str, secure: bool, addr: SocketAddr, host: String) -> Self {
58        WebAppConfig {
59            secure,
60            host,
61            addr,
62            name: name.into(),
63            pool_size: 128,
64            forwarded: ForwardedPolicy::default(),
65            state: HashMap::default(),
66            config: CfgContext::default(),
67        }
68    }
69
70    /// Server name
71    pub fn name(&self) -> &ByteString {
72        &self.name
73    }
74
75    /// Server host name
76    ///
77    /// Host name is used by application router as a hostname for url generation.
78    /// Check [`ConnectionInfo::host()`](crate::web::dev::ConnectionInfo::host)
79    /// documentation for more information.
80    ///
81    /// By default host name is set to a "localhost:8080" value.
82    pub fn host(&self) -> &str {
83        &self.host
84    }
85
86    /// Returns true if connection is secure(https)
87    pub fn secure(&self) -> bool {
88        self.secure
89    }
90
91    /// Returns the socket address of the local half of this TCP connection
92    pub fn local_addr(&self) -> SocketAddr {
93        self.addr
94    }
95
96    /// Trust policy for the `Forwarded` and `X-Forwarded-*` request headers.
97    pub fn forwarded(&self) -> &ForwardedPolicy {
98        &self.forwarded
99    }
100
101    /// Get a configuration value stored with [`WebAppConfig::set_value()`].
102    ///
103    /// Returns `None` if no value of type `T` is stored.
104    pub fn value<T: 'static>(&self) -> Option<&T> {
105        self.state
106            .get(&TypeId::of::<T>())
107            .and_then(|boxed| boxed.downcast_ref())
108    }
109
110    #[doc(hidden)]
111    #[deprecated(since = "4.7.0", note = "use `WebAppConfig::value()` instead")]
112    pub fn state<T: 'static>(&self) -> Option<&T> {
113        self.value()
114    }
115
116    #[must_use]
117    /// Set server host name.
118    ///
119    /// By default host name is set to a "localhost:8080" value.
120    pub fn set_host(mut self, host: String) -> Self {
121        self.host = host;
122        self
123    }
124
125    #[must_use]
126    /// Connection is secure(https).
127    pub fn set_secure(mut self) -> Self {
128        self.secure = true;
129        self
130    }
131
132    #[must_use]
133    /// Set the trust policy for the `Forwarded` and `X-Forwarded-*` request
134    /// headers, used by [`ConnectionInfo`](crate::web::dev::ConnectionInfo).
135    ///
136    /// By default the headers are ignored, see [`ForwardedPolicy`].
137    pub fn set_forwarded(mut self, policy: ForwardedPolicy) -> Self {
138        self.forwarded = policy;
139        self
140    }
141
142    #[must_use]
143    /// Set the socket address of the local half of the TCP connection.
144    pub fn set_local_addr(mut self, addr: SocketAddr) -> Self {
145        self.addr = addr;
146        self
147    }
148
149    #[must_use]
150    /// Set size of `HttpRequest` pool size.
151    ///
152    /// By default pool size is 128.
153    pub fn set_pool_size(mut self, size: usize) -> Self {
154        self.pool_size = size;
155        self
156    }
157
158    #[must_use]
159    /// Store a typed configuration value, replacing any value of the same type.
160    ///
161    /// Values are available at runtime via [`HttpRequest::app_value()`].
162    /// Built-in extractors read their configuration, such as
163    /// [`JsonConfig`](super::types::JsonConfig),
164    /// [`FormConfig`](super::types::FormConfig) and
165    /// [`PayloadConfig`](super::types::PayloadConfig), only from here.
166    ///
167    /// This store is separate from the application state `St`
168    /// (for example [`AppState<T>`](super::AppState)) passed to handlers
169    /// registered with [`Route::to_with_state()`](super::Route::to_with_state);
170    /// extractor configuration placed in the application state is ignored.
171    pub fn set_value<T: Send + Sync + 'static>(mut self, val: T) -> Self {
172        self.state.insert(TypeId::of::<T>(), Box::new(val));
173        self
174    }
175
176    #[must_use]
177    #[doc(hidden)]
178    #[deprecated(since = "4.7.0", note = "use `WebAppConfig::set_value()` instead")]
179    pub fn set_state<T: Send + Sync + 'static>(self, val: T) -> Self {
180        self.set_value(val)
181    }
182}
183
184/// Get message from the pool of the shared configuration with the given id.
185pub(crate) fn get_request(id: usize) -> Option<HttpRequest> {
186    CACHE
187        .try_with(|cache| cache.with(id, Vec::pop))
188        .ok()
189        .flatten()
190        .map(HttpRequest)
191}
192
193/// Put message from the pool.
194///
195/// The request is dropped instead if the pool is full, the request is still
196/// shared, or the thread's pool is already destroyed.
197pub(crate) fn put_request(id: usize, pool_size: usize, req: &mut Rc<HttpRequestInner>) {
198    let has_room = |cache: &LocalCache| cache.with(id, |cache| cache.len() < pool_size);
199    if !CACHE.try_with(has_room).unwrap_or(false) {
200        return;
201    }
202    if let Some(inner) = Rc::get_mut(req) {
203        // the head and the path may share the connection read buffer,
204        // a pooled request must not keep it alive.
205        // clearing runs user drop code that may drop other requests,
206        // so the pool must not be borrowed here
207        inner.head.clear();
208        inner.path.set(Url::new());
209
210        let _ = CACHE.try_with(|cache| {
211            cache.with(id, |cache| {
212                if cache.len() < pool_size {
213                    cache.push(req.clone());
214                }
215            });
216        });
217    }
218}
219
220/// Service config is used for external configuration.
221///
222/// Part of application configuration could be offloaded
223/// to set of external methods. This could help with
224/// modularization of big application configuration.
225///
226/// `St` is the application state and defaults to `()`. Use
227/// `ServiceConfig<AppState<T>>` for a stateful application, or a generic
228/// `fn config<St: web::State>(cfg: &mut ServiceConfig<St>)` for a module that
229/// works with any state.
230#[derive(derive_more::Debug)]
231#[debug("ServiceConfig")]
232pub struct ServiceConfig<St = (), In = ()> {
233    pub(super) services: Vec<Box<dyn AppServiceFactory<St, In>>>,
234    pub(super) external: Vec<ResourceDef>,
235}
236
237impl<St: State, In: 'static> ServiceConfig<St, In> {
238    /// Create a service configuration with the given external resources.
239    pub fn new(external: Vec<ResourceDef>) -> Self {
240        Self {
241            external,
242            services: Vec::new(),
243        }
244    }
245
246    /// Register a route for an application path.
247    ///
248    /// This has the same behavior as [`App::route()`]: it creates a separate
249    /// resource containing the route and promotes the route's method and custom
250    /// guards to resource guards. A request must match one of the
251    /// route's methods and every custom guard.
252    ///
253    /// [`App::route()`]: super::App::route
254    pub fn route(&mut self, path: &str, mut route: Route<St, In>) -> &mut Self {
255        self.service(
256            Resource::new(path)
257                .add_guards(route.take_guards())
258                .route(route),
259        )
260    }
261
262    /// Registers a web service with the current application or scope.
263    ///
264    /// This has the same routing behavior as [`App::service()`]. The service
265    /// can be a resource, scope, attribute-macro handler, or custom
266    /// [`WebServiceFactory`]. When this configuration is used by a scope, the
267    /// service is registered below that scope's path prefix.
268    ///
269    /// ```rust
270    /// use ntex::web::{self, App, ServiceConfig};
271    ///
272    /// fn configure(cfg: &mut ServiceConfig<()>) {
273    ///     cfg.service(
274    ///         web::resource("/health").to(async || "OK"),
275    ///     );
276    /// }
277    ///
278    /// App::default().configure(configure);
279    /// ```
280    ///
281    /// [`App::service()`]: super::App::service
282    pub fn service<F>(&mut self, factory: F) -> &mut Self
283    where
284        F: WebServiceFactory<St, In> + 'static,
285    {
286        self.services
287            .push(Box::new(ServiceFactoryWrapper::new(factory)));
288        self
289    }
290
291    /// Register an external resource.
292    ///
293    /// External resources are useful for URL generation purposes only
294    /// and are never considered for matching at request time. Calls to
295    /// `HttpRequest::url_for()` will work as expected.
296    ///
297    /// This is same as `App::external_resource()` method.
298    pub fn external_resource(&mut self, name: impl AsRef<str>, url: impl AsRef<str>) -> &mut Self {
299        let mut rdef = ResourceDef::new(url.as_ref());
300        rdef.set_name(name.as_ref());
301        self.external.push(rdef);
302        self
303    }
304}
305
306thread_local! {
307    static CACHE: LocalCache = LocalCache::new();
308}
309
310/// Request's objects pool
311struct LocalCache {
312    cache: RefCell<Vec<Vec<Rc<HttpRequestInner>>>>,
313}
314
315impl LocalCache {
316    fn new() -> Self {
317        Self {
318            cache: RefCell::new(Vec::with_capacity(16)),
319        }
320    }
321
322    /// Calls `f` with the pool for `idx`.
323    ///
324    /// `f` must not drop requests or run user code, the pool stays borrowed
325    /// while it runs.
326    fn with<F, R>(&self, idx: usize, f: F) -> R
327    where
328        F: FnOnce(&mut Vec<Rc<HttpRequestInner>>) -> R,
329    {
330        let mut cache = self.cache.borrow_mut();
331
332        while cache.len() <= idx {
333            cache.push(Vec::new());
334        }
335        f(&mut cache[idx])
336    }
337}
338
339#[cfg(test)]
340#[allow(clippy::assert_is_empty)]
341mod tests {
342    use super::*;
343    use crate::http::{Method, StatusCode};
344    use crate::util::Bytes;
345    use crate::web::test::{TestRequest, call_service, init_service, read_body};
346    use crate::web::{self, App, HttpRequest, HttpResponse};
347
348    struct DropRequest(#[allow(dead_code)] HttpRequest);
349
350    /// STATEMENT: Returning a request to the pool tolerates request extensions
351    /// that drop other requests while they are cleared.
352    ///
353    /// HOW:
354    /// - Create an outer request, then keep creating requests until one has a
355    ///   config id far beyond the outer one, so pooling it grows the pool list.
356    /// - Store that request in an extension of the outer request and drop the
357    ///   outer request, which re-enters `put_request` while clearing the head.
358    /// - Check both requests were pooled under their own config ids and the
359    ///   pooled outer request has no extensions left.
360    #[test]
361    fn miri_put_request_reentrant_drop() {
362        let outer = TestRequest::default().to_http_request();
363        let outer_id = outer.0.config.id();
364
365        let mut held = Vec::new();
366        let inner = loop {
367            let req = TestRequest::default().to_http_request();
368            if req.0.config.id() > 2 * outer_id + 32 {
369                break req;
370            }
371            held.push(req);
372        };
373        let inner_id = inner.0.config.id();
374
375        outer.extensions_mut().insert(DropRequest(inner));
376        drop(outer);
377
378        let pooled = get_request(outer_id).unwrap();
379        assert!(pooled.extensions().get::<DropRequest>().is_none());
380        assert!(get_request(inner_id).is_some());
381        drop(held);
382    }
383
384    thread_local! {
385        static HELD: std::cell::RefCell<Option<HttpRequest>> =
386            const { std::cell::RefCell::new(None) };
387    }
388
389    /// STATEMENT: Dropping a request after the thread's request pool is
390    /// destroyed does not panic.
391    ///
392    /// HOW:
393    /// - On a new thread, touch `HELD` before the pool so its destructor is
394    ///   registered first and therefore runs after the pool is destroyed.
395    /// - Initialize the pool by dropping a request, then store another request
396    ///   in `HELD`.
397    /// - Join the thread and check it exited without a panic or abort.
398    #[test]
399    fn miri_drop_request_after_pool_destroyed() {
400        std::thread::spawn(|| {
401            HELD.with(|_| {});
402            drop(TestRequest::default().to_http_request());
403            HELD.with(|held| {
404                *held.borrow_mut() = Some(TestRequest::default().to_http_request());
405            });
406        })
407        .join()
408        .unwrap();
409    }
410
411    /// STATEMENT: `WebAppConfig` retains explicit settings and exposes its default identity.
412    ///
413    /// HOW:
414    /// - Set the host, local address, and pool size and assert their stored values.
415    /// - Check the default name and insecure mode, then enable and assert secure mode.
416    #[crate::rt_test]
417    async fn test_webappconfig() {
418        let cfg = WebAppConfig::default()
419            .set_host("www.example.org".to_string())
420            .set_local_addr("127.0.0.1:8080".parse().unwrap())
421            .set_pool_size(256);
422        assert_eq!(cfg.host(), "www.example.org");
423        assert_eq!(cfg.local_addr(), "127.0.0.1:8080".parse().unwrap());
424        assert_eq!(cfg.pool_size, 256);
425        assert_eq!(cfg.name(), "ntex:web");
426        assert!(!cfg.secure());
427        assert!(cfg.set_secure().secure());
428    }
429
430    /// STATEMENT: An external resource registered through `configure` supports URL generation.
431    ///
432    /// HOW:
433    /// - Configure a `youtube` external resource and return its generated URL from `/test`.
434    /// - Call the service and assert an OK response containing the substituted video URL.
435    #[crate::rt_test]
436    async fn test_configure_external_resource() {
437        let srv = init_service(
438            App::new()
439                .configure(|cfg| {
440                    cfg.external_resource("youtube", "https://youtube.com/watch/{video_id}");
441                })
442                .route(
443                    "/test",
444                    web::get().to(async move |req: HttpRequest| {
445                        HttpResponse::Ok()
446                            .body(format!("{}", req.url_for("youtube", ["12345"]).unwrap()))
447                    }),
448                ),
449        )
450        .await;
451        let req = TestRequest::with_uri("/test").to_request();
452        let resp = call_service(&srv, req).await;
453        assert_eq!(resp.status(), StatusCode::OK);
454        let body = read_body(resp).await;
455        assert_eq!(body, Bytes::from_static(b"https://youtube.com/watch/12345"));
456    }
457
458    /// STATEMENT: `ServiceConfig` registers both resources and direct routes in an application.
459    ///
460    /// HOW:
461    /// - Configure a resource returning `Created` and a direct route returning `Ok`.
462    /// - Send GET requests to both paths and assert their distinct response statuses.
463    #[crate::rt_test]
464    async fn test_configure_service() {
465        let srv = init_service(App::new().configure(|cfg| {
466            cfg.service(
467                web::resource("/test").route(web::get().to(async || HttpResponse::Created())),
468            )
469            .route("/index.html", web::get().to(async || HttpResponse::Ok()));
470        }))
471        .await;
472
473        let req = TestRequest::with_uri("/test")
474            .method(Method::GET)
475            .to_request();
476        let resp = call_service(&srv, req).await;
477        assert_eq!(resp.status(), StatusCode::CREATED);
478
479        let req = TestRequest::with_uri("/index.html")
480            .method(Method::GET)
481            .to_request();
482        let resp = call_service(&srv, req).await;
483        assert_eq!(resp.status(), StatusCode::OK);
484    }
485}