Skip to main content

ntex/web/
service.rs

1use std::{marker::PhantomData, rc::Rc};
2
3use ntex_http::Method;
4use ntex_util::HashSet;
5
6use crate::error::{Failure, IntoFailure};
7use crate::http::{Response, header};
8use crate::router::{IntoPattern, ResourceDef};
9use crate::service::{IntoServiceFactory, ServiceFactory, boxed};
10
11use super::error::{InternalError, WebError, WebResponseError};
12use super::guard::{AllGuard, Guard};
13use super::route::RouteService;
14use super::{HttpService, State, WebRequest, WebResponse, dev::insert_slash, rmap::ResourceMap};
15
16/// Factory of web services that can be registered with an application or scope.
17///
18/// `App::service()` and `Scope::service()` accept any `WebServiceFactory`.
19/// It is implemented by [`Resource`](crate::web::Resource),
20/// [`Scope`](crate::web::Scope), services generated by the route attribute
21/// macros, and services built with `web::service()`.
22pub trait WebServiceFactory<St: State, In>: 'static {
23    /// Register the service, its path, and its guards in `config`.
24    fn register(self, config: &mut WebServiceConfig<St, In>);
25}
26
27pub(super) trait AppServiceFactory<St: State, In> {
28    fn register(&mut self, config: &mut WebServiceConfig<St, In>);
29}
30
31pub(super) struct ServiceFactoryWrapper<T> {
32    factory: Option<T>,
33}
34
35impl<T> ServiceFactoryWrapper<T> {
36    pub(super) fn new(factory: T) -> Self {
37        Self {
38            factory: Some(factory),
39        }
40    }
41}
42
43impl<T, St, In> AppServiceFactory<St, In> for ServiceFactoryWrapper<T>
44where
45    T: WebServiceFactory<St, In>,
46    St: State,
47{
48    fn register(&mut self, config: &mut WebServiceConfig<St, In>) {
49        if let Some(item) = self.factory.take() {
50            item.register(config);
51        }
52    }
53}
54
55type Guards = Vec<Box<dyn Guard>>;
56
57/// Service registered with a router.
58#[derive(Debug)]
59pub(crate) enum WebRoute<St: State, In> {
60    /// A service created per router instance.
61    Service(HttpService<St, In>),
62    /// Routes of a resource without middleware, filter, or fallback.
63    ///
64    /// The router dispatches to the first matching route itself and returns
65    /// `405 Method Not Allowed` if no route matches.
66    Routes(Box<[RouteService<St, In>]>),
67}
68
69/// Application service configuration
70#[derive(derive_more::Debug)]
71#[debug("WebServiceConfig")]
72pub struct WebServiceConfig<St: State, In = ()> {
73    root: bool,
74    services: Vec<(
75        ResourceDef,
76        WebRoute<St, In>,
77        Option<Guards>,
78        Option<Rc<ResourceMap>>,
79    )>,
80}
81
82impl<St: State, In: 'static> WebServiceConfig<St, In> {
83    /// Create server settings instance
84    pub(crate) fn new() -> Self {
85        WebServiceConfig {
86            root: true,
87            services: Vec::new(),
88        }
89    }
90
91    /// Check if root is being configured
92    pub fn is_root(&self) -> bool {
93        self.root
94    }
95
96    pub(crate) fn into_services(
97        self,
98    ) -> Vec<(
99        ResourceDef,
100        WebRoute<St, In>,
101        Option<Guards>,
102        Option<Rc<ResourceMap>>,
103    )> {
104        self.services
105    }
106
107    /// Register http service
108    pub fn register_service<S>(
109        &mut self,
110        rdef: ResourceDef,
111        guards: Option<Vec<Box<dyn Guard>>>,
112        nested: Option<Rc<ResourceMap>>,
113        factory: impl IntoServiceFactory<S, St, WebRequest<In>>,
114    ) where
115        S: ServiceFactory<
116                St,
117                WebRequest<In>,
118                Res = WebResponse,
119                Error = WebError<St, St::Error>,
120                InitError = Failure,
121            > + 'static,
122    {
123        self.services.push((
124            rdef,
125            WebRoute::Service(boxed::factory(factory.into_factory())),
126            guards,
127            nested,
128        ));
129    }
130
131    /// Register routes that the router dispatches to directly.
132    pub(super) fn register_routes(
133        &mut self,
134        rdef: ResourceDef,
135        guards: Option<Vec<Box<dyn Guard>>>,
136        routes: Vec<RouteService<St, In>>,
137    ) {
138        self.services
139            .push((rdef, WebRoute::Routes(routes.into()), guards, None));
140    }
141}
142
143/// Create service adapter for a specific path.
144///
145/// ```rust
146/// use std::convert::Infallible;
147/// use ntex::web::{self, guard, App, HttpResponse};
148///
149/// async fn my_service(req: web::WebRequest<()>) -> Result<web::WebResponse, Infallible> {
150///     Ok(req.into_response(HttpResponse::Ok().build()))
151/// }
152///
153/// let app = App::default().service(
154///     web::service("/users/*")
155///         .guard(guard::Header("content-type", "text/plain"))
156///         .build(my_service)
157/// );
158/// ```
159#[derive(Debug)]
160pub struct WebServiceAdapter {
161    rdef: Vec<String>,
162    name: Option<String>,
163    guards: AllGuard,
164    methods: HashSet<Method>,
165}
166
167impl WebServiceAdapter {
168    #[must_use]
169    #[allow(clippy::needless_pass_by_value)]
170    /// Create new `WebServiceAdapter` instance.
171    pub fn new<T: IntoPattern>(path: T) -> Self {
172        WebServiceAdapter {
173            rdef: path.patterns(),
174            name: None,
175            guards: AllGuard::default(),
176            methods: HashSet::default(),
177        }
178    }
179
180    /// Set service name.
181    ///
182    /// Name is used for url generation, it must be unique within the
183    /// enclosing scope or application, which panics on start otherwise.
184    #[must_use]
185    pub fn name(mut self, name: &str) -> Self {
186        self.name = Some(name.to_string());
187        self
188    }
189
190    /// Add a match guard to this web service.
191    ///
192    /// The service is selected only when its path and all registered guards
193    /// match. If a guard rejects the request, the router can try another
194    /// matching service; otherwise the containing scope or application fallback
195    /// is used.
196    ///
197    /// ```rust
198    /// use std::convert::Infallible;
199    /// use ntex::web::{self, guard, App, HttpResponse};
200    ///
201    /// async fn index(
202    ///     req: web::WebRequest<()>,
203    /// ) -> Result<web::WebResponse, Infallible> {
204    ///     Ok(req.into_response(HttpResponse::Ok().build()))
205    /// }
206    ///
207    /// App::default().service(
208    ///     web::service("/health")
209    ///         .guard(guard::Get())
210    ///         .guard(guard::Header("x-health-check", "true"))
211    ///         .build(index)
212    /// );
213    /// ```
214    #[must_use]
215    pub fn guard<G: Guard + 'static>(mut self, guard: G) -> Self {
216        self.guards.add(guard);
217        self
218    }
219
220    /// Add a supported method to this service.
221    ///
222    /// Repeated calls allow any of the registered methods. If this method is
223    /// never called, no method check is added and existing guard and service
224    /// behavior is unchanged.
225    ///
226    /// Methods are checked after the path and all guards match, but before the
227    /// service is called. An unsupported method returns `405 Method Not Allowed`
228    /// with an `Allow` header; the router does not try another service or fallback.
229    /// Use a method guard instead when a mismatch should continue routing.
230    ///
231    /// ```rust
232    /// use std::convert::Infallible;
233    /// use ntex::http::Method;
234    /// use ntex::web::{self, guard, App, HttpResponse};
235    ///
236    /// async fn index(
237    ///     req: web::WebRequest<()>,
238    /// ) -> Result<web::WebResponse, Infallible> {
239    ///     Ok(req.into_response(HttpResponse::Ok().build()))
240    /// }
241    ///
242    /// App::default().service(
243    ///     web::service("/health")
244    ///         .method(Method::GET)
245    ///         .guard(guard::Header("x-health-check", "true"))
246    ///         .build(index)
247    /// );
248    /// ```
249    #[must_use]
250    pub fn method(mut self, method: Method) -> Self {
251        self.methods.insert(method);
252        self
253    }
254
255    /// Set a service factory implementation and generate web service.
256    pub fn build<Sf, St, In, F>(self, service: F) -> impl WebServiceFactory<St, In>
257    where
258        St: State,
259        In: 'static,
260        F: IntoServiceFactory<Sf, St, WebRequest<In>>,
261        Sf: ServiceFactory<St, WebRequest<In>, Res = WebResponse> + 'static,
262        Sf::Error: WebResponseError<St, St::Error>,
263        Sf::InitError: IntoFailure,
264    {
265        WebServiceImpl {
266            srv: service
267                .into_factory()
268                .map_err(WebError::from_err)
269                .map_init_err(IntoFailure::fail),
270            rdef: self.rdef,
271            name: self.name,
272            guards: self.guards,
273            methods: self.methods,
274            ph: PhantomData,
275        }
276    }
277}
278
279struct WebServiceImpl<Sf, In> {
280    srv: Sf,
281    rdef: Vec<String>,
282    name: Option<String>,
283    guards: AllGuard,
284    methods: HashSet<Method>,
285    ph: PhantomData<In>,
286}
287
288impl<Sf, In, St> WebServiceFactory<St, In> for WebServiceImpl<Sf, In>
289where
290    St: State,
291    In: 'static,
292    Sf: ServiceFactory<
293            St,
294            WebRequest<In>,
295            Res = WebResponse,
296            Error = WebError<St, St::Error>,
297            InitError = Failure,
298        > + 'static,
299{
300    fn register(mut self, config: &mut WebServiceConfig<St, In>) {
301        let guards = if self.guards.0.is_empty() {
302            None
303        } else {
304            Some(std::mem::take(&mut self.guards.0))
305        };
306
307        let mut rdef = if config.is_root() || !self.rdef.is_empty() {
308            ResourceDef::new(insert_slash(self.rdef))
309        } else {
310            ResourceDef::new(self.rdef)
311        };
312        if let Some(name) = self.name {
313            rdef.set_name(name);
314        }
315        if self.methods.is_empty() {
316            config.register_service(rdef, guards, None, self.srv);
317        } else {
318            let mut allow: Vec<_> = self.methods.iter().map(Method::as_str).collect();
319            allow.sort_unstable();
320            let allow = allow.join(", ");
321            let methods = Rc::new(self.methods);
322
323            let service = crate::factory(async move |req: WebRequest<In>| {
324                if methods.contains(&req.head().method) {
325                    Ok(req)
326                } else {
327                    Err(WebError::from_err(InternalError::from_response(
328                        "Method not allowed",
329                        Response::MethodNotAllowed()
330                            .header(header::ALLOW, allow.as_str())
331                            .build(),
332                    )))
333                }
334            })
335            .map_init_err(|_| unreachable!())
336            .and_then(self.srv);
337
338            config.register_service(rdef, guards, None, service);
339        }
340    }
341}
342
343#[allow(unused_parens)]
344impl<T, St, In> WebServiceFactory<St, In> for Vec<T>
345where
346    T: WebServiceFactory<St, In> + 'static,
347    St: State,
348{
349    fn register(mut self, config: &mut WebServiceConfig<St, In>) {
350        for service in self.drain(..) {
351            service.register(config);
352        }
353    }
354}
355
356macro_rules! tuple_web_service(
357    {$(#[$meta:meta])* $(($n:tt, $T:ident)),+} => {
358
359        $(#[$meta])*
360        impl<St: State, In, $($T: WebServiceFactory<St, In> + 'static),+> WebServiceFactory<St, In> for ($($T,)+) {
361            fn register(self, config: &mut WebServiceConfig<St, In>) {
362                $(
363                    self.$n.register(config);
364                )+
365            }
366        }
367    }
368);
369
370impl<St, In, T, const N: usize> WebServiceFactory<St, In> for [T; N]
371where
372    St: State,
373    T: WebServiceFactory<St, In> + 'static,
374{
375    fn register(self, config: &mut WebServiceConfig<St, In>) {
376        for t in self {
377            t.register(config);
378        }
379    }
380}
381
382#[allow(non_snake_case, clippy::wildcard_imports)]
383#[rustfmt::skip]
384mod m {
385    use super::*;
386    use variadics_please::all_tuples_enumerated;
387
388    all_tuples_enumerated!(#[doc(fake_variadic)] tuple_web_service, 1, 24, T);
389}
390
391#[cfg(test)]
392mod tests {
393    use std::convert::Infallible;
394
395    use super::*;
396    use crate::http::header::ALLOW;
397    use crate::http::{Method, StatusCode};
398    use crate::web::test::{TestRequest, init_service};
399    use crate::web::{self, App, DefaultError, HttpResponse, guard};
400
401    /// STATEMENT: Raw web services handle matching paths and allow guards to reject requests.
402    ///
403    /// HOW:
404    /// - Register a named raw service and assert `/test` returns OK.
405    /// - Add a GET guard and assert a PUT request returns 404.
406    #[crate::rt_test]
407    async fn test_service() {
408        let srv = init_service(App::new().service(web::service("/test").name("test").build(
409            async move |req: WebRequest<()>| {
410                Ok::<_, Infallible>(req.into_response(HttpResponse::Ok().build()))
411            },
412        )))
413        .await;
414        let req = TestRequest::with_uri("/test").to_request();
415        let resp = srv.call(req).await.unwrap();
416        assert_eq!(resp.status(), StatusCode::OK);
417
418        let srv = init_service(
419            App::new().service(web::service("/test").guard(guard::Get()).build(
420                async move |req: WebRequest<()>| {
421                    Ok::<_, DefaultError>(req.into_response(HttpResponse::Ok().build()))
422                },
423            )),
424        )
425        .await;
426        let req = TestRequest::with_uri("/test")
427            .method(Method::PUT)
428            .to_request();
429        let resp = srv.call(req).await.unwrap();
430        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
431    }
432
433    /// STATEMENT: Service method restrictions return 405 with deduplicated `Allow` values only on path hits.
434    ///
435    /// HOW:
436    /// - Exercise restricted and unrestricted services at root and scoped prefixes with several methods.
437    /// - Assert unsupported restricted methods return 405 and `Allow: GET, POST`; others return OK without it.
438    /// - Assert missing paths remain 404.
439    #[crate::rt_test]
440    async fn test_service_methods() {
441        for (prefix, restricted) in [("", false), ("", true), ("/app", false), ("/app", true)] {
442            let mut service = web::service("/test");
443            if restricted {
444                service = service
445                    .method(Method::GET)
446                    .method(Method::POST)
447                    .method(Method::GET);
448            }
449            let service = service.build(async |req: WebRequest<()>| {
450                Ok::<_, Infallible>(req.into_response(HttpResponse::Ok().build()))
451            });
452            let app = App::new();
453            let app = if prefix.is_empty() {
454                app.service(service)
455            } else {
456                app.service(web::scope(prefix).service(service))
457            };
458            let srv = init_service(app).await;
459
460            for (method, supported) in [
461                (Method::GET, true),
462                (Method::POST, true),
463                (Method::PUT, false),
464                (Method::HEAD, false),
465                (Method::from_bytes(b"PROPFIND").unwrap(), false),
466            ] {
467                let rejected = restricted && !supported;
468                let resp = srv
469                    .call(
470                        TestRequest::with_uri(&format!("{prefix}/test"))
471                            .method(method)
472                            .to_request(),
473                    )
474                    .await
475                    .unwrap();
476                assert_eq!(
477                    resp.status(),
478                    if rejected {
479                        StatusCode::METHOD_NOT_ALLOWED
480                    } else {
481                        StatusCode::OK
482                    },
483                    "prefix={prefix:?}, restricted={restricted}, supported={supported}",
484                );
485                if rejected {
486                    assert_eq!(resp.headers().get(ALLOW).unwrap(), "GET, POST");
487                } else {
488                    assert!(!resp.headers().contains_key(ALLOW));
489                }
490            }
491
492            let resp = srv
493                .call(
494                    TestRequest::with_uri(&format!("{prefix}/missing"))
495                        .method(Method::PUT)
496                        .to_request(),
497                )
498                .await
499                .unwrap();
500            assert_eq!(resp.status(), StatusCode::NOT_FOUND);
501        }
502    }
503
504    /// STATEMENT: Service guards select the service before its method restrictions are applied.
505    ///
506    /// HOW:
507    /// - Register a header-guarded GET service before an unrestricted service at the same path.
508    /// - Send PUT without and with the header and assert 201 versus 405 with `Allow: GET`.
509    /// - Assert a missing path reaches the application's 202 default service.
510    #[crate::rt_test]
511    async fn test_service_methods_and_guards() {
512        let srv = init_service(
513            App::new()
514                .service(
515                    web::service("/test")
516                        .method(Method::GET)
517                        .guard(guard::Header("x-service", "selected"))
518                        .build(async |req: WebRequest<()>| {
519                            Ok::<_, Infallible>(req.into_response(HttpResponse::Ok().build()))
520                        }),
521                )
522                .service(web::service("/test").build(async |req: WebRequest<()>| {
523                    Ok::<_, Infallible>(req.into_response(HttpResponse::Created().build()))
524                }))
525                .default_service(web::to(async || HttpResponse::Accepted())),
526        )
527        .await;
528
529        let resp = srv
530            .call(
531                TestRequest::with_uri("/test")
532                    .method(Method::PUT)
533                    .to_request(),
534            )
535            .await
536            .unwrap();
537        assert_eq!(resp.status(), StatusCode::CREATED);
538
539        let resp = srv
540            .call(
541                TestRequest::with_uri("/test")
542                    .method(Method::PUT)
543                    .header("x-service", "selected")
544                    .to_request(),
545            )
546            .await
547            .unwrap();
548        assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
549        assert_eq!(resp.headers().get(ALLOW).unwrap(), "GET");
550
551        let resp = srv
552            .call(TestRequest::with_uri("/missing").to_request())
553            .await
554            .unwrap();
555        assert_eq!(resp.status(), StatusCode::ACCEPTED);
556    }
557
558    /// STATEMENT: Arrays, tuples, and vectors register every contained web service.
559    ///
560    /// HOW:
561    /// - Initialize separate applications with two resources registered through each collection type.
562    /// - Request both paths in each application and assert OK.
563    #[crate::rt_test]
564    async fn test_multi() {
565        let srv = init_service(App::new().service([
566            web::resource("/test1").to(async || HttpResponse::Ok()),
567            web::resource("/test2").to(async || HttpResponse::Ok()),
568        ]))
569        .await;
570        let req = TestRequest::with_uri("/test1").to_request();
571        let resp = srv.call(req).await.unwrap();
572        assert_eq!(resp.status(), StatusCode::OK);
573        let req = TestRequest::with_uri("/test2").to_request();
574        let resp = srv.call(req).await.unwrap();
575        assert_eq!(resp.status(), StatusCode::OK);
576
577        let srv = init_service(App::new().service((
578            web::resource("/test1").to(async || HttpResponse::Ok()),
579            web::resource("/test2").to(async || HttpResponse::Ok()),
580        )))
581        .await;
582        let req = TestRequest::with_uri("/test1").to_request();
583        let resp = srv.call(req).await.unwrap();
584        assert_eq!(resp.status(), StatusCode::OK);
585        let req = TestRequest::with_uri("/test2").to_request();
586        let resp = srv.call(req).await.unwrap();
587        assert_eq!(resp.status(), StatusCode::OK);
588
589        let srv = init_service(App::new().service(vec![
590            web::resource("/test1").to(async || HttpResponse::Ok()),
591            web::resource("/test2").to(async || HttpResponse::Ok()),
592        ]))
593        .await;
594        let req = TestRequest::with_uri("/test1").to_request();
595        let resp = srv.call(req).await.unwrap();
596        assert_eq!(resp.status(), StatusCode::OK);
597        let req = TestRequest::with_uri("/test2").to_request();
598        let resp = srv.call(req).await.unwrap();
599        assert_eq!(resp.status(), StatusCode::OK);
600    }
601
602    /// STATEMENT: Web request and response debug output includes identifying metadata and headers.
603    ///
604    /// HOW:
605    /// - Format a request carrying a query and `x-test` header and assert all appear with its type name.
606    /// - Format a response carrying `x-test` and assert its type name and header appear.
607    #[test]
608    fn test_fmt_debug() {
609        let req = TestRequest::get()
610            .uri("/index.html?test=1")
611            .header("x-test", "111")
612            .to_srv_request();
613        let s = format!("{req:?}");
614        assert!(s.contains("WebRequest"));
615        assert!(s.contains("test=1"));
616        assert!(s.contains("x-test"));
617
618        let res = HttpResponse::Ok().header("x-test", "111").build();
619        let res = TestRequest::post()
620            .uri("/index.html?test=1")
621            .to_srv_response(res);
622
623        let s = format!("{res:?}");
624        assert!(s.contains("WebResponse"));
625        assert!(s.contains("x-test"));
626    }
627
628    /// STATEMENT: An empty raw-service path matches only the exact root of its enclosing scope.
629    ///
630    /// HOW:
631    /// - Mount an empty service under `/app`.
632    /// - Assert `/app` returns OK and `/app/` returns 404.
633    #[crate::rt_test]
634    async fn test_service_empty_path_in_scope() {
635        let srv = init_service(App::new().service(web::scope("/app").service(
636            web::service("").build(async move |req: WebRequest<()>| {
637                Ok::<_, Infallible>(req.into_response(HttpResponse::Ok().build()))
638            }),
639        )))
640        .await;
641        let req = TestRequest::with_uri("/app").to_request();
642        let resp = srv.call(req).await.unwrap();
643        assert_eq!(resp.status(), StatusCode::OK);
644
645        let req = TestRequest::with_uri("/app/").to_request();
646        let resp = srv.call(req).await.unwrap();
647        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
648    }
649}