ntex 4.6.0

Framework for composable network services
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
use std::{marker::PhantomData, rc::Rc};

use ntex_http::Method;
use ntex_util::HashSet;

use crate::error::{Failure, IntoFailure};
use crate::http::{Response, header};
use crate::router::{IntoPattern, ResourceDef};
use crate::service::{IntoServiceFactory, ServiceFactory, boxed};

use super::error::{InternalError, WebError, WebResponseError};
use super::guard::{AllGuard, Guard};
use super::{HttpService, State, WebRequest, WebResponse, dev::insert_slash, rmap::ResourceMap};

/// Factory of web services that can be registered with an application or scope.
///
/// `App::service()` and `Scope::service()` accept any `WebServiceFactory`.
/// It is implemented by [`Resource`](crate::web::Resource),
/// [`Scope`](crate::web::Scope), services generated by the route attribute
/// macros, and services built with `web::service()`.
pub trait WebServiceFactory<St: State, In>: 'static {
    /// Register the service, its path, and its guards in `config`.
    fn register(self, config: &mut WebServiceConfig<St, In>);
}

pub(super) trait AppServiceFactory<St: State, In> {
    fn register(&mut self, config: &mut WebServiceConfig<St, In>);
}

pub(super) struct ServiceFactoryWrapper<T> {
    factory: Option<T>,
}

impl<T> ServiceFactoryWrapper<T> {
    pub(super) fn new(factory: T) -> Self {
        Self {
            factory: Some(factory),
        }
    }
}

impl<T, St, In> AppServiceFactory<St, In> for ServiceFactoryWrapper<T>
where
    T: WebServiceFactory<St, In>,
    St: State,
{
    fn register(&mut self, config: &mut WebServiceConfig<St, In>) {
        if let Some(item) = self.factory.take() {
            item.register(config);
        }
    }
}

type Guards = Vec<Box<dyn Guard>>;

/// Application service configuration
#[derive(derive_more::Debug)]
#[debug("WebServiceConfig")]
pub struct WebServiceConfig<St: State, In = ()> {
    root: bool,
    services: Vec<(
        ResourceDef,
        HttpService<St, In>,
        Option<Guards>,
        Option<Rc<ResourceMap>>,
    )>,
}

impl<St: State, In: 'static> WebServiceConfig<St, In> {
    /// Create server settings instance
    pub(crate) fn new() -> Self {
        WebServiceConfig {
            root: true,
            services: Vec::new(),
        }
    }

    /// Check if root is being configured
    pub fn is_root(&self) -> bool {
        self.root
    }

    pub(crate) fn into_services(
        self,
    ) -> Vec<(
        ResourceDef,
        HttpService<St, In>,
        Option<Guards>,
        Option<Rc<ResourceMap>>,
    )> {
        self.services
    }

    /// Register http service
    pub fn register_service<S>(
        &mut self,
        rdef: ResourceDef,
        guards: Option<Vec<Box<dyn Guard>>>,
        nested: Option<Rc<ResourceMap>>,
        factory: impl IntoServiceFactory<S, St, WebRequest<In>>,
    ) where
        S: ServiceFactory<
                St,
                WebRequest<In>,
                Res = WebResponse,
                Error = WebError<St, St::Error>,
                InitError = Failure,
            > + 'static,
    {
        self.services
            .push((rdef, boxed::factory(factory.into_factory()), guards, nested));
    }
}

/// Create service adapter for a specific path.
///
/// ```rust
/// use std::convert::Infallible;
/// use ntex::web::{self, guard, App, HttpResponse};
///
/// async fn my_service(req: web::WebRequest<()>) -> Result<web::WebResponse, Infallible> {
///     Ok(req.into_response(HttpResponse::Ok().build()))
/// }
///
/// let app = App::default().service(
///     web::service("/users/*")
///         .guard(guard::Header("content-type", "text/plain"))
///         .build(my_service)
/// );
/// ```
#[derive(Debug)]
pub struct WebServiceAdapter {
    rdef: Vec<String>,
    name: Option<String>,
    guards: AllGuard,
    methods: HashSet<Method>,
}

impl WebServiceAdapter {
    #[must_use]
    #[allow(clippy::needless_pass_by_value)]
    /// Create new `WebServiceAdapter` instance.
    pub fn new<T: IntoPattern>(path: T) -> Self {
        WebServiceAdapter {
            rdef: path.patterns(),
            name: None,
            guards: AllGuard::default(),
            methods: HashSet::default(),
        }
    }

    /// Set service name.
    ///
    /// Name is used for url generation.
    #[must_use]
    pub fn name(mut self, name: &str) -> Self {
        self.name = Some(name.to_string());
        self
    }

