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