ntex_service/middleware.rs
1use std::{fmt, marker::PhantomData, rc::Rc};
2
3use crate::dev::{Apply, ApplyCtx};
4use crate::{IntoServiceFactory, Service, ServiceChainFactory, ServiceFactory};
5
6/// Applies middleware to every service produced by a factory.
7///
8/// Returns a [`ServiceChainFactory`] containing an [`ApplyMiddleware`].
9/// Creation first awaits the inner factory, then calls [`Middleware::create`]
10/// synchronously with the new service and the same state reference. If the
11/// factory fails, its initialization error is returned without invoking the
12/// middleware.
13///
14/// To use the result as a [`ServiceFactory`], the middleware's service must
15/// accept the same state and request types as the inner service. Response and
16/// service-error types may change. The wrapper is responsible for forwarding
17/// calls, binding, readiness, and shutdown as appropriate.
18///
19/// Cloning the resulting factory shares the middleware and inner factory
20/// through [`Rc`]; neither needs to implement [`Clone`].
21///
22/// # Example
23///
24/// ```
25/// use ntex_service::{Identity, apply, fn_factory, fn_service};
26///
27/// # async fn example() -> Result<(), ()> {
28/// let factory = apply(
29/// Identity,
30/// fn_factory(async |offset: &u32| {
31/// let offset = *offset;
32/// Ok::<_, ()>(fn_service(async move |req: u32| Ok::<_, ()>(req + offset)))
33/// }),
34/// );
35///
36/// let pipeline = factory.pipeline(10).await?;
37/// assert_eq!(pipeline.call(2).await?, 12);
38/// # Ok(())
39/// # }
40/// ```
41pub fn apply<Sf, St, Req, M>(
42 mw: M,
43 factory: impl IntoServiceFactory<Sf, St, Req>,
44) -> ServiceChainFactory<ApplyMiddleware<M, Sf>, St, Req>
45where
46 Sf: ServiceFactory<St, Req>,
47 M: Middleware<Sf::Service, St>,
48{
49 ServiceChainFactory {
50 factory: ApplyMiddleware::new(mw, factory.into_factory()),
51 _t: PhantomData,
52 }
53}
54
55/// Wraps an inner service during service construction.
56///
57/// [`Self::create`] takes ownership of an already-created service and returns
58/// a wrapper synchronously and infallibly. The wrapper can run work before
59/// and after inner calls, transform requests, responses, or errors, or avoid
60/// calling the inner service.
61///
62/// Use [`apply()`], [`Self::apply_to`], or [`ServiceChainFactory::apply`] to
63/// install middleware on a factory. These require the wrapper to implement
64/// [`Service`] for the factory's state and request types. Direct use of
65/// [`Self::create`] can also construct wrappers with a different request type.
66///
67/// The state reference is available during construction. A service wrapper
68/// can access the current state on each call through [`crate::Ctx::st`].
69/// [`Rc`] middleware shares one middleware value across its clones, and
70/// [`Stack`] composes multiple wrappers.
71///
72/// # Lifecycle forwarding
73///
74/// Middleware must arrange the resulting service's lifecycle behavior.
75/// Wrappers retaining an inner service should forward [`Service::bind`] so
76/// its readiness notifications reach the enclosing pipeline, and forward or
77/// deliberately replace its readiness and shutdown behavior. These methods
78/// are not forwarded automatically by implementing this trait.
79///
80/// # Example
81///
82/// For example, timeout middleware:
83///
84/// ```rust
85/// use ntex_service::{Ctx, Service};
86/// use ntex::{time::sleep, util::Either, util::select};
87///
88/// pub struct Timeout<S> {
89/// service: S,
90/// timeout: std::time::Duration,
91/// }
92///
93/// pub enum TimeoutError<E> {
94/// Service(E),
95/// Timeout,
96/// }
97///
98/// impl<S, R> Service<(), R> for Timeout<S>
99/// where
100/// S: Service<(), R>,
101/// {
102/// type Res = S::Res;
103/// type Error = TimeoutError<S::Error>;
104///
105/// ntex_service::forward_bind!((), service);
106/// ntex_service::forward_shutdown!((), service);
107///
108/// async fn ready(&self, ctx: Ctx<'_, Self>) -> Result<(), Self::Error> {
109/// ctx.ready(&self.service).await.map_err(TimeoutError::Service)
110/// }
111///
112/// async fn call(&self, req: R, ctx: Ctx<'_, Self>) -> Result<Self::Res, Self::Error> {
113/// match select(sleep(self.timeout), ctx.call(&self.service, req)).await {
114/// Either::Left(_) => Err(TimeoutError::Timeout),
115/// Either::Right(res) => res.map_err(TimeoutError::Service),
116/// }
117/// }
118/// }
119/// ```
120///
121/// The timeout service is independent of the wrapped service implementation and
122/// can be applied to any compatible service.
123///
124/// Middleware that constructs `Timeout` could look like this:
125///
126/// ```rust
127/// # use ntex_service::Middleware;
128/// # pub struct Timeout<S> {
129/// # service: S,
130/// # timeout: std::time::Duration,
131/// # }
132/// pub struct TimeoutMiddleware {
133/// timeout: std::time::Duration,
134/// }
135///
136/// impl<S> Middleware<S, ()> for TimeoutMiddleware
137/// {
138/// type Service = Timeout<S>;
139///
140/// fn create(&self, _: &(), service: S) -> Self::Service {
141/// Timeout {
142/// service,
143/// timeout: self.timeout,
144/// }
145/// }
146/// }
147/// ```
148pub trait Middleware<S, St> {
149 /// Wrapper returned by [`Self::create`].
150 ///
151 /// Factory application requires this type to implement [`Service`] for
152 /// the factory's state and request types. Its response and error types
153 /// may differ from those of the inner service.
154 type Service;
155
156 /// Wraps `service` using the supplied construction state.
157 ///
158 /// This is synchronous and infallible. It does not bind or check readiness
159 /// of the returned service; those steps belong to the enclosing pipeline.
160 fn create(&self, st: &St, service: S) -> Self::Service;
161
162 /// Creates a service factory that instantiates a service and applies
163 /// the current middleware to it.
164 ///
165 /// This is equivalent to [`apply()`] with this middleware and `factory`.
166 /// The factory is awaited before invoking [`Self::create`] with the same
167 /// state reference. Initialization errors bypass the middleware.
168 ///
169 /// The middleware and factory are shared when the returned builder is
170 /// cloned; they do not need to implement [`Clone`].
171 fn apply_to<Sf, Req>(
172 self,
173 factory: Sf,
174 ) -> ServiceChainFactory<ApplyMiddleware<Self, Sf>, St, Req>
175 where
176 Sf: ServiceFactory<St, Req, Service = S>,
177 Self: Sized,
178 Self::Service: Service<St, Req>,
179 {
180 crate::factory(ApplyMiddleware::new(self, factory))
181 }
182}
183
184impl<M, S, St> Middleware<S, St> for Rc<M>
185where
186 M: Middleware<S, St>,
187{
188 type Service = M::Service;
189
190 fn create(&self, st: &St, service: S) -> M::Service {
191 self.as_ref().create(st, service)
192 }
193}
194
195/// A service factory with middleware applied.
196///
197/// Created by [`apply()`], [`Middleware::apply_to`], or
198/// [`ServiceChainFactory::apply`]. Each creation first awaits the inner
199/// factory, then wraps its service through [`Middleware::create`] with the
200/// same state reference.
201///
202/// The wrapper determines response and service-error types and is responsible
203/// for lifecycle forwarding. Inner initialization errors are returned
204/// unchanged without invoking the middleware.
205///
206/// Cloning shares both middleware and factory through [`Rc`] rather than
207/// cloning them or creating a service.
208pub struct ApplyMiddleware<M, Sf>(Rc<(M, Sf)>);
209
210impl<M, Sf> ApplyMiddleware<M, Sf> {
211 /// Creates a new `ApplyMiddleware` factory.
212 pub(crate) fn new(mw: M, sf: Sf) -> Self {
213 Self(Rc::new((mw, sf)))
214 }
215}
216
217impl<M, Sf> Clone for ApplyMiddleware<M, Sf> {
218 fn clone(&self) -> Self {
219 Self(self.0.clone())
220 }
221}
222
223impl<M, Sf> fmt::Debug for ApplyMiddleware<M, Sf>
224where
225 M: fmt::Debug,
226 Sf: fmt::Debug,
227{
228 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229 f.debug_struct("ApplyMiddleware")
230 .field("factory", &self.0.1)
231 .field("middleware", &self.0.0)
232 .finish()
233 }
234}
235
236impl<M, Sf, St, Req> ServiceFactory<St, Req> for ApplyMiddleware<M, Sf>
237where
238 Sf: ServiceFactory<St, Req>,
239 M: Middleware<Sf::Service, St>,
240 M::Service: Service<St, Req>,
241{
242 type Res = <M::Service as Service<St, Req>>::Res;
243 type Error = <M::Service as Service<St, Req>>::Error;
244
245 type Service = M::Service;
246 type InitError = Sf::InitError;
247
248 #[inline]
249 async fn create(&self, st: &St) -> Result<Self::Service, Self::InitError> {
250 Ok(self.0.0.create(st, self.0.1.create(st).await?))
251 }
252}
253
254/// Middleware that returns the wrapped service unchanged.
255///
256/// Construction ignores state and returns the exact input service without
257/// adding a wrapper, readiness cache, or lifecycle behavior. This is useful as
258/// a default middleware or a no-op component of a [`Stack`].
259#[derive(Debug, Clone, Copy)]
260pub struct Identity;
261
262impl<S, St> Middleware<S, St> for Identity {
263 type Service = S;
264
265 #[inline]
266 fn create(&self, _: &St, service: S) -> Self::Service {
267 service
268 }
269}
270
271/// Two middleware values applied in sequence.
272///
273/// Construction applies `inner` first, then `outer`, with the same state
274/// reference: the result is `outer(inner(service))`. Requests enter the outer
275/// wrapper first; if forwarded, they then pass through the inner wrapper to
276/// the service. Responses return through the inner wrapper before the outer.
277///
278/// The stack only composes construction. Lifecycle forwarding and whether
279/// calls reach the inner service are determined by each wrapper. Cloning
280/// clones both middleware values without constructing a service.
281///
282/// # Example
283///
284/// ```
285/// use ntex_service::{Middleware, Service, Stack, fn_layer, fn_service};
286///
287/// # async fn example() -> Result<(), ()> {
288/// let inner = fn_layer(async |req: u32, ctx| ctx.call(req + 1).await);
289/// let outer = fn_layer(async |req: u32, ctx| ctx.call(req * 2).await);
290/// let service = Stack::new(inner, outer)
291/// .create(&(), fn_service(async |req: u32| Ok::<_, ()>(req)));
292///
293/// let pipeline = service.pipeline(());
294/// assert_eq!(pipeline.call(2).await?, 5);
295/// # Ok(())
296/// # }
297/// ```
298#[derive(Debug, Clone)]
299pub struct Stack<Inner, Outer> {
300 inner: Inner,
301 outer: Outer,
302}
303
304impl<Inner, Outer> Stack<Inner, Outer> {
305 /// Stores two middleware values in inner-to-outer construction order.
306 ///
307 /// No service is created until [`Middleware::create`] is called. The
308 /// resulting outer wrapper receives requests before the inner wrapper.
309 pub fn new(inner: Inner, outer: Outer) -> Self {
310 Stack { inner, outer }
311 }
312}
313
314impl<S, St, Inner, Outer> Middleware<S, St> for Stack<Inner, Outer>
315where
316 Inner: Middleware<S, St>,
317 Outer: Middleware<Inner::Service, St>,
318{
319 type Service = Outer::Service;
320
321 fn create(&self, st: &St, service: S) -> Self::Service {
322 self.outer.create(st, self.inner.create(st, service))
323 }
324}
325
326#[doc(hidden)]
327/// Creates middleware from an asynchronous function.
328///
329/// The function receives an input request and an [`ApplyCtx`] that can call the
330/// wrapped service or access pipeline state. Each [`Middleware::create`] call
331/// clones the function into an [`Apply`] wrapper; it does not invoke it.
332///
333/// Request, response, and error types may change, while the state type stays
334/// the same. The middleware implementation requires `Err: From<S::Error>` to
335/// convert inner readiness errors. See [`crate::apply_fn`] for lifecycle and
336/// call-time readiness semantics.
337pub fn fn_layer<F, S, St, Req, In, Out, Err>(f: F) -> FnMiddleware<F, S, St, Req, In, Out, Err>
338where
339 F: AsyncFn(In, &ApplyCtx<'_, S, St, Req>) -> Result<Out, Err> + Clone,
340 S: Service<St, Req>,
341{
342 FnMiddleware { f, r: PhantomData }
343}
344
345/// Middleware backed by an asynchronous function.
346///
347/// Created by [`fn_layer`]. Each [`Middleware::create`] call wraps the supplied
348/// service in [`Apply`] with a clone of the function. The construction state
349/// is not captured automatically; the function accesses current pipeline state
350/// through [`ApplyCtx::st`].
351///
352/// The function controls whether and how often the inner service is called.
353/// Binding, readiness, and shutdown follow [`Apply`], including conversion of
354/// inner readiness errors through [`From`]. Cloning this middleware clones only
355/// the function, not an inner service.
356pub struct FnMiddleware<F, S, St, Req, In, Out, Err> {
357 f: F,
358 r: PhantomData<fn(S, St, Req) -> (In, Out, Err)>,
359}
360
361impl<F, S, St, Req, In, Out, Err> Clone for FnMiddleware<F, S, St, Req, In, Out, Err>
362where
363 F: Clone,
364{
365 fn clone(&self) -> Self {
366 FnMiddleware {
367 f: self.f.clone(),
368 r: PhantomData,
369 }
370 }
371}
372
373impl<F, S, St, Req, In, Out, Err> fmt::Debug for FnMiddleware<F, S, St, Req, In, Out, Err> {
374 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
375 f.debug_struct("FnMiddleware")
376 .field("layer", &std::any::type_name::<F>())
377 .finish()
378 }
379}
380
381impl<F, S, St, Req, In, Out, Err> Middleware<S, St> for FnMiddleware<F, S, St, Req, In, Out, Err>
382where
383 S: Service<St, Req>,
384 F: AsyncFn(In, &ApplyCtx<'_, S, St, Req>) -> Result<Out, Err> + Clone,
385 Err: From<S::Error>,
386{
387 type Service = Apply<S, St, Req, F, In, Out, Err>;
388
389 fn create(&self, _: &St, service: S) -> Self::Service {
390 Apply::new(service, self.f.clone())
391 }
392}
393
394#[cfg(test)]
395#[allow(clippy::redundant_clone)]
396#[path = "../tests/unit/middleware.rs"]
397mod tests;