    /// Add a match guard to this web service.
    ///
    /// The service is selected only when its path and all registered guards
    /// match. If a guard rejects the request, the router can try another
    /// matching service; otherwise the containing scope or application fallback
    /// is used.
    ///
    /// ```rust
    /// use std::convert::Infallible;
    /// use ntex::web::{self, guard, App, HttpResponse};
    ///
    /// async fn index(
    ///     req: web::WebRequest<()>,
    /// ) -> Result<web::WebResponse, Infallible> {
    ///     Ok(req.into_response(HttpResponse::Ok().build()))
    /// }
    ///
    /// App::default().service(
    ///     web::service("/health")
    ///         .guard(guard::Get())
    ///         .guard(guard::Header("x-health-check", "true"))
    ///         .build(index)
    /// );
    /// ```
    #[must_use]
    pub fn guard<G: Guard + 'static>(mut self, guard: G) -> Self {
        self.guards.add(guard);
        self
    }

    /// Add a supported method to this service.
    ///
    /// Repeated calls allow any of the registered methods. If this method is
    /// never called, no method check is added and existing guard and service
    /// behavior is unchanged.
    ///
    /// Methods are checked after the path and all guards match, but before the
    /// service is called. An unsupported method returns `405 Method Not Allowed`
    /// with an `Allow` header; the router does not try another service or fallback.
    /// Use a method guard instead when a mismatch should continue routing.
    ///
    /// ```rust
    /// use std::convert::Infallible;
    /// use ntex::http::Method;
    /// use ntex::web::{self, guard, App, HttpResponse};
    ///
    /// async fn index(
    ///     req: web::WebRequest<()>,
    /// ) -> Result<web::WebResponse, Infallible> {
    ///     Ok(req.into_response(HttpResponse::Ok().build()))
    /// }
    ///
    /// App::default().service(
    ///     web::service("/health")
    ///         .method(Method::GET)
    ///         .guard(guard::Header("x-health-check", "true"))
    ///         .build(index)
    /// );
    /// ```
    #[must_use]
    pub fn method(mut self, method: Method) -> Self {
        self.methods.insert(method);
        self
    }

    /// Set a service factory implementation and generate web service.
    pub fn build<Sf, St, In, F>(self, service: F) -> impl WebServiceFactory<St, In>
    where
        St: State,
        In: 'static,
        F: IntoServiceFactory<Sf, St, WebRequest<In>>,
        Sf: ServiceFactory<St, WebRequest<In>, Res = WebResponse> + 'static,
        Sf::Error: WebResponseError<St, St::Error>,
        Sf::InitError: IntoFailure,
    {
        WebServiceImpl {
            srv: service
                .into_factory()
                .map_err(WebError::from_err)
                .map_init_err(IntoFailure::fail),
            rdef: self.rdef,
            name: self.name,
            guards: self.guards,
            methods: self.methods,
            ph: PhantomData,
        }
    }
}

struct WebServiceImpl<Sf, In> {
    srv: Sf,
    rdef: Vec<String>,
    name: Option<String>,
    guards: AllGuard,
    methods: HashSet<Method>,
    ph: PhantomData<In>,
}

impl<Sf, In, St> WebServiceFactory<St, In> for WebServiceImpl<Sf, In>
where
    St: State,
    In: 'static,
    Sf: ServiceFactory<
            St,
            WebRequest<In>,
            Res = WebResponse,
            Error = WebError<St, St::Error>,
            InitError = Failure,
        > + 'static,
{
    fn register(mut self, config: &mut WebServiceConfig<St, In>) {
        let guards = if self.guards.0.is_empty() {
            None
        } else {
            Some(std::mem::take(&mut self.guards.0))
        };

        let mut rdef = if config.is_root() || !self.rdef.is_empty() {
            ResourceDef::new(insert_slash(self.rdef))
        } else {
            ResourceDef::new(self.rdef)
        };
        if let Some(name) = self.name {
            rdef.set_name(name);
        }
        if self.methods.is_empty() {
            config.register_service(rdef, guards, None, self.srv);
        } else {
            let mut allow: Vec<_> = self.methods.iter().map(Method::as_str).collect();
            allow.sort_unstable();
            let allow = allow.join(", ");
            let methods = Rc::new(self.methods);

            let service = crate::factory(async move |req: WebRequest<In>| {
                if methods.contains(&req.head().method) {
                    Ok(req)
                } else {
                    Err(WebError::from_err(InternalError::from_response(
                        "Method not allowed",
                        Response::MethodNotAllowed()
                            .header(header::ALLOW, allow.as_str())
                            .build(),
                    )))
                }
            })
            .map_init_err(|_| unreachable!())
            .and_then(self.srv);

            config.register_service(rdef, guards, None, service);
        }
    }
}

