Skip to main content

ntex/web/
handler.rs

1use std::{fmt, marker::PhantomData, pin::Pin, rc::Rc};
2
3use crate::service::dev::InlineFuture;
4
5use super::{FromRequest, Responder, State, WebRequest, WebResponse, WebResponseError};
6
7/// Async fn handler that receives the application and request state.
8///
9/// Implemented for async functions and closures whose first two arguments are
10/// the application state `&St` and the request state `U`, followed by up to 16
11/// extractors. `T` is the tuple of extractor types. Register such handlers with
12/// [`Route::to_with_state()`](crate::web::Route::to_with_state).
13#[diagnostic::on_unimplemented(
14    message = "`{Self}` is not a valid state-aware web handler",
15    label = "not a `to_with_state()` handler",
16    note = "a state-aware handler is an `async fn` or async closure whose first two arguments are `&St` and the request state, followed by up to 16 extractors",
17    note = "the return type must implement `Responder`; for `Result<T, E>`, `E` must implement `WebResponseError`",
18    note = "use `to()` for handlers that take only extractors"
19)]
20pub trait HandlerSt<St, U, T>: 'static
21where
22    St: State,
23{
24    /// Handler result, converted into a response.
25    type Output: Responder<St>;
26
27    /// Call the handler with the states and extracted values.
28    async fn call(&self, st: &St, req: U, param: T) -> Self::Output;
29}
30
31impl<St, U, F, R> HandlerSt<St, U, ()> for F
32where
33    F: AsyncFn(&St, U) -> R + 'static,
34    R: Responder<St>,
35    St: State,
36{
37    type Output = R;
38
39    #[allow(clippy::ignored_unit_patterns)]
40    async fn call(&self, st: &St, req: U, _: ()) -> R {
41        (self)(st, req).await
42    }
43}
44
45/// Async fn handler.
46///
47/// Implemented for async functions and closures that take up to 16
48/// extractors. `T` is the tuple of extractor types. Register such handlers with
49/// [`Route::to()`](crate::web::Route::to). Use [`HandlerSt`] when the handler
50/// needs the application or request state.
51#[diagnostic::on_unimplemented(
52    message = "`{Self}` is not a valid web handler",
53    label = "not a web handler",
54    note = "a handler is an `async fn` or async closure taking up to 16 extractors that implement `FromRequest`",
55    note = "the return type must implement `Responder`; for `Result<T, E>`, `E` must implement `WebResponseError`",
56    note = "use `to_with_state()` for handlers whose first arguments are `&St` and the request state"
57)]
58pub trait Handler<St, T>: 'static
59where
60    St: State,
61{
62    /// Handler result, converted into a response.
63    type Output: Responder<St>;
64
65    /// Call the handler with the extracted values.
66    async fn call(&self, param: T) -> Self::Output;
67}
68
69impl<St, F, R> Handler<St, ()> for F
70where
71    F: AsyncFn() -> R + 'static,
72    R: Responder<St>,
73    St: State,
74{
75    type Output = R;
76
77    #[allow(clippy::ignored_unit_patterns)]
78    async fn call(&self, _: ()) -> R {
79        (self)().await
80    }
81}
82
83pub(super) trait HandlerFn<St: State, U>: fmt::Debug {
84    /// Builds the handler future for `req` in `fut`, replacing its current future.
85    fn call<'a>(&'a self, st: &'a St, req: WebRequest<U>, fut: Pin<&mut HandlerFuture<'a>>);
86}
87
88/// Size of the inline handler future storage, in words.
89const SLOT_WORDS: usize = 32;
90
91/// Type-erased handler future, stored inline when it fits into `SLOT_WORDS`.
92pub(super) type HandlerFuture<'a> = InlineFuture<'a, WebResponse, SLOT_WORDS>;
93
94pub(super) struct HandlerStWrapper<St, U, F, T> {
95    hnd: F,
96    _t: PhantomData<(St, U, T)>,
97}
98
99impl<St, U, F, T> HandlerStWrapper<St, U, F, T>
100where
101    F: HandlerSt<St, U, T> + 'static,
102    T: FromRequest<St> + 'static,
103    T::Error: WebResponseError<St, St::Error>,
104    St: State,
105    U: 'static,
106{
107    pub(super) fn create(hnd: F) -> Rc<dyn HandlerFn<St, U>> {
108        Rc::new(HandlerStWrapper {
109            hnd,
110            _t: PhantomData,
111        })
112    }
113}
114
115impl<St, U, F, T> fmt::Debug for HandlerStWrapper<St, U, F, T> {
116    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117        write!(f, "HandlerSt({:?})", std::any::type_name::<F>())
118    }
119}
120
121impl<St, U, F, T> HandlerFn<St, U> for HandlerStWrapper<St, U, F, T>
122where
123    F: HandlerSt<St, U, T> + 'static,
124    T: FromRequest<St> + 'static,
125    T::Error: WebResponseError<St, St::Error>,
126    St: State,
127{
128    fn call<'a>(&'a self, st: &'a St, req: WebRequest<U>, fut: Pin<&mut HandlerFuture<'a>>) {
129        // split before the async block, so the dead `WebRequest` is not kept
130        // in every state of the handler future
131        let (req, mut payload, reqst) = req.into_parts();
132        fut.set_with(|| async move {
133            let param = match T::from_request(st, &req, &mut payload).await {
134                Ok(param) => param,
135                Err(e) => return WebResponse::from_err(st, &e, req),
136            };
137
138            let result = self.hnd.call(st, reqst, param).await;
139            let response = result.respond_to(st, &req).await;
140            WebResponse::new(response, req)
141        });
142    }
143}
144
145pub(super) struct HandlerWrapper<St, U, F, T> {
146    hnd: F,
147    _t: PhantomData<(St, U, T)>,
148}
149
150impl<St, U, F, T> HandlerWrapper<St, U, F, T>
151where
152    F: Handler<St, T> + 'static,
153    T: FromRequest<St> + 'static,
154    T::Error: WebResponseError<St, St::Error>,
155    St: State,
156    U: 'static,
157{
158    pub(super) fn create(hnd: F) -> Rc<dyn HandlerFn<St, U>> {
159        Rc::new(HandlerWrapper {
160            hnd,
161            _t: PhantomData,
162        })
163    }
164}
165
166impl<St, U, F, T> fmt::Debug for HandlerWrapper<St, U, F, T> {
167    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168        write!(f, "HandlerNoState({:?})", std::any::type_name::<F>())
169    }
170}
171
172impl<St, U, F, T> HandlerFn<St, U> for HandlerWrapper<St, U, F, T>
173where
174    F: Handler<St, T> + 'static,
175    T: FromRequest<St> + 'static,
176    T::Error: WebResponseError<St, St::Error>,
177    St: State,
178{
179    fn call<'a>(&'a self, st: &'a St, req: WebRequest<U>, fut: Pin<&mut HandlerFuture<'a>>) {
180        let (req, mut payload, _) = req.into_parts();
181        fut.set_with(|| async move {
182            let param = match T::from_request(st, &req, &mut payload).await {
183                Ok(param) => param,
184                Err(e) => return WebResponse::from_err(st, &e, req),
185            };
186
187            let result = self.hnd.call(param).await;
188            let response = result.respond_to(st, &req).await;
189            WebResponse::new(response, req)
190        });
191    }
192}
193
194/// `FromRequest` trait impl for tuples
195macro_rules! factory_tuple (
196    {$(#[$meta:meta])* $(($T:ident, $t:ident)),+} => {
197        $(#[$meta])*
198        impl<St, Func, U, $($T,)+ Res> HandlerSt<St, U, ($($T,)+)> for Func
199        where
200            St: State,
201            Func: 'static,
202            Func: AsyncFn(&St, U, $($T,)+) -> Res,
203            Res: Responder<St>,
204        {
205            type Output = Res;
206
207            async fn call(&self, st: &St, req: U, ($($t,)+): ($($T,)+)) -> Self::Output {
208                (self)(st, req, $($t,)+).await
209            }
210        }
211    }
212);
213
214macro_rules! factory_tuple_no_state (
215    {$(#[$meta:meta])* $(($T:ident, $t:ident)),+} => {
216        $(#[$meta])*
217        impl<St, Func, $($T,)+ Res> Handler<St, ($($T,)+)> for Func
218        where
219            St: State,
220            Func: 'static,
221            Func: AsyncFn($($T,)+) -> Res,
222            Res: Responder<St>,
223        {
224            type Output = Res;
225
226            async fn call(&self, ($($t,)+): ($($T,)+)) -> Self::Output {
227                (self)($($t,)+).await
228            }
229        }
230    }
231);
232
233#[allow(clippy::wildcard_imports)]
234#[rustfmt::skip]
235mod m {
236    use super::*;
237    use variadics_please::all_tuples;
238
239    // Can't use #[doc(fake_variadic)] here
240    all_tuples!(factory_tuple, 1, 16, T, t);
241
242    all_tuples!(factory_tuple_no_state, 1, 16, T, t);
243}