Skip to main content

ntex/web/middleware/
from_fn.rs

1use std::{fmt, marker::PhantomData};
2
3use crate::service::{BindCtx, Ctx, Middleware, Service};
4use crate::web::{State, WebError, WebRequest, WebResponse, WebResponseError};
5
6/// Creates web middleware from an async closure.
7///
8/// The closure receives the request and a [`Next`] handle. Call
9/// [`Next::call()`] to run the rest of the pipeline, or return a response
10/// without calling it to short-circuit. Binding, readiness, and shutdown are
11/// forwarded to the inner service automatically.
12///
13/// Closure types are inferred, no annotations are needed:
14///
15/// ```rust,no_run
16/// use ntex::http::header::{HeaderName, HeaderValue};
17/// use ntex::web::{self, App, HttpResponse, middleware::from_fn};
18///
19/// let server = web::HttpServer::new(async |_| {
20///     App::new()
21///         .middleware(from_fn(async |req, next| {
22///             if !req.headers().contains_key("authorization") {
23///                 return Ok(req.into_response(HttpResponse::Unauthorized().build()));
24///             }
25///             let mut res = next.call(req).await?;
26///             res.headers_mut().insert(
27///                 HeaderName::from_static("x-application"),
28///                 HeaderValue::from_static("example"),
29///             );
30///             Ok(res)
31///         }))
32///         .route("/", web::get().to(async || "Hello"))
33/// });
34/// ```
35///
36/// Return `Err(web::WebError::from_err(err))` to reject a request with any
37/// [`WebResponseError`]. To read application state with [`Next::st()`],
38/// annotate the state type of `next`:
39///
40/// ```rust
41/// use ntex::http::header::{HeaderName, HeaderValue};
42/// use ntex::web::{self, App, AppState, middleware::{Next, from_fn}, test};
43///
44/// # #[ntex::main]
45/// # async fn main() {
46/// let app = test::init_service_st(
47///     AppState::new("example"),
48///     App::new()
49///         .middleware(from_fn(async |req, next: Next<'_, _, AppState<&str>>| {
50///             let name = **next.st();
51///             let mut res = next.call(req).await?;
52///             res.headers_mut().insert(
53///                 HeaderName::from_static("x-application"),
54///                 HeaderValue::from_static(name),
55///             );
56///             Ok(res)
57///         }))
58///         .route("/", web::get().to(async || "Hello")),
59/// )
60/// .await;
61/// # }
62/// ```
63pub fn from_fn<F, S, St, In>(f: F) -> FromFn<F, S, St, In>
64where
65    St: State,
66    F: AsyncFn(WebRequest<In>, Next<'_, S, St>) -> Result<WebResponse, WebError<St, St::Error>>
67        + Clone,
68{
69    FromFn { f, _t: PhantomData }
70}
71
72/// Middleware created by [`from_fn`].
73pub struct FromFn<F, S, St, In = ()> {
74    f: F,
75    _t: PhantomData<fn(S, St, In)>,
76}
77
78impl<F: Clone, S, St, In> Clone for FromFn<F, S, St, In> {
79    fn clone(&self) -> Self {
80        FromFn {
81            f: self.f.clone(),
82            _t: PhantomData,
83        }
84    }
85}
86
87impl<F, S, St, In> fmt::Debug for FromFn<F, S, St, In> {
88    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89        f.debug_struct("FromFn")
90            .field("f", &std::any::type_name::<F>())
91            .finish()
92    }
93}
94
95impl<F, S, St, In> Middleware<S, St> for FromFn<F, S, St, In>
96where
97    St: State,
98    S: Service<St, WebRequest<In>, Res = WebResponse>,
99    S::Error: WebResponseError<St, St::Error>,
100    F: AsyncFn(WebRequest<In>, Next<'_, S, St>) -> Result<WebResponse, WebError<St, St::Error>>
101        + Clone,
102{
103    type Service = FromFnService<F, S>;
104
105    fn create(&self, _: &St, svc: S) -> Self::Service {
106        FromFnService {
107            f: self.f.clone(),
108            svc,
109        }
110    }
111}
112
113/// Service created by [`FromFn`].
114pub struct FromFnService<F, S> {
115    f: F,
116    svc: S,
117}
118
119impl<F, S: fmt::Debug> fmt::Debug for FromFnService<F, S> {
120    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121        f.debug_struct("FromFnService")
122            .field("svc", &self.svc)
123            .field("f", &std::any::type_name::<F>())
124            .finish()
125    }
126}
127
128impl<F, S, St, In> Service<St, WebRequest<In>> for FromFnService<F, S>
129where
130    St: State,
131    S: Service<St, WebRequest<In>, Res = WebResponse>,
132    S::Error: WebResponseError<St, St::Error>,
133    F: AsyncFn(WebRequest<In>, Next<'_, S, St>) -> Result<WebResponse, WebError<St, St::Error>>,
134{
135    type Res = WebResponse;
136    type Error = WebError<St, St::Error>;
137
138    async fn call(
139        &self,
140        req: WebRequest<In>,
141        ctx: Ctx<'_, Self, St>,
142    ) -> Result<Self::Res, Self::Error> {
143        ctx.call(&NextService(&self.svc), (req, &self.f)).await
144    }
145
146    fn bind(&self, ctx: BindCtx<'_>) {
147        ctx.bind::<_, St, _>(&self.svc);
148    }
149
150    async fn ready(&self, ctx: Ctx<'_, Self, St>) -> Result<(), Self::Error> {
151        ctx.ready(&self.svc).await.map_err(WebError::from_err)
152    }
153
154    async fn shutdown(&self, ctx: Ctx<'_, Self, St>) {
155        ctx.shutdown(&self.svc).await;
156    }
157}
158
159/// Handle to the rest of the pipeline, passed to [`from_fn`] closures.
160pub struct Next<'a, S, St> {
161    svc: &'a S,
162    ctx: Ctx<'a, NextService<'a, S>, St>,
163}
164
165impl<S, St> fmt::Debug for Next<'_, S, St> {
166    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167        f.debug_struct("Next").finish()
168    }
169}
170
171impl<S, St: State> Next<'_, S, St> {
172    /// Calls the inner service.
173    ///
174    /// Errors of the inner service are converted to [`WebError`].
175    pub async fn call<In>(
176        &self,
177        req: WebRequest<In>,
178    ) -> Result<WebResponse, WebError<St, St::Error>>
179    where
180        S: Service<St, WebRequest<In>, Res = WebResponse>,
181        S::Error: WebResponseError<St, St::Error>,
182    {
183        self.ctx
184            .call(self.svc, req)
185            .await
186            .map_err(WebError::from_err)
187    }
188
189    /// Returns the application state.
190    pub fn st(&self) -> &St {
191        self.ctx.st()
192    }
193}
194
195struct NextService<'a, S>(&'a S);
196
197impl<'f, F, S, St, In> Service<St, (WebRequest<In>, &'f F)> for NextService<'_, S>
198where
199    St: State,
200    S: Service<St, WebRequest<In>, Res = WebResponse>,
201    S::Error: WebResponseError<St, St::Error>,
202    F: AsyncFn(WebRequest<In>, Next<'_, S, St>) -> Result<WebResponse, WebError<St, St::Error>>,
203{
204    type Res = WebResponse;
205    type Error = WebError<St, St::Error>;
206
207    async fn call(
208        &self,
209        (req, f): (WebRequest<In>, &'f F),
210        ctx: Ctx<'_, Self, St>,
211    ) -> Result<Self::Res, Self::Error> {
212        f(req, Next { svc: self.0, ctx }).await
213    }
214}
215
216#[cfg(test)]
217mod tests {
218    use std::{cell::Cell, rc::Rc};
219
220    use super::*;
221    use crate::http::StatusCode;
222    use crate::http::error::Canceled;
223    use crate::http::header::{CONTENT_TYPE, HeaderName, HeaderValue};
224    use crate::service::{Pipeline, ReadyNotifier};
225    use crate::web::test::{TestRequest, call_service, init_service, init_service_st};
226    use crate::web::{self, App, AppState, HttpResponse, error, middleware::DefaultHeaders};
227
228    /// STATEMENT: `from_fn` closures infer their types without annotations at app,
229    /// scope and resource level, and compose with other middlewares.
230    ///
231    /// HOW:
232    /// - Register unannotated `from_fn` closures on `App`, `Scope` and `Resource`,
233    ///   stacked with `DefaultHeaders`.
234    /// - Confirm each layer's header is set and `/skip` is short-circuited with 403.
235    #[crate::rt_test]
236    async fn from_fn_infers_and_stacks() {
237        let srv = init_service(
238            App::new()
239                .middleware(from_fn(async |req, next| {
240                    if req.path() == "/skip" {
241                        return Ok(req.into_response(HttpResponse::Forbidden().build()));
242                    }
243                    let mut res = next.call(req).await?;
244                    res.headers_mut()
245                        .insert(CONTENT_TYPE, HeaderValue::from_static("app"));
246                    Ok(res)
247                }))
248                .middleware(DefaultHeaders::new().header("x-a", "1"))
249                .middleware(from_fn(async |req, next| next.call(req).await))
250                .service(
251                    web::scope("/s")
252                        .middleware(from_fn(async |req, next| {
253                            let mut res = next.call(req).await?;
254                            res.headers_mut().insert(
255                                HeaderName::from_static("x-scope"),
256                                HeaderValue::from_static("1"),
257                            );
258                            Ok(res)
259                        }))
260                        .service(
261                            web::resource("/r")
262                                .middleware(from_fn(async |req, next| {
263                                    let mut res = next.call(req).await?;
264                                    res.headers_mut().insert(
265                                        HeaderName::from_static("x-res"),
266                                        HeaderValue::from_static("1"),
267                                    );
268                                    Ok(res)
269                                }))
270                                .to(async || HttpResponse::Ok()),
271                        ),
272                )
273                .route("/test", web::get().to(async || HttpResponse::Ok())),
274        )
275        .await;
276        let res = call_service(&srv, TestRequest::with_uri("/test").to_request()).await;
277        assert_eq!(res.status(), StatusCode::OK);
278        assert_eq!(res.headers().get(CONTENT_TYPE).unwrap(), "app");
279        let res = call_service(&srv, TestRequest::with_uri("/skip").to_request()).await;
280        assert_eq!(res.status(), StatusCode::FORBIDDEN);
281        let res = call_service(&srv, TestRequest::with_uri("/s/r").to_request()).await;
282        assert_eq!(res.headers().get("x-scope").unwrap(), "1");
283        assert_eq!(res.headers().get("x-res").unwrap(), "1");
284        assert_eq!(res.headers().get("x-a").unwrap(), "1");
285    }
286
287    /// STATEMENT: A `from_fn` closure can reject a request by returning a `WebError`.
288    ///
289    /// HOW:
290    /// - Return `Err(WebError::from_err(ErrorUnauthorized(..)))` when the
291    ///   `authorization` header is missing, otherwise call `next`.
292    /// - Confirm 401 without the header and 200 with it.
293    #[crate::rt_test]
294    async fn from_fn_returns_error() {
295        let srv = init_service(
296            App::new()
297                .middleware(from_fn(async |req, next| {
298                    if !req.headers().contains_key("authorization") {
299                        return Err(WebError::from_err(error::ErrorUnauthorized("no auth")));
300                    }
301                    next.call(req).await
302                }))
303                .route("/test", web::get().to(async || HttpResponse::Ok())),
304        )
305        .await;
306        let res = call_service(&srv, TestRequest::with_uri("/test").to_request()).await;
307        assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
308        let req = TestRequest::with_uri("/test")
309            .header("authorization", "x")
310            .to_request();
311        let res = call_service(&srv, req).await;
312        assert_eq!(res.status(), StatusCode::OK);
313    }
314
315    /// STATEMENT: A `from_fn` closure can read application state through `Next::st`.
316    ///
317    /// HOW:
318    /// - Build an app with `AppState<&str>` and annotate `next: Next<'_, _, AppState<&str>>`.
319    /// - Copy the state value into a response header and confirm it.
320    #[crate::rt_test]
321    async fn from_fn_reads_state() {
322        let srv = init_service_st(
323            AppState::new("st"),
324            App::<AppState<&'static str>>::new()
325                .middleware(from_fn(async |req, next: Next<'_, _, AppState<&str>>| {
326                    let tag = **next.st();
327                    let mut res = next.call(req).await?;
328                    res.headers_mut().insert(
329                        HeaderName::from_static("x-st"),
330                        HeaderValue::from_static(tag),
331                    );
332                    Ok(res)
333                }))
334                .route("/test", web::get().to(async || HttpResponse::Ok())),
335        )
336        .await;
337        let res = call_service(&srv, TestRequest::with_uri("/test").to_request()).await;
338        assert_eq!(res.headers().get("x-st").unwrap(), "st");
339    }
340
341    #[derive(Default)]
342    struct GateState {
343        closed: Cell<bool>,
344        changed: ReadyNotifier,
345        binds: Cell<usize>,
346        checks: Cell<usize>,
347        shutdowns: Cell<usize>,
348    }
349
350    #[derive(Clone, Default)]
351    struct Gate(Rc<GateState>);
352
353    impl Gate {
354        fn set_closed(&self, closed: bool) {
355            self.0.closed.set(closed);
356            self.0.changed.notify();
357        }
358
359        fn counts(&self) -> (usize, usize, usize) {
360            (
361                self.0.binds.get(),
362                self.0.checks.get(),
363                self.0.shutdowns.get(),
364            )
365        }
366    }
367
368    impl Service<(), WebRequest<()>> for Gate {
369        type Res = WebResponse;
370        type Error = Canceled;
371
372        fn bind(&self, ctx: BindCtx<'_>) {
373            self.0.binds.set(self.0.binds.get() + 1);
374            ctx.subscribe(&self.0.changed);
375        }
376
377        async fn ready(&self, _: Ctx<'_, Self>) -> Result<(), Canceled> {
378            self.0.checks.set(self.0.checks.get() + 1);
379            if self.0.closed.get() { Err(Canceled) } else { Ok(()) }
380        }
381
382        async fn call(
383            &self,
384            req: WebRequest<()>,
385            _: Ctx<'_, Self>,
386        ) -> Result<WebResponse, Canceled> {
387            Ok(req.into_response(HttpResponse::Ok().build()))
388        }
389
390        async fn shutdown(&self, _: Ctx<'_, Self>) {
391            self.0.shutdowns.set(self.0.shutdowns.get() + 1);
392        }
393    }
394
395    /// STATEMENT: `from_fn` middleware preserves child binding, readiness errors,
396    /// readiness invalidation, and shutdown.
397    ///
398    /// HOW:
399    /// - Wrap a `Gate` child, whose `bind` subscribes a `ReadyNotifier`, with a
400    ///   pass-through `from_fn` closure and confirm it is bound once.
401    /// - Confirm repeated calls check child readiness once while cached.
402    /// - Close the gate and notify, confirm `ready` fails; reopen, notify, and
403    ///   confirm calls succeed again.
404    /// - Shut the pipeline down and confirm the child's `shutdown` runs once.
405    #[crate::rt_test]
406    async fn from_fn_preserves_child_lifecycle() {
407        let gate = Gate::default();
408        let mw = from_fn(async |req, next| next.call(req).await);
409        let pl = Pipeline::new((), mw.create(&(), gate.clone()));
410        assert_eq!(gate.counts(), (1, 0, 0));
411
412        let res = pl.call(TestRequest::default().to_srv_request()).await;
413        assert_eq!(res.unwrap().status(), StatusCode::OK);
414        let res = pl.call(TestRequest::default().to_srv_request()).await;
415        assert_eq!(res.unwrap().status(), StatusCode::OK);
416        assert_eq!(gate.counts(), (1, 1, 0));
417
418        gate.set_closed(true);
419        assert!(pl.ready().await.is_err());
420        gate.set_closed(false);
421        let res = pl.call(TestRequest::default().to_srv_request()).await;
422        assert_eq!(res.unwrap().status(), StatusCode::OK);
423        assert_eq!(gate.counts(), (1, 3, 0));
424
425        pl.shutdown().await;
426        assert_eq!(gate.counts(), (1, 3, 1));
427    }
428}