#[allow(unused_parens)]
impl<T, St, In> WebServiceFactory<St, In> for Vec<T>
where
    T: WebServiceFactory<St, In> + 'static,
    St: State,
{
    fn register(mut self, config: &mut WebServiceConfig<St, In>) {
        for service in self.drain(..) {
            service.register(config);
        }
    }
}

macro_rules! tuple_web_service(
    {$(#[$meta:meta])* $(($n:tt, $T:ident)),+} => {

        $(#[$meta])*
        impl<St: State, In, $($T: WebServiceFactory<St, In> + 'static),+> WebServiceFactory<St, In> for ($($T,)+) {
            fn register(self, config: &mut WebServiceConfig<St, In>) {
                $(
                    self.$n.register(config);
                )+
            }
        }
    }
);

impl<St, In, T, const N: usize> WebServiceFactory<St, In> for [T; N]
where
    St: State,
    T: WebServiceFactory<St, In> + 'static,
{
    fn register(self, config: &mut WebServiceConfig<St, In>) {
        for t in self {
            t.register(config);
        }
    }
}

#[allow(non_snake_case, clippy::wildcard_imports)]
#[rustfmt::skip]
mod m {
    use super::*;
    use variadics_please::all_tuples_enumerated;

    all_tuples_enumerated!(#[doc(fake_variadic)] tuple_web_service, 1, 24, T);
}

#[cfg(test)]
mod tests {
    use std::convert::Infallible;

    use super::*;
    use crate::http::header::ALLOW;
    use crate::http::{Method, StatusCode};
    use crate::web::test::{TestRequest, init_service};
    use crate::web::{self, App, DefaultError, HttpResponse, guard};

    /// STATEMENT: Raw web services handle matching paths and allow guards to reject requests.
    ///
    /// HOW:
    /// - Register a named raw service and assert `/test` returns OK.
    /// - Add a GET guard and assert a PUT request returns 404.
    #[crate::rt_test]
    async fn test_service() {
        let srv = init_service(App::new().service(web::service("/test").name("test").build(
            async move |req: WebRequest<()>| {
                Ok::<_, Infallible>(req.into_response(HttpResponse::Ok().build()))
            },
        )))
        .await;
        let req = TestRequest::with_uri("/test").to_request();
        let resp = srv.call(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let srv = init_service(
            App::new().service(web::service("/test").guard(guard::Get()).build(
                async move |req: WebRequest<()>| {
                    Ok::<_, DefaultError>(req.into_response(HttpResponse::Ok().build()))
                },
            )),
        )
        .await;
        let req = TestRequest::with_uri("/test")
            .method(Method::PUT)
            .to_request();
        let resp = srv.call(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    /// STATEMENT: Service method restrictions return 405 with deduplicated `Allow` values only on path hits.
    ///
    /// HOW:
    /// - Exercise restricted and unrestricted services at root and scoped prefixes with several methods.
    /// - Assert unsupported restricted methods return 405 and `Allow: GET, POST`; others return OK without it.
    /// - Assert missing paths remain 404.
    #[crate::rt_test]
    async fn test_service_methods() {
        for (prefix, restricted) in [("", false), ("", true), ("/app", false), ("/app", true)] {
            let mut service = web::service("/test");
            if restricted {
                service = service
                    .method(Method::GET)
                    .method(Method::POST)
                    .method(Method::GET);
            }
            let service = service.build(async |req: WebRequest<()>| {
                Ok::<_, Infallible>(req.into_response(HttpResponse::Ok().build()))
            });
            let app = App::new();
            let app = if prefix.is_empty() {
                app.service(service)
            } else {
                app.service(web::scope(prefix).service(service))
            };
            let srv = init_service(app).await;

            for (method, supported) in [
                (Method::GET, true),
                (Method::POST, true),
                (Method::PUT, false),
                (Method::HEAD, false),
                (Method::from_bytes(b"PROPFIND").unwrap(), false),
            ] {
                let rejected = restricted && !supported;
                let resp = srv
                    .call(
                        TestRequest::with_uri(&format!("{prefix}/test"))
                            .method(method)
                            .to_request(),
                    )
                    .await
                    .unwrap();
                assert_eq!(
                    resp.status(),
                    if rejected {
                        StatusCode::METHOD_NOT_ALLOWED
                    } else {
                        StatusCode::OK
                    },
                    "prefix={prefix:?}, restricted={restricted}, supported={supported}",
                );
                if rejected {
                    assert_eq!(resp.headers().get(ALLOW).unwrap(), "GET, POST");
                } else {
                    assert!(!resp.headers().contains_key(ALLOW));
                }
            }

            let resp = srv
                .call(
                    TestRequest::with_uri(&format!("{prefix}/missing"))
                        .method(Method::PUT)
                        .to_request(),
                )
                .await
                .unwrap();
            assert_eq!(resp.status(), StatusCode::NOT_FOUND);
        }
    }

    /// STATEMENT: Service guards select the service before its method restrictions are applied.
    ///
    /// HOW:
    /// - Register a header-guarded GET service before an unrestricted service at the same path.
    /// - Send PUT without and with the header and assert 201 versus 405 with `Allow: GET`.
    /// - Assert a missing path reaches the application's 202 default service.
    #[crate::rt_test]
    async fn test_service_methods_and_guards() {
        let srv = init_service(
            App::new()
                .service(
                    web::service("/test")
                        .method(Method::GET)
                        .guard(guard::Header("x-service", "selected"))
                        .build(async |req: WebRequest<()>| {
                            Ok::<_, Infallible>(req.into_response(HttpResponse::Ok().build()))
                        }),
                )
                .service(web::service("/test").build(async |req: WebRequest<()>| {
                    Ok::<_, Infallible>(req.into_response(HttpResponse::Created().build()))
                }))
                .default_service(web::to(async || HttpResponse::Accepted())),
        )
        .await;

        let resp = srv
            .call(
                TestRequest::with_uri("/test")
                    .method(Method::PUT)
                    .to_request(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::CREATED);

        let resp = srv
            .call(
                TestRequest::with_uri("/test")
                    .method(Method::PUT)
                    .header("x-service", "selected")
                    .to_request(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
        assert_eq!(resp.headers().get(ALLOW).unwrap(), "GET");

        let resp = srv
            .call(TestRequest::with_uri("/missing").to_request())
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::ACCEPTED);
    }

    /// STATEMENT: Arrays, tuples, and vectors register every contained web service.
    ///
    /// HOW:
    /// - Initialize separate applications with two resources registered through each collection type.
    /// - Request both paths in each application and assert OK.
    #[crate::rt_test]
    async fn test_multi() {
        let srv = init_service(App::new().service([
            web::resource("/test1").to(async || HttpResponse::Ok()),
            web::resource("/test2").to(async || HttpResponse::Ok()),
        ]))
        .await;
        let req = TestRequest::with_uri("/test1").to_request();
        let resp = srv.call(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let req = TestRequest::with_uri("/test2").to_request();
        let resp = srv.call(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let srv = init_service(App::new().service((
            web::resource("/test1").to(async || HttpResponse::Ok()),
            web::resource("/test2").to(async || HttpResponse::Ok()),
        )))
        .await;
        let req = TestRequest::with_uri("/test1").to_request();
        let resp = srv.call(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let req = TestRequest::with_uri("/test2").to_request();
        let resp = srv.call(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let srv = init_service(App::new().service(vec![
            web::resource("/test1").to(async || HttpResponse::Ok()),
            web::resource("/test2").to(async || HttpResponse::Ok()),
        ]))
        .await;
        let req = TestRequest::with_uri("/test1").to_request();
        let resp = srv.call(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let req = TestRequest::with_uri("/test2").to_request();
        let resp = srv.call(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
    }

    /// STATEMENT: Web request and response debug output includes identifying metadata and headers.
    ///
    /// HOW:
    /// - Format a request carrying a query and `x-test` header and assert all appear with its type name.
    /// - Format a response carrying `x-test` and assert its type name and header appear.
    #[test]
    fn test_fmt_debug() {
        let req = TestRequest::get()
            .uri("/index.html?test=1")
            .header("x-test", "111")
            .to_srv_request();
        let s = format!("{req:?}");
        assert!(s.contains("WebRequest"));
        assert!(s.contains("test=1"));
        assert!(s.contains("x-test"));

        let res = HttpResponse::Ok().header("x-test", "111").build();
        let res = TestRequest::post()
            .uri("/index.html?test=1")
            .to_srv_response(res);

        let s = format!("{res:?}");
        assert!(s.contains("WebResponse"));
        assert!(s.contains("x-test"));
    }

    /// STATEMENT: An empty raw-service path matches only the exact root of its enclosing scope.
    ///
    /// HOW:
    /// - Mount an empty service under `/app`.
    /// - Assert `/app` returns OK and `/app/` returns 404.
    #[crate::rt_test]
    async fn test_service_empty_path_in_scope() {
        let srv = init_service(App::new().service(web::scope("/app").service(
            web::service("").build(async move |req: WebRequest<()>| {
                Ok::<_, Infallible>(req.into_response(HttpResponse::Ok().build()))
            }),
        )))
        .await;
        let req = TestRequest::with_uri("/app").to_request();
        let resp = srv.call(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let req = TestRequest::with_uri("/app/").to_request();
        let resp = srv.call(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }
}