Skip to main content

ntex/web/
resource.rs

1use std::{any::Any, any::TypeId, marker::PhantomData};
2
3use crate::error::{Failure, IntoFailure};
4use crate::http::Response;
5use crate::router::{IntoPattern, ResourceDef};
6use crate::service::{Identity, ReadyBinding, ServiceChainFactory};
7use crate::{Ctx, IntoServiceFactory, Middleware, Service, ServiceFactory, factory};
8
9use super::dev::{WebServiceConfig, WebServiceFactory, insert_slash};
10use super::error::{WebError, WebResponseError};
11use super::guard::Guard;
12use super::route::{IntoRoutes, Route, RouteService};
13use super::stack::{Filter, WebStack, passthrough};
14use super::{
15    FromRequest, Handler, HandlerSt, HttpHandler, HttpService, State, WebRequest, WebResponse,
16};
17
18/// Groups routes and configuration for one or more URL patterns.
19///
20/// A resource is useful when several routes belong to the same path. Along
21/// with those routes, it can have its own guards, filters, middleware, name,
22/// and fallback service. Create one with [`web::resource()`], then register it
23/// with [`App::service()`] or [`Scope::service()`].
24///
25/// For each request, the router first checks the resource's path and guards.
26/// If they do not match, it keeps looking for another resource or scope. Once
27/// this resource is selected, its middleware and filters run, followed by its
28/// routes in registration order. The first route whose guards all pass handles
29/// the request.
30///
31/// When none of the routes match, the resource uses its own fallback. By
32/// default, that fallback returns `405 Method Not Allowed`.
33///
34/// Use [`Resource::route()`] to add guarded routes, or [`Resource::to()`] to
35/// add an unguarded handler that accepts any request reaching the resource.
36///
37/// ```rust
38/// use ntex::web::{self, App, HttpResponse};
39///
40/// App::default().service(
41///     web::resource("/users")
42///         .route(web::get().to(async || "users"))
43///         .route(web::post().to(async || HttpResponse::Created()))
44///         .default_service(web::to(async || {
45///             HttpResponse::MethodNotAllowed().body("Use GET or POST")
46///         })),
47/// );
48/// ```
49///
50/// [`App::service()`]: super::App::service
51/// [`Scope::service()`]: super::Scope::service
52/// [`web::resource()`]: super::resource
53#[derive(derive_more::Debug)]
54#[debug("Resource({rdef:?})")]
55pub struct Resource<St: State, In, Out = In, M = Identity, F = Filter<St, In>> {
56    middleware: M,
57    filter: ServiceChainFactory<F, St, WebRequest<In>>,
58    rdef: Vec<String>,
59    name: Option<String>,
60    guards: Vec<Box<dyn Guard>>,
61    ph: PhantomData<Out>,
62}
63
64/// A resource with routes or a configured fallback.
65///
66/// From here, you can add more routes or handlers and change the resource
67/// fallback. Configure resource-wide settings such as its name, guards,
68/// filters, and middleware before adding the first route or fallback.
69///
70/// The finished builder can be registered with [`App::service()`] or
71/// [`Scope::service()`]. It keeps the path and all configuration from the
72/// original [`Resource`].
73///
74/// [`App::service()`]: super::App::service
75/// [`Scope::service()`]: super::Scope::service
76#[derive(derive_more::Debug)]
77#[debug("ResourceServices({rdef:?})")]
78pub struct ResourceServices<St: State, In, Out, M, F> {
79    middleware: M,
80    filter: ServiceChainFactory<F, St, WebRequest<In>>,
81    rdef: Vec<String>,
82    name: Option<String>,
83    guards: Vec<Box<dyn Guard>>,
84    routes: Vec<Route<St, Out>>,
85    default: Option<HttpService<St, Out>>,
86}
87
88impl<St: State, In: 'static> Resource<St, In, In> {
89    #[allow(clippy::needless_pass_by_value)]
90    /// Create a resource for the given path pattern or patterns.
91    ///
92    /// Same as [`web::resource()`](crate::web::resource).
93    pub fn new<T: IntoPattern>(path: T) -> Resource<St, In, In> {
94        Resource {
95            rdef: path.patterns(),
96            name: None,
97            middleware: Identity,
98            filter: factory(Filter::new()),
99            guards: Vec::new(),
100            ph: PhantomData,
101        }
102    }
103}
104
105impl<St, In, Out, M, F> Resource<St, In, Out, M, F>
106where
107    St: State,
108    In: 'static,
109    Out: 'static,
110    F: ServiceFactory<
111            St,
112            WebRequest<In>,
113            Res = WebRequest<Out>,
114            Error = WebError<St, St::Error>,
115            InitError = Failure,
116        >,
117{
118    /// Set resource name.
119    ///
120    /// Name is used for url generation, it must be unique within the
121    /// enclosing scope or application, which panics on start otherwise.
122    #[must_use]
123    pub fn name(mut self, name: &str) -> Self {
124        self.name = Some(name.to_string());
125        self
126    }
127
128    /// Add a match guard to this resource.
129    ///
130    /// The resource is selected only when its path and all registered guards
131    /// match. If a guard rejects the request, the router can try another
132    /// resource with the same path; otherwise the containing scope or
133    /// application fallback is used.
134    ///
135    /// Resource guards run before route selection. Use [`Route::guard()`] when
136    /// the condition should choose between routes inside one resource.
137    ///
138    /// ```rust
139    /// use ntex::web::{self, guard, App};
140    ///
141    /// App::default()
142    ///     .service(
143    ///         web::resource("/items")
144    ///             .guard(guard::Header("accept", "application/json"))
145    ///             .to(async || "JSON items")
146    ///     )
147    ///     .service(
148    ///         web::resource("/items")
149    ///             .guard(guard::Header("accept", "text/plain"))
150    ///             .to(async || "Text items")
151    ///     );
152    /// ```
153    #[must_use]
154    pub fn guard<G: Guard + 'static>(mut self, guard: G) -> Self {
155        self.guards.push(Box::new(guard));
156        self
157    }
158
159    pub(crate) fn add_guards(mut self, guards: Vec<Box<dyn Guard>>) -> Self {
160        self.guards.extend(guards);
161        self
162    }
163
164    /// Registers a request filter for this resource.
165    ///
166    /// The filter runs after the resource's path and guards match, but before
167    /// its routes are checked. It therefore also runs when no route matches
168    /// and the resource's default service is used.
169    ///
170    /// ```rust
171    /// use std::convert::Infallible;
172    /// use ntex::web::{self, App, WebRequest};
173    ///
174    /// async fn item(_state: &(), item_id: usize) -> String {
175    ///     format!("Item {item_id}")
176    /// }
177    ///
178    /// App::new().service(
179    ///     web::resource("/item")
180    ///         .filter(async |req: WebRequest<()>| {
181    ///             Ok::<_, Infallible>(req.map_state(|()| 10usize))
182    ///         })
183    ///         .route(web::get().to_with_state(item)),
184    /// );
185    /// ```
186    #[must_use]
187    pub fn filter<U, R>(
188        self,
189        filter: impl IntoServiceFactory<U, St, WebRequest<Out>>,
190    ) -> Resource<
191        St,
192        In,
193        R,
194        M,
195        impl ServiceFactory<
196            St,
197            WebRequest<In>,
198            Res = WebRequest<R>,
199            Error = WebError<St, St::Error>,
200            InitError = Failure,
201        >,
202    >
203    where
204        U: ServiceFactory<St, WebRequest<Out>, Res = WebRequest<R>>,
205        U::Error: WebResponseError<St, St::Error>,
206        U::InitError: IntoFailure,
207    {
208        Resource {
209            filter: self.filter.and_then(
210                filter
211                    .into_factory()
212                    .map_err(WebError::from_err)
213                    .map_init_err(IntoFailure::fail),
214            ),
215            middleware: self.middleware,
216            rdef: self.rdef,
217            name: self.name,
218            guards: self.guards,
219            ph: PhantomData,
220        }
221    }
222
223    /// Registers a middleware for this resource.
224    ///
225    /// The middleware runs only after the resource's path and guards match. It
226    /// wraps the resource filter, routes, and fallback service, so it can
227    /// inspect or modify both the request and response. It also runs when no
228    /// route matches and the resource fallback handles the request.
229    ///
230    /// ```rust
231    /// use ntex::web::{self, middleware, App};
232    ///
233    /// App::default().service(
234    ///     web::resource("/items")
235    ///         .middleware(middleware::Logger::default())
236    ///         .route(web::get().to(async || "Items")),
237    /// );
238    /// ```
239    #[must_use]
240    #[doc(alias = "wrap")]
241    pub fn middleware<U>(self, mw: U) -> Resource<St, In, Out, WebStack<St, U, M>, F> {
242        Resource {
243            middleware: WebStack::new(mw, self.middleware),
244            filter: self.filter,
245            rdef: self.rdef,
246            name: self.name,
247            guards: self.guards,
248            ph: PhantomData,
249        }
250    }
251
252    /// Add one or more routes to this resource.
253    ///
254    /// Routes are checked in registration order after the resource path and
255    /// resource guards match. The first route whose method and custom guards
256    /// accept the request is called. If no route matches, the resource's
257    /// default service is used; without a custom default, it returns
258    /// `405 Method Not Allowed`.
259    ///
260    /// A single [`Route`] or a collection of routes can be supplied.
261    ///
262    /// ```rust
263    /// use ntex::web::{self, App, HttpResponse};
264    ///
265    /// App::default().service(
266    ///     web::resource("/items").route([
267    ///         web::get().to(async || "list"),
268    ///         web::post().to(async || HttpResponse::Created()),
269    ///         web::delete().to(async || HttpResponse::NoContent()),
270    ///     ])
271    /// );
272    /// ```
273    #[must_use]
274    pub fn route<R>(self, route: R) -> ResourceServices<St, In, Out, M, F>
275    where
276        R: IntoRoutes<St, Out>,
277    {
278        let mut routes = Vec::new();
279        for route in route.routes() {
280            routes.push(route);
281        }
282
283        ResourceServices {
284            routes,
285            name: self.name,
286            rdef: self.rdef,
287            guards: self.guards,
288            filter: self.filter,
289            middleware: self.middleware,
290            default: None,
291        }
292    }
293
294    /// Register route with a handler.
295    ///
296    /// The route matches every request after this resource's path and guards
297    /// match. The handler receives request extractor values and returns a type
298    /// implementing [`Responder`](super::Responder).
299    ///
300    /// ```rust
301    /// use ntex::web::{self, App};
302    ///
303    /// async fn show_user(id: web::types::Path<u32>) -> String {
304    ///     format!("User {}", id.into_inner())
305    /// }
306    ///
307    /// App::default()
308    ///     .service(web::resource("/users/{id}").to(show_user));
309    /// ```
310    ///
311    /// This is equivalent to `resource.route(web::route().to(handler))`.
312    #[must_use]
313    pub fn to<Args>(self, h: impl Handler<St, Args>) -> ResourceServices<St, In, Out, M, F>
314    where
315        Args: FromRequest<St> + 'static,
316        Args::Error: WebResponseError<St, St::Error>,
317    {
318        ResourceServices {
319            name: self.name,
320            rdef: self.rdef,
321            guards: self.guards,
322            filter: self.filter,
323            middleware: self.middleware,
324            default: None,
325            routes: vec![Route::new().to(h)],
326        }
327    }
328
329    /// Register a state-aware handler as a new route.
330    ///
331    /// The handler receives a shared reference to the application state,
332    /// followed by the current request state and any request extractors.
333    ///
334    /// ```rust
335    /// use ntex::web;
336    ///
337    /// struct AppState {
338    ///     greeting: &'static str,
339    /// }
340    ///
341    /// impl web::State for AppState {
342    ///     type Error = web::DefaultError;
343    /// }
344    ///
345    /// async fn index(
346    ///     state: &AppState,
347    ///     request_state: (),
348    ///     name: web::types::Path<String>,
349    /// ) -> String {
350    ///     let _ = request_state;
351    ///     format!("{}, {}!", state.greeting, name.into_inner())
352    /// }
353    ///
354    /// web::App::<AppState>::new()
355    ///     .service(web::resource("/{name}").to_with_state(index));
356    /// ```
357    ///
358    /// This is equivalent to `resource.route(web::route().to_with_state(handler))`.
359    #[must_use]
360    pub fn to_with_state<Args>(
361        self,
362        h: impl HandlerSt<St, Out, Args>,
363    ) -> ResourceServices<St, In, Out, M, F>
364    where
365        Args: FromRequest<St> + 'static,
366        Args::Error: WebResponseError<St, St::Error>,
367    {
368        ResourceServices {
369            name: self.name,
370            rdef: self.rdef,
371            guards: self.guards,
372            filter: self.filter,
373            middleware: self.middleware,
374            default: None,
375            routes: vec![Route::new().to_with_state(h)],
376        }
377    }
378
379    /// Set the fallback service for this resource.
380    ///
381    /// The fallback is called after the resource path and guards match but none
382    /// of its routes match, commonly because the request method is unsupported.
383    /// Without a custom fallback, the resource returns
384    /// `405 Method Not Allowed`. It does not delegate to a scope or application
385    /// fallback.
386    ///
387    /// ```rust
388    /// use ntex::web::{self, App, HttpResponse};
389    ///
390    /// App::default().service(
391    ///     web::resource("/items")
392    ///         .route(web::get().to(async || "items"))
393    ///         .default_service(web::to(async || {
394    ///             HttpResponse::MethodNotAllowed().body("Use GET")
395    ///         }))
396    /// );
397    /// ```
398    #[must_use]
399    pub fn default_service<S>(
400        self,
401        f: impl IntoServiceFactory<S, St, WebRequest<Out>>,
402    ) -> ResourceServices<St, In, Out, M, F>
403    where
404        S: ServiceFactory<St, WebRequest<Out>, Res = WebResponse> + 'static,
405        S::Error: WebResponseError<St, St::Error>,
406        S::InitError: IntoFailure,
407    {
408        // create and configure default resource
409        ResourceServices {
410            name: self.name,
411            rdef: self.rdef,
412            guards: self.guards,
413            filter: self.filter,
414            routes: Vec::new(),
415            middleware: self.middleware,
416            default: Some(HttpService::new(
417                f.into_factory()
418                    .map_err(WebError::from_err)
419                    .map_init_err(IntoFailure::fail),
420            )),
421        }
422    }
423}
424
425impl<St, In, Out, M, F> ResourceServices<St, In, Out, M, F>
426where
427    St: State,
428    In: 'static,
429    Out: 'static,
430    M: 'static,
431    F: ServiceFactory<
432            St,
433            WebRequest<In>,
434            Res = WebRequest<Out>,
435            Error = WebError<St, St::Error>,
436            InitError = Failure,
437        >,
438{
439    /// Add one or more routes to this resource.
440    ///
441    /// Routes are checked in registration order after the resource path and
442    /// resource guards match. The first route whose method and custom guards
443    /// accept the request is called. If no route matches, the resource's
444    /// default service is used; without a custom default, it returns
445    /// `405 Method Not Allowed`.
446    ///
447    /// A single [`Route`] or a collection of routes can be supplied.
448    ///
449    /// ```rust
450    /// use ntex::web::{self, App, HttpResponse};
451    ///
452    /// App::default().service(
453    ///     web::resource("/items")
454    ///         .route(web::get().to(async || "list"))
455    ///         .route([
456    ///             web::post().to(async || HttpResponse::Created()),
457    ///             web::delete().to(async || HttpResponse::NoContent()),
458    ///         ])
459    /// );
460    /// ```
461    #[must_use]
462    pub fn route<R>(mut self, route: R) -> Self
463    where
464        R: IntoRoutes<St, Out>,
465    {
466        for route in route.routes() {
467            self.routes.push(route);
468        }
469        self
470    }
471
472    /// Add an unguarded route with a handler.
473    ///
474    /// The route matches every request not accepted by an earlier route.
475    /// Routes are checked in registration order, so this catch-all route should
476    /// normally be added last; routes added after it cannot be selected.
477    ///
478    /// The handler receives request extractor values and returns a type
479    /// implementing [`Responder`](super::Responder).
480    ///
481    /// ```rust
482    /// use ntex::web::{self, App};
483    ///
484    /// App::default().service(
485    ///     web::resource("/items")
486    ///         .route(web::get().to(async || "list"))
487    ///         .to(async || "Unsupported request")
488    /// );
489    /// ```
490    #[must_use]
491    pub fn to<Args>(mut self, handler: impl Handler<St, Args>) -> Self
492    where
493        Args: FromRequest<St> + 'static,
494        Args::Error: WebResponseError<St, St::Error>,
495    {
496        self.routes.push(Route::new().to(handler));
497        self
498    }
499
500    /// Add a state-aware handler as a new route.
501    ///
502    /// The route has no guards and matches any request not accepted by an
503    /// earlier route. The handler receives a shared reference to the
504    /// application state, followed by the current request state and any request
505    /// extractors.
506    ///
507    /// ```rust
508    /// use ntex::web;
509    ///
510    /// struct AppState;
511    ///
512    /// impl web::State for AppState {
513    ///     type Error = web::DefaultError;
514    /// }
515    ///
516    /// async fn fallback(
517    ///     _state: &AppState,
518    ///     _request_state: (),
519    ///     req: web::HttpRequest,
520    /// ) -> String {
521    ///     format!("No route for {}", req.path())
522    /// }
523    ///
524    /// web::App::<AppState>::new().service(
525    ///     web::resource("/")
526    ///         .route(web::get().to(async || "GET"))
527    ///         .to_with_state(fallback)
528    /// );
529    /// ```
530    #[must_use]
531    pub fn to_with_state<Args>(mut self, handler: impl HandlerSt<St, Out, Args>) -> Self
532    where
533        Args: FromRequest<St> + 'static,
534        Args::Error: WebResponseError<St, St::Error>,
535    {
536        self.routes.push(Route::new().to_with_state(handler));
537        self
538    }
539
540    /// Set the fallback service for this resource.
541    ///
542    /// The fallback is called after the resource path and guards match but none
543    /// of its routes match, commonly because the request method is unsupported.
544    /// Without a custom fallback, the resource returns
545    /// `405 Method Not Allowed`. It does not delegate to a scope or application
546    /// fallback.
547    ///
548    /// ```rust
549    /// use ntex::web::{self, App, HttpResponse};
550    ///
551    /// App::default().service(
552    ///     web::resource("/items")
553    ///         .route(web::get().to(async || "items"))
554    ///         .default_service(web::to(async || {
555    ///             HttpResponse::MethodNotAllowed().body("Use GET")
556    ///         }))
557    /// );
558    /// ```
559    #[must_use]
560    pub fn default_service<S>(mut self, f: impl IntoServiceFactory<S, St, WebRequest<Out>>) -> Self
561    where
562        S: ServiceFactory<St, WebRequest<Out>, Res = WebResponse> + 'static,
563        S::Error: WebResponseError<St, St::Error>,
564        S::InitError: IntoFailure,
565    {
566        // create and configure default resource
567        self.default = Some(HttpService::new(
568            f.into_factory()
569                .map_err(WebError::from_err)
570                .map_init_err(IntoFailure::fail),
571        ));
572
573        self
574    }
575}
576
577impl<St, Outer, In, Out, M, F> WebServiceFactory<St, Outer> for ResourceServices<St, In, Out, M, F>
578where
579    St: State,
580    Outer: 'static,
581    In: 'static,
582    Out: 'static,
583    F: ServiceFactory<
584            St,
585            WebRequest<In>,
586            Res = WebRequest<Out>,
587            Error = WebError<St, St::Error>,
588            InitError = Failure,
589        > + 'static,
590    M: Middleware<ResourceService<St, In, Out, F::Service>, St> + 'static,
591    M::Service: Service<St, WebRequest<Outer>, Res = WebResponse, Error = WebError<St, St::Error>>,
592{
593    fn register(mut self, config: &mut WebServiceConfig<St, Outer>) {
594        let guards = if self.guards.is_empty() {
595            None
596        } else {
597            Some(std::mem::take(&mut self.guards))
598        };
599        let mut rdef = if config.is_root() || !self.rdef.is_empty() {
600            ResourceDef::new(insert_slash(self.rdef.clone()))
601        } else {
602            ResourceDef::new(self.rdef.clone())
603        };
604        if let Some(ref name) = self.name {
605            rdef.set_name(name.clone());
606        }
607
608        // A resource without middleware, filter, or fallback is dispatched
609        // by the router directly.
610        if self.default.is_none()
611            && TypeId::of::<M>() == TypeId::of::<Identity>()
612            && TypeId::of::<Out>() == TypeId::of::<Outer>()
613            && Filter::<St, In>::is_identity::<F>()
614        {
615            let routes: Vec<RouteService<St, Out>> =
616                self.routes.iter().map(Route::service).collect();
617            let mut routes = Some(routes);
618            let routes = (&mut routes as &mut dyn Any)
619                .downcast_mut::<Option<Vec<RouteService<St, Outer>>>>()
620                .and_then(Option::take)
621                .expect("request state types are equal");
622            config.register_routes(rdef, guards, routes);
623            return;
624        }
625
626        config.register_service(
627            rdef,
628            guards,
629            None,
630            ResourceServiceFactory {
631                middleware: self.middleware,
632                filter: self.filter,
633                routes: self.routes,
634                default: self.default.take(),
635                ph: PhantomData,
636            },
637        );
638    }
639}
640
641impl<St, Outer, In, Out, M, F>
642    IntoServiceFactory<
643        ResourceServiceFactory<St, In, Out, M, ServiceChainFactory<F, St, WebRequest<In>>>,
644        St,
645        WebRequest<Outer>,
646    > for ResourceServices<St, In, Out, M, F>
647where
648    St: State,
649    Outer: 'static,
650    In: 'static,
651    Out: 'static,
652    F: ServiceFactory<
653            St,
654            WebRequest<In>,
655            Res = WebRequest<Out>,
656            Error = WebError<St, St::Error>,
657            InitError = Failure,
658        > + 'static,
659    M: Middleware<ResourceService<St, In, Out, F::Service>, St> + 'static,
660    M::Service: Service<St, WebRequest<Outer>, Res = WebResponse, Error = WebError<St, St::Error>>,
661{
662    fn into_factory(
663        mut self,
664    ) -> ResourceServiceFactory<St, In, Out, M, ServiceChainFactory<F, St, WebRequest<In>>> {
665        ResourceServiceFactory {
666            middleware: self.middleware,
667            filter: self.filter,
668            routes: self.routes,
669            default: self.default.take(),
670            ph: PhantomData,
671        }
672    }
673}
674
675/// Resource service factory
676#[derive(derive_more::Debug)]
677#[debug("ResourceServiceFactory")]
678pub struct ResourceServiceFactory<St: State, In, Out, M, F> {
679    middleware: M,
680    filter: F,
681    routes: Vec<Route<St, Out>>,
682    default: Option<HttpService<St, Out>>,
683    ph: PhantomData<In>,
684}
685
686impl<St, Outer, In, Out, M, F> ServiceFactory<St, WebRequest<Outer>>
687    for ResourceServiceFactory<St, In, Out, M, F>
688where
689    St: State,
690    In: 'static,
691    Out: 'static,
692    F: ServiceFactory<
693            St,
694            WebRequest<In>,
695            Res = WebRequest<Out>,
696            Error = WebError<St, St::Error>,
697            InitError = Failure,
698        > + 'static,
699    M: Middleware<ResourceService<St, In, Out, F::Service>, St> + 'static,
700    M::Service: Service<St, WebRequest<Outer>, Res = WebResponse, Error = WebError<St, St::Error>>,
701{
702    type Res = WebResponse;
703    type Error = WebError<St, St::Error>;
704
705    type Service = M::Service;
706    type InitError = Failure;
707
708    async fn create(&self, st: &St) -> Result<Self::Service, Self::InitError> {
709        let filter = self.filter.create(st).await?;
710        let default = if let Some(ref default) = self.default {
711            Some(ReadyBinding::new(default.create(st).await?))
712        } else {
713            None
714        };
715
716        Ok(self.middleware.create(
717            st,
718            ResourceService {
719                filter,
720                bypass: Filter::<St, In>::is_identity::<F>(),
721                default,
722                routes: self.routes.iter().map(Route::service).collect(),
723                ph: PhantomData,
724            },
725        ))
726    }
727}
728
729/// Resource service.
730///
731/// Readiness requires both the filter and the configured fallback to be ready,
732/// even when a request matches a route.
733#[derive(derive_more::Debug)]
734#[debug("ResourceService")]
735pub struct ResourceService<St: State, In, Out, F> {
736    filter: F,
737    /// Set if `filter` is the identity filter, which is never called.
738    bypass: bool,
739    routes: Vec<RouteService<St, Out>>,
740    default: Option<ReadyBinding<HttpHandler<St, Out>>>,
741    ph: PhantomData<In>,
742}
743
744impl<St, In, Out, F> Service<St, WebRequest<In>> for ResourceService<St, In, Out, F>
745where
746    St: State,
747    In: 'static,
748    Out: 'static,
749    F: Service<St, WebRequest<In>, Res = WebRequest<Out>, Error = WebError<St, St::Error>>,
750{
751    type Res = WebResponse;
752    type Error = WebError<St, St::Error>;
753
754    fn bind(&self, ctx: crate::service::BindCtx<'_>) {
755        ctx.bind(&self.filter);
756        for route in &self.routes {
757            ctx.bind(route);
758        }
759        if let Some(default) = &self.default {
760            ctx.bind(default);
761        }
762    }
763
764    async fn ready(&self, ctx: Ctx<'_, Self, St>) -> Result<(), Self::Error> {
765        ctx.ready(&self.filter).await?;
766        if let Some(default) = &self.default {
767            ctx.ready(default).await?;
768        }
769        Ok(())
770    }
771
772    async fn shutdown(&self, ctx: Ctx<'_, Self, St>) {
773        ctx.shutdown(&self.filter).await;
774        for route in &self.routes {
775            ctx.shutdown(route).await;
776        }
777        if let Some(default) = &self.default {
778            ctx.shutdown(default).await;
779        }
780    }
781
782    async fn call(
783        &self,
784        req: WebRequest<In>,
785        ctx: Ctx<'_, Self, St>,
786    ) -> Result<Self::Res, Self::Error> {
787        let mut req = if self.bypass {
788            passthrough::<In, Out>(req)
789        } else {
790            ctx.call(&self.filter, req).await?
791        };
792
793        for route in &self.routes {
794            if route.check(&mut req) {
795                return ctx.call(route, req).await;
796            }
797        }
798        if let Some(ref default) = self.default {
799            ctx.call(default, req).await
800        } else {
801            Ok(WebResponse::new(
802                Response::MethodNotAllowed().build(),
803                req.into_parts().0,
804            ))
805        }
806    }
807}
808
809#[cfg(test)]
810mod tests {
811    use std::convert::Infallible;
812
813    use crate::http::{Method, StatusCode};
814    use crate::time::{Millis, sleep};
815    use crate::web::test::{TestRequest, call_service, init_service};
816    use crate::web::{self, App, HttpResponse, guard, request::WebRequest};
817
818    /// STATEMENT: Resource filters execute before a matching route handler.
819    ///
820    /// HOW:
821    /// - Attach a flag-setting filter and GET handler to `/test`.
822    /// - Call it and assert OK and that the shared flag was set.
823    #[crate::rt_test]
824    async fn test_filter() {
825        let filter = std::rc::Rc::new(std::cell::Cell::new(false));
826        let filter2 = filter.clone();
827        let srv = init_service(
828            App::new().service(
829                web::resource("/test")
830                    .filter(async move |req: WebRequest<()>| {
831                        filter2.set(true);
832                        Ok::<_, Infallible>(req)
833                    })
834                    .route(web::get().to(async || HttpResponse::Ok())),
835            ),
836        )
837        .await;
838        let req = TestRequest::with_uri("/test").to_request();
839        let resp = call_service(&srv, req).await;
840        assert_eq!(resp.status(), StatusCode::OK);
841        assert!(filter.get());
842    }
843
844    /// STATEMENT: Only the default identity filter is bypassed by resource services.
845    ///
846    /// HOW:
847    /// - Create a resource service without a filter and assert `bypass` is `true`.
848    /// - Create one with a custom filter and assert `bypass` is `false`.
849    #[crate::rt_test]
850    async fn default_filter_is_bypassed() {
851        use crate::service::{IntoServiceFactory, ServiceFactory};
852
853        let srv = IntoServiceFactory::<_, (), WebRequest<()>>::into_factory(
854            web::resource("/test").to(async || HttpResponse::Ok()),
855        )
856        .create(&())
857        .await
858        .unwrap();
859        assert!(srv.bypass);
860
861        let srv = IntoServiceFactory::<_, (), WebRequest<()>>::into_factory(
862            web::resource("/test")
863                .filter(async |req: WebRequest<()>| Ok::<_, Infallible>(req))
864                .to(async || HttpResponse::Ok()),
865        )
866        .create(&())
867        .await
868        .unwrap();
869        assert!(!srv.bypass);
870    }
871
872    /// STATEMENT: Resource readiness requires both the filter and initialized fallback to be ready.
873    ///
874    /// HOW:
875    /// - Build a resource with raw gated filter and fallback services and verify both are bound.
876    /// - Release the filter and verify resource readiness still waits for the fallback.
877    /// - Cache readiness, block the fallback, and verify readiness and both request paths wait.
878    /// - Recover the fallback, then verify filter notifications also block calls without rebinding.
879    #[crate::rt_test]
880    async fn filter_and_fallback_readiness() {
881        use std::{cell::Cell, future::Future, rc::Rc, task::Context, task::Waker};
882
883        use crate::service::{BindCtx, Ctx, ReadyNotifier, Service, ServiceFactory, fn_factory};
884
885        #[derive(Default)]
886        struct Gate {
887            available: Cell<bool>,
888            binds: Cell<usize>,
889            calls: Cell<usize>,
890            changed: ReadyNotifier,
891        }
892
893        struct Gated(Rc<Gate>);
894
895        impl Service<(), WebRequest<()>> for Gated {
896            type Res = WebRequest<()>;
897            type Error = Infallible;
898
899            fn bind(&self, ctx: BindCtx<'_>) {
900                self.0.binds.set(self.0.binds.get() + 1);
901                ctx.subscribe(&self.0.changed);
902            }
903
904            async fn ready(&self, _: Ctx<'_, Self>) -> Result<(), Infallible> {
905                if !self.0.available.get() {
906                    std::future::pending::<()>().await;
907                }
908                Ok(())
909            }
910
911            async fn call(
912                &self,
913                req: WebRequest<()>,
914                _: Ctx<'_, Self>,
915            ) -> Result<WebRequest<()>, Infallible> {
916                self.0.calls.set(self.0.calls.get() + 1);
917                Ok(req)
918            }
919        }
920
921        let filter = Rc::new(Gate::default());
922        let default = Rc::new(Gate::default());
923        let factory = |gate: Rc<Gate>| {
924            fn_factory(async move |(): &()| Ok::<_, Infallible>(Gated(gate.clone())))
925        };
926        let srv = crate::factory(
927            web::resource("/test")
928                .filter(factory(filter.clone()))
929                .route(web::get().to(async || HttpResponse::Ok()))
930                .default_service(
931                    factory(default.clone())
932                        .map(|req: WebRequest<()>| req.into_response(HttpResponse::Created())),
933                ),
934        )
935        .pipeline(())
936        .await
937        .unwrap();
938        assert_eq!((filter.binds.get(), default.binds.get()), (1, 1));
939
940        let mut cx = Context::from_waker(Waker::noop());
941        let mut ready = Box::pin(srv.ready());
942        assert!(ready.as_mut().poll(&mut cx).is_pending());
943        filter.available.set(true);
944        filter.changed.notify();
945        assert!(ready.as_mut().poll(&mut cx).is_pending());
946        default.available.set(true);
947        default.changed.notify();
948        ready.await.unwrap();
949
950        let response = srv
951            .call(TestRequest::default().to_srv_request())
952            .await
953            .unwrap();
954        assert_eq!(response.status(), StatusCode::OK);
955        assert_eq!(default.calls.get(), 0);
956
957        srv.ready().await.unwrap();
958        default.available.set(false);
959        default.changed.notify();
960        let calls = filter.calls.get();
961        let mut ready = Box::pin(srv.ready());
962        assert!(ready.as_mut().poll(&mut cx).is_pending());
963        let mut matched = Box::pin(srv.call(TestRequest::default().to_srv_request()));
964        assert!(matched.as_mut().poll(&mut cx).is_pending());
965        let mut call = Box::pin(srv.call(TestRequest::post().to_srv_request()));
966        assert!(call.as_mut().poll(&mut cx).is_pending());
967        assert_eq!(filter.calls.get(), calls);
968        assert_eq!(default.calls.get(), 0);
969        default.available.set(true);
970        default.changed.notify();
971        ready.await.unwrap();
972        assert_eq!(matched.await.unwrap().status(), StatusCode::OK);
973        assert_eq!(call.await.unwrap().status(), StatusCode::CREATED);
974
975        srv.ready().await.unwrap();
976        let calls = filter.calls.get();
977        filter.available.set(false);
978        filter.changed.notify();
979        let mut call = Box::pin(srv.call(TestRequest::default().to_srv_request()));
980        assert!(call.as_mut().poll(&mut cx).is_pending());
981        assert_eq!(filter.calls.get(), calls);
982        filter.available.set(true);
983        filter.changed.notify();
984        assert_eq!(call.await.unwrap().status(), StatusCode::OK);
985        assert_eq!((filter.binds.get(), default.binds.get()), (1, 1));
986    }
987
988    /// STATEMENT: Shutting down a resource shuts down its filter and fallback services.
989    ///
990    /// HOW:
991    /// - Build a resource whose filter and default service count `shutdown` calls.
992    /// - Shut down the resource pipeline and assert each counter is exactly one.
993    #[crate::rt_test]
994    async fn shutdown_reaches_filter_and_fallback() {
995        use std::{cell::Cell, rc::Rc};
996
997        use crate::service::{Ctx, Service, ServiceFactory, fn_factory};
998
999        struct Counted(Rc<Cell<usize>>);
1000
1001        impl Service<(), WebRequest<()>> for Counted {
1002            type Res = WebRequest<()>;
1003            type Error = Infallible;
1004
1005            async fn call(
1006                &self,
1007                req: WebRequest<()>,
1008                _: Ctx<'_, Self>,
1009            ) -> Result<WebRequest<()>, Infallible> {
1010                Ok(req)
1011            }
1012
1013            async fn shutdown(&self, _: Ctx<'_, Self>) {
1014                self.0.set(self.0.get() + 1);
1015            }
1016        }
1017
1018        let filter = Rc::new(Cell::new(0));
1019        let default = Rc::new(Cell::new(0));
1020        let factory = |count: Rc<Cell<usize>>| {
1021            fn_factory(async move |(): &()| Ok::<_, Infallible>(Counted(count.clone())))
1022        };
1023        let srv = crate::factory(
1024            web::resource("/test")
1025                .filter(factory(filter.clone()))
1026                .route(web::get().to(async || HttpResponse::Ok()))
1027                .default_service(
1028                    factory(default.clone())
1029                        .map(|req: WebRequest<()>| req.into_response(HttpResponse::Created())),
1030                ),
1031        )
1032        .pipeline(())
1033        .await
1034        .unwrap();
1035
1036        srv.shutdown().await;
1037        assert_eq!((filter.get(), default.get()), (1, 1));
1038    }
1039
1040    /// STATEMENT: `Resource::to` supports handlers that complete asynchronously.
1041    ///
1042    /// HOW:
1043    /// - Register `/test` with a handler that sleeps before returning OK.
1044    /// - Await a request and assert its status is OK.
1045    #[crate::rt_test]
1046    async fn test_to() {
1047        let srv = init_service(App::new().service(web::resource("/test").to(async || {
1048            sleep(Millis(100)).await;
1049            HttpResponse::Ok()
1050        })))
1051        .await;
1052        let req = TestRequest::with_uri("/test").to_request();
1053        let resp = call_service(&srv, req).await;
1054        assert_eq!(resp.status(), StatusCode::OK);
1055    }
1056
1057    /// STATEMENT: One resource can serve multiple path patterns.
1058    ///
1059    /// HOW:
1060    /// - Register `/test` and `/test2` together with one OK handler.
1061    /// - Request both paths and assert OK for each response.
1062    #[crate::rt_test]
1063    async fn test_pattern() {
1064        let srv = init_service(
1065            App::new().service(web::resource(["/test", "/test2"]).to(async || HttpResponse::Ok())),
1066        )
1067        .await;
1068        let req = TestRequest::with_uri("/test").to_request();
1069        let resp = call_service(&srv, req).await;
1070        assert_eq!(resp.status(), StatusCode::OK);
1071        let req = TestRequest::with_uri("/test2").to_request();
1072        let resp = call_service(&srv, req).await;
1073        assert_eq!(resp.status(), StatusCode::OK);
1074    }
1075
1076    /// STATEMENT: Resource method misses use the resource fallback rather than the application default.
1077    ///
1078    /// HOW:
1079    /// - Register a GET-only resource and a bad-request application default; assert GET is OK and POST is 405.
1080    /// - Add a bad-request resource default and assert GET stays OK while POST now returns 400.
1081    #[crate::rt_test]
1082    async fn test_default_resource() {
1083        let srv = init_service(
1084            App::new()
1085                .service(web::resource("/test").route(web::get().to(async || HttpResponse::Ok())))
1086                .default_service(async move |r: WebRequest<()>| {
1087                    Ok::<_, Infallible>(r.into_response(HttpResponse::BadRequest()))
1088                }),
1089        )
1090        .await;
1091        let req = TestRequest::with_uri("/test").to_request();
1092        let resp = call_service(&srv, req).await;
1093        assert_eq!(resp.status(), StatusCode::OK);
1094
1095        let req = TestRequest::with_uri("/test")
1096            .method(Method::POST)
1097            .to_request();
1098        let resp = call_service(&srv, req).await;
1099        assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
1100
1101        let srv = init_service(
1102            App::new().service(
1103                web::resource("/test")
1104                    .route(web::get().to(async || HttpResponse::Ok()))
1105                    .default_service(async move |r: WebRequest<()>| {
1106                        Ok::<_, Infallible>(r.into_response(HttpResponse::BadRequest()))
1107                    }),
1108            ),
1109        )
1110        .await;
1111
1112        let req = TestRequest::with_uri("/test").to_request();
1113        let resp = call_service(&srv, req).await;
1114        assert_eq!(resp.status(), StatusCode::OK);
1115
1116        let req = TestRequest::with_uri("/test")
1117            .method(Method::POST)
1118            .to_request();
1119        let resp = call_service(&srv, req).await;
1120        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
1121    }
1122
1123    /// STATEMENT: Resource guards distinguish otherwise identical parameterized paths by method.
1124    ///
1125    /// HOW:
1126    /// - Register GET-, PUT-, and DELETE-guarded resources at `/test/{p}`.
1127    /// - Call each method and assert statuses OK, `CREATED`, and `NO_CONTENT`, respectively.
1128    #[crate::rt_test]
1129    async fn test_resource_guards() {
1130        let srv = init_service(
1131            App::new()
1132                .service(
1133                    web::resource("/test/{p}")
1134                        .guard(guard::Get())
1135                        .to(async || HttpResponse::Ok()),
1136                )
1137                .service(
1138                    web::resource("/test/{p}")
1139                        .guard(guard::Put())
1140                        .to(async || HttpResponse::Created()),
1141                )
1142                .service(
1143                    web::resource("/test/{p}")
1144                        .guard(guard::Delete())
1145                        .to(async || HttpResponse::NoContent()),
1146                ),
1147        )
1148        .await;
1149
1150        let req = TestRequest::with_uri("/test/it")
1151            .method(Method::GET)
1152            .to_request();
1153        let resp = call_service(&srv, req).await;
1154        assert_eq!(resp.status(), StatusCode::OK);
1155
1156        let req = TestRequest::with_uri("/test/it")
1157            .method(Method::PUT)
1158            .to_request();
1159        let resp = call_service(&srv, req).await;
1160        assert_eq!(resp.status(), StatusCode::CREATED);
1161
1162        let req = TestRequest::with_uri("/test/it")
1163            .method(Method::DELETE)
1164            .to_request();
1165        let resp = call_service(&srv, req).await;
1166        assert_eq!(resp.status(), StatusCode::NO_CONTENT);
1167    }
1168
1169    /// STATEMENT: Resource middleware applies to both matching handlers and fallback responses.
1170    ///
1171    /// HOW:
1172    /// - Add a default content-type header around a GET-only resource.
1173    /// - Send GET and POST and assert both responses contain `text/plain`.
1174    #[crate::rt_test]
1175    async fn test_middleware() {
1176        use crate::http::header::{CONTENT_TYPE, HeaderValue};
1177        use crate::web::middleware::DefaultHeaders;
1178
1179        let srv = init_service(
1180            App::new().service(
1181                web::resource("/test")
1182                    .middleware(DefaultHeaders::new().header(CONTENT_TYPE, "text/plain"))
1183                    .route(web::get().to(async || HttpResponse::Ok())),
1184            ),
1185        )
1186        .await;
1187        for method in [Method::GET, Method::POST] {
1188            let req = TestRequest::with_uri("/test").method(method).to_request();
1189            let resp = call_service(&srv, req).await;
1190            assert_eq!(
1191                resp.headers().get(CONTENT_TYPE),
1192                Some(&HeaderValue::from_static("text/plain"))
1193            );
1194        }
1195    }
1196
1197    /// STATEMENT: An empty resource path matches a scope root without accepting an extra slash.
1198    ///
1199    /// HOW:
1200    /// - Register an empty resource under `/app`.
1201    /// - Assert `/app` returns OK and `/app/` returns 404.
1202    #[crate::rt_test]
1203    async fn test_empty_path_in_scope() {
1204        let srv = init_service(App::new().service(
1205            web::scope("/app").service(web::resource("").to(async || HttpResponse::Ok())),
1206        ))
1207        .await;
1208        let resp = call_service(&srv, TestRequest::with_uri("/app").to_request()).await;
1209        assert_eq!(resp.status(), StatusCode::OK);
1210        let resp = call_service(&srv, TestRequest::with_uri("/app/").to_request()).await;
1211        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
1212    }
1213
1214    /// STATEMENT: Converting a resource into a factory preserves its routes and default service.
1215    ///
1216    /// HOW:
1217    /// - Convert a GET resource with a 405 default through `IntoServiceFactory` and build its pipeline.
1218    /// - Call with GET and PUT and assert OK and `METHOD_NOT_ALLOWED`, respectively.
1219    #[crate::rt_test]
1220    async fn test_into_factory() {
1221        use crate::service::{IntoServiceFactory, ServiceFactory};
1222
1223        let res = web::resource("/test")
1224            .route(web::get().to(async || HttpResponse::Ok()))
1225            .default_service(async |r: WebRequest<()>| {
1226                Ok::<_, Infallible>(r.into_response(HttpResponse::MethodNotAllowed()))
1227            });
1228        let srv = IntoServiceFactory::<_, (), WebRequest<()>>::into_factory(res)
1229            .pipeline(())
1230            .await
1231            .unwrap();
1232
1233        let resp = srv
1234            .call(TestRequest::default().to_srv_request())
1235            .await
1236            .unwrap();
1237        assert_eq!(resp.status(), StatusCode::OK);
1238        let req = TestRequest::default().method(Method::PUT).to_srv_request();
1239        let resp = srv.call(req).await.unwrap();
1240        assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
1241    }
1242}