Skip to main content

ntex_service/
apply.rs

1use std::{fmt, marker};
2
3use crate::{BindCtx, Ctx, IntoService, IntoServiceFactory, Service, ServiceFactory, util};
4use crate::{ServiceCaller, ServiceChain, ServiceChainFactory};
5
6/// Applies an asynchronous middleware function to a service.
7///
8/// The function receives an input request and an [`ApplyCtx`] with access to
9/// the pipeline state and inner service. It can adapt the request, transform
10/// the response or error, and decide whether and how often to call the inner
11/// service. The state type stays the same; the request, response, and error
12/// types can differ from those of the inner service.
13///
14/// Returns a [`ServiceChain`] containing an [`Apply`] service. Binding and
15/// shutdown are forwarded to the inner service. Readiness is also forwarded,
16/// with inner readiness errors converted into the middleware's error type
17/// through [`From`]. Errors from [`ApplyCtx::call`] retain the inner error
18/// type, so the middleware can handle or convert them.
19///
20/// # Readiness
21///
22/// The enclosing pipeline checks readiness before invoking the middleware.
23/// [`ApplyCtx::call`] forwards directly to the inner service; it does not add
24/// another readiness check for a raw service. Wrap the inner service with
25/// [`crate::ready()`] when calls need their own readiness check, including
26/// after the middleware awaits other work or makes an earlier call.
27///
28/// # Example
29///
30/// ```
31/// use ntex_service::{Service, apply_fn, fn_service};
32///
33/// # async fn example() -> Result<(), ()> {
34/// let service = apply_fn(
35///     fn_service(async |req: u32| Ok::<_, ()>(req + 1)),
36///     async |req: &str, ctx| {
37///         let value = req.parse::<u32>().map_err(|_| ())?;
38///         let response = ctx.call(value).await?;
39///         Ok::<_, ()>(response.to_string())
40///     },
41/// );
42/// let pipeline = service.pipeline(());
43/// assert_eq!(pipeline.call("41").await?, "42");
44/// # Ok(())
45/// # }
46/// ```
47///
48/// See the framework guide's [Service Pipelines](https://docs.ntex.rs/2-pipeline.html)
49/// chapter for composition and readiness semantics.
50pub fn apply_fn<S, St, Req, F, In, Out, Err>(
51    service: impl IntoService<S, St, Req>,
52    f: F,
53) -> ServiceChain<Apply<S, St, Req, F, In, Out, Err>, St, In>
54where
55    S: Service<St, Req>,
56    F: AsyncFn(In, &ApplyCtx<'_, S, St, Req>) -> Result<Out, Err>,
57    Err: From<S::Error>,
58{
59    crate::service(Apply::new(service.into_service(), f))
60}
61
62/// Applies an asynchronous middleware function to every service from a factory.
63///
64/// Returns a [`ServiceChainFactory`] containing an [`ApplyFactory`]. Each
65/// successful creation wraps the new inner service with a clone of the
66/// middleware function. The inner factory receives the same state and its
67/// initialization errors are returned unchanged.
68///
69/// The resulting services use the call, binding, readiness, and shutdown
70/// behavior described in [`apply_fn`]. To give each created inner service its
71/// own readiness cache, wrap the inner factory with [`crate::ready_factory()`].
72///
73/// # Example
74///
75/// ```
76/// use ntex_service::{ServiceFactory, apply_fn_factory, fn_factory, fn_service};
77///
78/// # async fn example() -> Result<(), ()> {
79/// let factory = apply_fn_factory(
80///     fn_factory(async |offset: &u32| {
81///         let offset = *offset;
82///         Ok::<_, ()>(fn_service(async move |req: u32| Ok::<_, ()>(req + offset)))
83///     }),
84///     async |req: u8, ctx| ctx.call(u32::from(req)).await,
85/// );
86/// let pipeline = factory.pipeline(10).await?;
87/// assert_eq!(pipeline.call(2).await?, 12);
88/// # Ok(())
89/// # }
90/// ```
91pub fn apply_fn_factory<Sf, St, Req, F, In, Out, Err>(
92    service: impl IntoServiceFactory<Sf, St, Req>,
93    f: F,
94) -> ServiceChainFactory<ApplyFactory<F, Sf, St, Req, In, Out, Err>, St, In>
95where
96    Sf: ServiceFactory<St, Req>,
97    F: AsyncFn(In, &ApplyCtx<'_, Sf::Service, St, Req>) -> Result<Out, Err> + Clone,
98    Err: From<Sf::Error>,
99{
100    crate::factory(ApplyFactory::new(service.into_factory(), f))
101}
102
103#[derive(Debug)]
104/// State and inner-service access for [`apply_fn`] and [`apply_fn_factory`] middleware.
105///
106/// [`Self::st`] borrows the current pipeline state, and [`Self::call`] invokes
107/// the inner service with that state. The context also implements
108/// [`ServiceCaller`], with the same call behavior.
109///
110/// Calls forward directly to the inner service. Wrap it with [`crate::ready()`]
111/// to check its independent readiness on each call, including after middleware
112/// awaits or makes another call. The context borrows both the state and the
113/// inner service for the middleware invocation.
114pub struct ApplyCtx<'a, S, St, Req> {
115    ctx: Ctx<'a, S, St>,
116    service: &'a S,
117    r: marker::PhantomData<Req>,
118}
119
120impl<S: Service<St, Req>, St, Req> ApplyCtx<'_, S, St, Req> {
121    /// Returns the pipeline state.
122    ///
123    /// Inner calls made through this context receive the same state reference.
124    #[inline]
125    pub fn st(&self) -> &St {
126        self.ctx.st()
127    }
128
129    /// Calls the inner service, preserving any explicit readiness wrapper.
130    ///
131    /// This does not independently check readiness for a raw inner service.
132    /// An inner [`crate::ready()`] wrapper still checks its own readiness
133    /// cache.
134    ///
135    /// Returns the inner response and error types without applying the outer
136    /// middleware's conversions.
137    #[inline]
138    pub fn call(&self, req: Req) -> impl Future<Output = Result<S::Res, S::Error>> {
139        self.service.call(req, self.ctx.cast())
140    }
141}
142
143impl<S: Service<St, Req>, St, Req> ServiceCaller<Req, S::Res, S::Error>
144    for ApplyCtx<'_, S, St, Req>
145{
146    #[inline]
147    fn call_service(&self, req: Req) -> impl Future<Output = Result<S::Res, S::Error>> {
148        self.call(req)
149    }
150}
151
152/// Middleware service constructed by [`apply_fn`] or [`ApplyFactory`].
153///
154/// Calls invoke the middleware function with an [`ApplyCtx`]. Binding and
155/// shutdown are forwarded to the inner service, and readiness errors are
156/// converted into the middleware's error type.
157///
158/// Shares the enclosing readiness scope with its child unless the child has
159/// its own readiness cache, for example through [`crate::ready()`].
160///
161/// Cloning clones both the inner service and middleware function. Whether
162/// those clones share state or readiness depends on the inner service's
163/// clone behavior.
164pub struct Apply<S, St, Req, F, In, Out, Err> {
165    svc: S,
166    f: F,
167    r: marker::PhantomData<fn(St, Req) -> (In, Out, Err)>,
168}
169
170impl<S, St, Req, F, In, Out, Err> Apply<S, St, Req, F, In, Out, Err>
171where
172    F: AsyncFn(In, &ApplyCtx<'_, S, St, Req>) -> Result<Out, Err>,
173{
174    pub(crate) fn new(svc: S, f: F) -> Self {
175        Apply {
176            f,
177            svc,
178            r: marker::PhantomData,
179        }
180    }
181}
182
183impl<S, St, Req, F, In, Out, Err> Clone for Apply<S, St, Req, F, In, Out, Err>
184where
185    S: Clone,
186    F: Clone,
187{
188    fn clone(&self) -> Self {
189        Apply {
190            svc: self.svc.clone(),
191            f: self.f.clone(),
192            r: marker::PhantomData,
193        }
194    }
195}
196
197impl<S, St, Req, F, In, Out, Err> fmt::Debug for Apply<S, St, Req, F, In, Out, Err>
198where
199    S: fmt::Debug,
200{
201    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
202        f.debug_struct("Apply")
203            .field("svc", &self.svc)
204            .field("map", &std::any::type_name::<F>())
205            .finish()
206    }
207}
208
209impl<S, St, Req, F, In, Out, Err> Service<St, In> for Apply<S, St, Req, F, In, Out, Err>
210where
211    S: Service<St, Req>,
212    F: AsyncFn(In, &ApplyCtx<'_, S, St, Req>) -> Result<Out, Err>,
213    Err: From<S::Error>,
214{
215    type Res = Out;
216    type Error = Err;
217
218    #[inline]
219    fn ready(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = Result<(), Err>> {
220        util::map_output(ctx.ready(&self.svc), |res| res.map_err(From::from))
221    }
222
223    #[inline]
224    #[allow(clippy::manual_async_fn)]
225    fn call(&self, req: In, ctx: Ctx<'_, Self, St>) -> impl Future<Output = Result<Out, Err>> {
226        // An `async fn` would store `req` and `ctx` twice. The block is needed
227        // because the call future borrows the local `ApplyCtx`.
228        async move {
229            let ctx = ApplyCtx {
230                ctx: ctx.cast(),
231                service: &self.svc,
232                r: marker::PhantomData,
233            };
234            (self.f)(req, &ctx).await
235        }
236    }
237
238    #[inline]
239    fn bind(&self, ctx: BindCtx<'_>) {
240        ctx.bind(&self.svc);
241    }
242
243    #[inline]
244    fn shutdown(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = ()> {
245        ctx.shutdown(&self.svc)
246    }
247}
248
249/// Service factory produced by [`apply_fn_factory`].
250///
251/// Implements [`ServiceFactory`] by creating an inner service with the supplied
252/// state, then wrapping it in [`Apply`] with a clone of the middleware function.
253/// Initialization errors are those of the inner factory and are not converted
254/// into the middleware's call error type.
255///
256/// Cloning clones both the inner factory and middleware function; it does not
257/// create a service.
258pub struct ApplyFactory<F, Sf, St, Req, In, Out, Err>
259where
260    F: AsyncFn(In, &ApplyCtx<'_, Sf::Service, St, Req>) -> Result<Out, Err> + Clone,
261    Sf: ServiceFactory<St, Req>,
262{
263    f: F,
264    sf: Sf,
265    r: marker::PhantomData<fn(St, Req) -> (In, Out)>,
266}
267
268impl<F, Sf, St, Req, In, Out, Err> ApplyFactory<F, Sf, St, Req, In, Out, Err>
269where
270    F: AsyncFn(In, &ApplyCtx<'_, Sf::Service, St, Req>) -> Result<Out, Err> + Clone,
271    Sf: ServiceFactory<St, Req>,
272{
273    /// Creates a new `ApplyFactory`.
274    pub(crate) fn new(sf: Sf, f: F) -> Self
275    where
276        Sf: ServiceFactory<St, Req>,
277        Err: From<Sf::Error>,
278    {
279        Self {
280            f,
281            sf,
282            r: marker::PhantomData,
283        }
284    }
285}
286
287impl<F, Sf, St, Req, In, Out, Err> Clone for ApplyFactory<F, Sf, St, Req, In, Out, Err>
288where
289    F: AsyncFn(In, &ApplyCtx<'_, Sf::Service, St, Req>) -> Result<Out, Err> + Clone,
290    Sf: ServiceFactory<St, Req> + Clone,
291{
292    fn clone(&self) -> Self {
293        Self {
294            f: self.f.clone(),
295            sf: self.sf.clone(),
296            r: marker::PhantomData,
297        }
298    }
299}
300
301impl<F, Sf, St, Req, In, Out, Err> fmt::Debug for ApplyFactory<F, Sf, St, Req, In, Out, Err>
302where
303    F: AsyncFn(In, &ApplyCtx<'_, Sf::Service, St, Req>) -> Result<Out, Err> + Clone,
304    Sf: ServiceFactory<St, Req> + fmt::Debug,
305{
306    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
307        f.debug_struct("ApplyFactory")
308            .field("factory", &self.sf)
309            .field("map", &std::any::type_name::<F>())
310            .finish()
311    }
312}
313
314impl<F, Sf, St, Req, In, Out, Err> ServiceFactory<St, In>
315    for ApplyFactory<F, Sf, St, Req, In, Out, Err>
316where
317    F: AsyncFn(In, &ApplyCtx<'_, Sf::Service, St, Req>) -> Result<Out, Err> + Clone,
318    Sf: ServiceFactory<St, Req>,
319    Err: From<Sf::Error>,
320{
321    type Res = Out;
322    type Error = Err;
323
324    type Service = Apply<Sf::Service, St, Req, F, In, Out, Err>;
325    type InitError = Sf::InitError;
326
327    #[inline]
328    async fn create(&self, st: &St) -> Result<Self::Service, Self::InitError> {
329        self.sf
330            .create(st)
331            .await
332            .map(|svc| Apply::new(svc, self.f.clone()))
333    }
334}
335
336#[cfg(test)]
337#[path = "../tests/unit/apply.rs"]
338mod tests;