Skip to main content

ntex_service/
lib.rs

1//! Asynchronous services, factories, middleware, and execution pipelines.
2//!
3//! The [`Service`] trait is the crate's central abstraction. A service
4//! asynchronously transforms a request into a response, while
5//! [`ServiceFactory`] constructs services and [`Pipeline`] manages readiness,
6//! calls, and shutdown.
7#![deny(clippy::pedantic)]
8#![allow(
9    clippy::cast_possible_truncation,
10    clippy::missing_fields_in_debug,
11    clippy::missing_errors_doc,
12    clippy::missing_panics_doc,
13    clippy::must_use_candidate,
14    clippy::type_complexity,
15    clippy::unused_async,
16    clippy::unused_async_trait_impl
17)]
18use std::rc::Rc;
19
20mod and_then;
21mod apply;
22mod bind;
23mod binding;
24pub mod boxed;
25pub mod cfg;
26mod chain;
27mod ctx;
28mod fn_ready;
29mod fn_service;
30mod fn_shutdown;
31mod inline;
32mod macros;
33mod map;
34mod map_err;
35mod map_init_err;
36mod map_state;
37mod middleware;
38mod readiness;
39mod ready;
40mod ready_call;
41pub mod state;
42mod then;
43mod util;
44
45pub mod pipeline;
46mod pl_factory;
47mod pl_inner;
48mod pl_state;
49
50pub use crate::apply::{apply_fn, apply_fn_factory};
51pub use crate::bind::BindCtx;
52pub use crate::binding::{ReadyBinding, ReadyBindingMiddleware};
53pub use crate::chain::{ServiceChain, ServiceChainFactory, factory, service};
54pub use crate::ctx::Ctx;
55pub use crate::fn_service::{fn_factory, fn_service, fn_service_st};
56pub use crate::map_state::{map_state, map_state_factory};
57pub use crate::middleware::{Identity, Middleware, Stack, apply, fn_layer};
58pub use crate::pipeline::Pipeline;
59pub use crate::readiness::{ReadyCallback, ReadyLink, ReadyNotifier};
60pub use crate::ready::{ready, ready_factory};
61pub use crate::state::{RequestState, State};
62
63#[allow(unused_variables)]
64/// An asynchronous operation from a request to a response.
65///
66/// A service receives requests and asynchronously produces responses.
67/// Conceptually, it is similar to:
68///
69/// ```rust,ignore
70/// async fn(Request) -> Result<Response, Error>
71/// ```
72///
73/// The request and pipeline-state types are generic parameters. The response
74/// and error types are associated types, allowing one service type to implement
75/// `Service` for multiple request types.
76///
77/// Methods take `&self`, so implementations that mutate internal state must use
78/// interior mutability such as `Cell`, `RefCell`, or a synchronization
79/// primitive when appropriate.
80///
81/// The same abstraction can represent client- and server-side operations.
82/// Services focus on transformation, making them straightforward to test and
83/// compose.
84///
85/// A service call requires a [`Ctx`] and therefore runs through a [`Pipeline`]
86/// or from another service. The pipeline coordinates readiness across a
87/// composed service chain before dispatching a request.
88///
89/// ```rust
90/// # use std::convert::Infallible;
91/// #
92/// # use ntex_service::{Service, Ctx};
93///
94/// struct MyService;
95///
96/// impl Service<(), u8> for MyService {
97///     type Res = u64;
98///     type Error = Infallible;
99///
100///     async fn call(&self, req: u8, ctx: Ctx<'_, Self>) -> Result<Self::Res, Self::Error> {
101///         Ok(req as u64)
102///     }
103/// }
104/// ```
105///
106/// Simple services do not need a manual trait implementation. The example
107/// above can be expressed with [`fn_service`]:
108///
109/// ```rust
110/// # use std::convert::Infallible;
111/// # use ntex_service::{Pipeline, fn_service};
112/// #
113/// # async fn run() -> Result<(), Infallible> {
114/// let service = fn_service(|req: u8| async move {
115///     Ok::<_, Infallible>(u64::from(req))
116/// });
117/// let pipeline = Pipeline::new((), service);
118///
119/// assert_eq!(pipeline.call(10).await?, 10);
120/// # Ok(())
121/// # }
122/// ```
123///
124/// # Wrapping services
125///
126/// The default [`Self::bind`], [`Self::ready`], and [`Self::shutdown`] bodies
127/// are only suitable for leaf services. A wrapper that owns another service and
128/// implements only [`Self::call`] still compiles, but its child is never bound,
129/// child readiness errors and capacity limits are bypassed, child readiness
130/// notifications never invalidate the wrapper's cached readiness, and the child
131/// is never shut down.
132///
133/// Prefer helpers that forward the whole lifecycle:
134///
135/// - [`fn_layer`] or [`apply_fn`] for wrappers that only adapt calls;
136///   `ntex::web::middleware::from_fn` is the equivalent for web middleware.
137/// - [`forward!`] for manual implementations with one or several service fields.
138/// - [`Pipeline::bind_to`] in [`Self::bind`] for [`Pipeline`] fields.
139///
140/// Otherwise implement all three methods: bind every child with
141/// [`BindCtx::bind`], check each child with [`Ctx::ready`], and shut each child
142/// down with [`Ctx::shutdown`]. A wrapper that adds its own readiness, such as a
143/// capacity limit, must also subscribe a [`ReadyNotifier`] in [`Self::bind`] and
144/// notify it on every change; waking a task does not invalidate cached success.
145///
146/// # Framework guide
147///
148/// - [Service Model](https://docs.ntex.rs/1-service.html)
149/// - [Service Pipelines](https://docs.ntex.rs/2-pipeline.html)
150/// - [Service State](https://docs.ntex.rs/3-state.html)
151#[diagnostic::on_unimplemented(
152    message = "`{Self}` is not a `Service<{St}, {Req}>`",
153    label = "expected a service for `{Req}` requests with `{St}` state",
154    note = "the state type comes first: `impl Service<St, Req> for T`; use `()` for no state",
155    note = "check that `St` and `Req` match the pipeline or parent service exactly",
156    note = "wrap async functions with `fn_service` (`async |req| ..`) or `fn_service_st` (`async |st, req| ..`)"
157)]
158pub trait Service<St, Req> {
159    /// Response produced by the service.
160    type Res;
161
162    /// Error produced while checking readiness or processing a request.
163    type Error;
164
165    /// Processes a request and asynchronously returns the response.
166    ///
167    /// The enclosing pipeline checks readiness before invoking this method.
168    /// Implementations should not call their own `ready` method. A composed
169    /// service can use [`Ctx::call`] to call an inner service using the closest
170    /// upstream readiness cache. A service wrapped with [`ready()`] can be
171    /// called directly to check its own cache instead.
172    async fn call(&self, req: Req, ctx: Ctx<'_, Self, St>) -> Result<Self::Res, Self::Error>;
173
174    #[inline]
175    /// Initializes the service within a [`Pipeline`].
176    ///
177    /// Called during pipeline construction or [`Ctx::create`], before runtime
178    /// operations on the new service.
179    ///
180    /// The default is suitable for leaves without notification sources.
181    /// Composites must bind every existing child, and services with changing
182    /// readiness must subscribe to all their sources here. Lazily created
183    /// children must be initialized through [`Ctx::create`], which binds them
184    /// explicitly before use.
185    /// Register reusable [`ReadyCallback`] handles with [`BindCtx::on_notify`]
186    /// to observe notifications reaching the service's scope.
187    ///
188    /// Binding is synchronous. Shared services can be bound to multiple parents;
189    /// implementations must support repeated binding.
190    /// [`forward!`] forwards to one or several service fields. Register [`Pipeline`] fields with [`Pipeline::bind_to`].
191    /// Ordinary readiness checks, calls, and shutdown do not add dependencies.
192    fn bind(&self, ctx: BindCtx<'_>) {}
193
194    #[inline]
195    /// Waits until the service is ready to process a request.
196    ///
197    /// If the service is at capacity, the returned future remains pending until
198    /// capacity becomes available.
199    ///
200    /// Pipeline readiness is coordinated across all services in a composed
201    /// chain. A request is dispatched only when the chain is ready.
202    ///
203    /// A [`Pipeline`] or [`ReadyBinding`] caches success until a subscribed
204    /// [`ReadyNotifier`] invalidates it; calls do not consume that success.
205    /// Subscribe in [`Self::bind`] and notify on every readiness-changing
206    /// transition, including consuming or releasing capacity and external
207    /// failures, before another caller can use stale cached readiness.
208    /// A task wake schedules a pending check but does not invalidate a cached
209    /// success. Services must not rely on this method being polled on every
210    /// call to drive background progress.
211    ///
212    /// Readiness checks and their wake sources run on the pipeline's thread.
213    /// This local-only requirement does not apply to task wakers supplied to
214    /// [`Self::call`] or [`Self::shutdown`].
215    ///
216    /// Readiness may inspect [`Ctx::st`], but it describes the shared gate, not
217    /// a reservation for one request or state value. State-taking pipeline
218    /// handles share the same cache; independent gates need separate pipelines
219    /// or service bindings.
220    fn ready(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = Result<(), Self::Error>> {
221        // Unlike an `async fn`, the default future does not store its arguments.
222        async { Ok(()) }
223    }
224
225    #[inline]
226    /// Shuts down the service.
227    ///
228    /// Returns when the service has been properly shut down.
229    fn shutdown(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = ()> {
230        // Unlike an `async fn`, the default future does not store its arguments.
231        async {}
232    }
233
234    #[inline]
235    /// Maps this service's output to a different type, returning a new service.
236    ///
237    /// This is similar to `Option::map` or `Iterator::map`, changing the
238    /// output type of the underlying service.
239    ///
240    /// This function consumes the original service and returns a wrapped version,
241    /// following the pattern of standard library `map` methods.
242    fn map<F, Res>(self, f: F) -> ServiceChain<dev::Map<F, Self, Res>, St, Req>
243    where
244        Self: Sized,
245        F: Fn(Self::Res) -> Res,
246    {
247        service(dev::Map::new(f, self))
248    }
249
250    #[inline]
251    /// Maps this service's error to a different type, returning a new service.
252    ///
253    /// This is similar to `Result::map_err`, changing the error type of the
254    /// underlying service. It is useful, for example, to ensure multiple
255    /// services have the same error type.
256    ///
257    /// This function consumes the original service and returns a wrapped version.
258    fn map_err<F, E>(self, f: F) -> ServiceChain<dev::MapErr<F, Self, E>, St, Req>
259    where
260        Self: Sized,
261        F: Fn(Self::Error) -> E,
262    {
263        service(dev::MapErr::new(f, self))
264    }
265
266    #[inline]
267    /// Calls another service after this service completes successfully.
268    ///
269    /// The first service's response becomes the second service's request. If
270    /// the first service returns an error, the second service is not called.
271    fn and_then<Next, F>(self, f: F) -> ServiceChain<dev::AndThen<Self, Next>, St, Req>
272    where
273        Self: Sized,
274        Next: Service<St, Self::Res, Error = Self::Error>,
275        F: IntoService<Next, St, Self::Res>,
276    {
277        service(dev::AndThen::new(self, f.into_service()))
278    }
279
280    #[inline]
281    /// Wraps this service and its state in a [`Pipeline`].
282    fn pipeline(self, st: St) -> Pipeline<Req, Self::Res, Self::Error>
283    where
284        Self: Sized + 'static,
285        St: 'static,
286        Req: 'static,
287    {
288        Pipeline::new(st, self)
289    }
290}
291
292/// A factory for asynchronously creating [`Service`] values.
293///
294/// This is useful when new `Service`s must be produced dynamically. For example,
295/// a TCP server listener accepts new connections, constructs a new `Service` for
296/// each connection using the `ServiceFactory` trait, and uses that service to
297/// handle inbound requests.
298///
299/// `St` is the state type shared by the factory and its services.
300///
301/// Simple factories can often use [`fn_factory`] to reduce boilerplate.
302#[diagnostic::on_unimplemented(
303    message = "`{Self}` is not a `ServiceFactory<{St}, {Req}>`",
304    label = "expected a factory of services for `{Req}` requests with `{St}` state",
305    note = "the state type comes first: `impl ServiceFactory<St, Req> for T`; use `()` for no state",
306    note = "a `Service` is not a factory; use `fn_factory(async |st| Ok(service))` to create it per pipeline",
307    note = "async functions `async |req| ..` and `async |st, req| ..` convert into factories automatically"
308)]
309pub trait ServiceFactory<St, Req> {
310    /// Response produced by the created services.
311    type Res;
312
313    /// Error produced by the created services.
314    type Error;
315
316    /// The type of `Service` produced by this factory.
317    type Service: Service<St, Req, Res = Self::Res, Error = Self::Error>;
318
319    /// Error that can occur while constructing a service.
320    type InitError;
321
322    /// Asynchronously creates a service using the supplied state.
323    async fn create(&self, st: &St) -> Result<Self::Service, Self::InitError>;
324
325    #[inline]
326    /// Creates a service and wraps it with its state in a [`Pipeline`].
327    async fn pipeline(
328        &self,
329        st: St,
330    ) -> Result<Pipeline<Req, Self::Res, Self::Error>, Self::InitError>
331    where
332        Self: 'static,
333        St: 'static,
334        Req: 'static,
335    {
336        let svc = self.create(&st).await?;
337        Ok(Pipeline::new(st, svc))
338    }
339
340    #[inline]
341    /// Returns a factory whose services map responses to a different type.
342    fn map<F, Res>(self, f: F) -> ServiceChainFactory<dev::MapFactory<F, Self, Res>, St, Req>
343    where
344        Self: Sized,
345        F: Fn(Self::Res) -> Res + Clone,
346    {
347        factory(dev::MapFactory::new(f, self))
348    }
349
350    #[inline]
351    /// Returns a factory whose services map errors to a different type.
352    fn map_err<F, E>(self, f: F) -> ServiceChainFactory<dev::MapErrFactory<F, Self, E>, St, Req>
353    where
354        Self: Sized,
355        F: Fn(Self::Error) -> E + Clone,
356    {
357        factory(dev::MapErrFactory::new(f, self))
358    }
359
360    #[inline]
361    /// Maps this factory's initialization error to a different error,
362    /// returning a new service factory.
363    fn map_init_err<F, E>(self, f: F) -> ServiceChainFactory<dev::MapInitErr<F, Self, E>, St, Req>
364    where
365        Self: Sized,
366        F: Fn(Self::InitError) -> E + Clone,
367    {
368        factory(dev::MapInitErr::new(f, self))
369    }
370
371    /// Chains another factory after this factory's services.
372    ///
373    /// Each response from the first service becomes a request to the second
374    /// service. The second service is not called when the first returns an
375    /// error.
376    fn and_then<U, F>(self, f: F) -> ServiceChainFactory<dev::AndThenFactory<Self, U>, St, Req>
377    where
378        Self: Sized,
379        U: ServiceFactory<St, Self::Res, Error = Self::Error, InitError = Self::InitError>,
380        F: IntoServiceFactory<U, St, Self::Res>,
381    {
382        factory(dev::AndThenFactory::new(self, f.into_factory()))
383    }
384
385    /// Creates a boxed service factory.
386    fn boxed(self) -> boxed::BoxServiceFactory<St, Req, Self::Res, Self::Error, Self::InitError>
387    where
388        St: 'static,
389        Req: 'static,
390        Self: Sized + 'static,
391    {
392        boxed::factory(self)
393    }
394}
395
396impl<S, St, Req> Service<St, Req> for &S
397where
398    S: Service<St, Req>,
399{
400    type Res = S::Res;
401    type Error = S::Error;
402
403    fn bind(&self, ctx: BindCtx<'_>) {
404        ctx.bind(&**self);
405    }
406
407    #[inline]
408    fn ready(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = Result<(), S::Error>> {
409        Service::ready(&**self, ctx.cast())
410    }
411
412    #[inline]
413    fn call(
414        &self,
415        req: Req,
416        ctx: Ctx<'_, Self, St>,
417    ) -> impl Future<Output = Result<S::Res, S::Error>> {
418        Service::call(&**self, req, ctx.cast())
419    }
420
421    #[inline]
422    fn shutdown(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = ()> {
423        Service::shutdown(&**self, ctx.cast())
424    }
425}
426
427impl<S, St, Req> Service<St, Req> for Box<S>
428where
429    S: Service<St, Req>,
430{
431    type Res = S::Res;
432    type Error = S::Error;
433
434    fn bind(&self, ctx: BindCtx<'_>) {
435        ctx.bind(&**self);
436    }
437
438    #[inline]
439    fn ready(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = Result<(), S::Error>> {
440        Service::ready(&**self, ctx.cast())
441    }
442
443    #[inline]
444    fn call(
445        &self,
446        req: Req,
447        ctx: Ctx<'_, Self, St>,
448    ) -> impl Future<Output = Result<S::Res, S::Error>> {
449        Service::call(&**self, req, ctx.cast())
450    }
451
452    #[inline]
453    fn shutdown(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = ()> {
454        Service::shutdown(&**self, ctx.cast())
455    }
456}
457
458impl<S, St, Req> Service<St, Req> for Rc<S>
459where
460    S: Service<St, Req>,
461{
462    type Res = S::Res;
463    type Error = S::Error;
464
465    fn bind(&self, ctx: BindCtx<'_>) {
466        ctx.bind(&**self);
467    }
468
469    #[inline]
470    fn ready(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = Result<(), S::Error>> {
471        Service::ready(&**self, ctx.cast())
472    }
473
474    #[inline]
475    fn call(
476        &self,
477        req: Req,
478        ctx: Ctx<'_, Self, St>,
479    ) -> impl Future<Output = Result<S::Res, S::Error>> {
480        Service::call(&**self, req, ctx.cast())
481    }
482
483    #[inline]
484    fn shutdown(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = ()> {
485        Service::shutdown(&**self, ctx.cast())
486    }
487}
488
489impl<Sf, St, Req> ServiceFactory<St, Req> for Rc<Sf>
490where
491    Sf: ServiceFactory<St, Req>,
492{
493    type Res = Sf::Res;
494    type Error = Sf::Error;
495    type Service = Sf::Service;
496    type InitError = Sf::InitError;
497
498    async fn create(&self, st: &St) -> Result<Self::Service, Self::InitError> {
499        self.as_ref().create(st).await
500    }
501}
502
503/// A common interface for values that can call a service.
504pub trait ServiceCaller<Req, Res, Err> {
505    /// Waits for readiness, then calls the service.
506    async fn call_service(&self, req: Req) -> Result<Res, Err>;
507}
508
509/// Conversion into a [`Service`].
510#[diagnostic::on_unimplemented(
511    message = "`{Self}` cannot be converted into a `Service<{St}, {Req}>`",
512    label = "expected a service or an async function for `{Req}` requests",
513    note = "accepted values: a `Service<{St}, {Req}>`, `async |req: {Req}| -> Result<Res, Err>`, or `async |st: &{St}, req: {Req}| -> Result<Res, Err>`",
514    note = "async functions must return `Result`"
515)]
516pub trait IntoService<S, St, Req>
517where
518    S: Service<St, Req>,
519{
520    /// Converts this value into a service.
521    fn into_service(self) -> S;
522}
523
524/// Conversion into a [`ServiceFactory`].
525#[diagnostic::on_unimplemented(
526    message = "`{Self}` cannot be converted into a `ServiceFactory<{St}, {Req}>`",
527    label = "expected a service factory or an async function for `{Req}` requests",
528    note = "accepted values: a `ServiceFactory<{St}, {Req}>`, a `Clone` async function `async |req: {Req}| -> Result<Res, Err>` or `async |st: &{St}, req: {Req}| -> Result<Res, Err>`, or `async |st: &{St}| -> Result<impl Service, Err>`",
529    note = "a `Service` value is not a factory; wrap its construction with `fn_factory`"
530)]
531pub trait IntoServiceFactory<Sf, St, Req>
532where
533    Sf: ServiceFactory<St, Req>,
534{
535    /// Converts this value into a service factory.
536    fn into_factory(self) -> Sf;
537}
538
539impl<S, St, Req> IntoService<S, St, Req> for S
540where
541    S: Service<St, Req>,
542{
543    #[inline]
544    fn into_service(self) -> S {
545        self
546    }
547}
548
549impl<Sf, St, Req> IntoServiceFactory<Sf, St, Req> for Sf
550where
551    Sf: ServiceFactory<St, Req>,
552{
553    #[inline]
554    fn into_factory(self) -> Sf {
555        self
556    }
557}
558
559/// Combinator and helper types used by the public API.
560///
561/// Most services can be built through the crate-level functions and the
562/// [`Service`] and [`ServiceFactory`] methods without naming these types.
563/// This module exposes their concrete return types for type annotations,
564/// reusable wrappers, and custom composition.
565///
566/// - [`ServiceChain`] and [`ServiceChainFactory`] are builders returned by
567///   [`service()`] and [`factory()`].
568/// - [`dev::FnService`], [`dev::FnServiceSt`], and [`dev::FnFactory`] adapt
569///   functions into services and factories.
570/// - [`dev::AndThen`], [`dev::Then`], [`dev::Map`], and [`dev::MapErr`] compose
571///   or transform service results, with corresponding factory adapters.
572/// - [`dev::ApplyCtx`] provides state and inner-service calls to
573///   [`apply_fn`] middleware; [`dev::MapState`] substitutes the inner state.
574/// - [`dev::Ready`] and [`dev::ReadyFactory`] are the wrappers produced by
575///   [`ready()`] and [`ready_factory()`] for independent cached readiness.
576///
577/// # Framework guide
578///
579/// - [Service Pipelines](https://docs.ntex.rs/2-pipeline.html)
580/// - [Service State](https://docs.ntex.rs/3-state.html)
581#[doc(hidden)]
582pub mod __private {
583    pub use crate::readiness::Generation;
584    pub use crate::util::{join, map_output, ready_field, ready_join};
585}
586
587pub mod dev {
588    pub use crate::and_then::{AndThen, AndThenFactory};
589    pub use crate::apply::{Apply, ApplyCtx, ApplyFactory};
590    pub use crate::chain::{ServiceChain, ServiceChainFactory};
591    pub use crate::fn_ready::FnReadiness;
592    pub use crate::fn_service::{FnFactory, FnService, FnServiceSt, FnServiceStFactory};
593    pub use crate::fn_shutdown::FnShutdown;
594    pub use crate::inline::InlineFuture;
595    pub use crate::map::{Map, MapFactory};
596    pub use crate::map_err::{MapErr, MapErrFactory};
597    pub use crate::map_init_err::MapInitErr;
598    pub use crate::map_state::{MapState, MapStateFactory};
599    pub use crate::middleware::{ApplyMiddleware, FnMiddleware};
600    pub use crate::ready::{Ready, ReadyFactory};
601    pub use crate::then::{Then, ThenFactory};
602}
603
604#[cfg(test)]
605#[path = "../tests/unit/lib.rs"]
606mod tests;