ntex_service/chain.rs
1use std::{fmt, marker::PhantomData};
2
3use crate::and_then::{AndThen, AndThenFactory};
4use crate::apply::{Apply, ApplyCtx, ApplyFactory};
5use crate::fn_ready::FnReadiness;
6use crate::fn_shutdown::FnShutdown;
7use crate::map::{Map, MapFactory};
8use crate::map_err::{MapErr, MapErrFactory};
9use crate::map_init_err::MapInitErr;
10use crate::middleware::{ApplyMiddleware, Middleware};
11use crate::pipeline::Pipeline;
12use crate::then::{Then, ThenFactory};
13use crate::{BindCtx, ctx::Ctx};
14use crate::{IntoService, IntoServiceFactory, Service, ServiceFactory};
15
16/// Starts a [`ServiceChain`] with one service.
17///
18/// Converts the input through [`IntoService`] and returns a builder for
19/// composing calls, mapping results, and adding middleware. This does not
20/// create a pipeline or check readiness; use [`Service::pipeline`] to supply
21/// state and obtain a callable pipeline.
22///
23/// # Example
24///
25/// ```
26/// use ntex_service::{Service, fn_service, service};
27///
28/// # async fn example() -> Result<(), ()> {
29/// let pipeline = service(fn_service(async |req: u32| Ok::<_, ()>(req + 1)))
30/// .map(|value| value.to_string())
31/// .pipeline(());
32///
33/// assert_eq!(pipeline.call(41).await?, "42");
34/// # Ok(())
35/// # }
36/// ```
37pub fn service<S, St, Req>(service: impl IntoService<S, St, Req>) -> ServiceChain<S, St, Req>
38where
39 S: Service<St, Req>,
40{
41 ServiceChain {
42 service: service.into_service(),
43 st: PhantomData,
44 }
45}
46
47/// Starts a [`ServiceChainFactory`] with one service factory.
48///
49/// Converts the input through [`IntoServiceFactory`] without creating a
50/// service. Combinators configure how services will be created and composed.
51/// Use [`ServiceChainFactory::pipeline`] to create a service and bind it to
52/// its state, or [`ServiceFactory::create`] to obtain the service alone.
53///
54/// # Example
55///
56/// ```
57/// use ntex_service::{factory, fn_factory, fn_service};
58///
59/// # async fn example() -> Result<(), ()> {
60/// let factory = factory(fn_factory(async |offset: &u32| {
61/// let offset = *offset;
62/// Ok::<_, ()>(fn_service(async move |req: u32| Ok::<_, ()>(req + offset)))
63/// }))
64/// .and_then(fn_factory(async |_: &u32| {
65/// Ok::<_, ()>(fn_service(async |value: u32| Ok::<_, ()>(value * 2)))
66/// }));
67///
68/// let pipeline = factory.pipeline(10).await?;
69/// assert_eq!(pipeline.call(2).await?, 24);
70/// # Ok(())
71/// # }
72/// ```
73pub fn factory<Sf, St, Req>(
74 factory: impl IntoServiceFactory<Sf, St, Req>,
75) -> ServiceChainFactory<Sf, St, Req>
76where
77 Sf: ServiceFactory<St, Req>,
78{
79 ServiceChainFactory {
80 factory: factory.into_factory(),
81 _t: PhantomData,
82 }
83}
84
85/// A builder for composing services and combinators into one service.
86///
87/// Created by [`service()`] and service combinators. Each builder method
88/// consumes the chain and returns a new chain containing the added adapter.
89/// Use [`Self::and_then`] to process successful responses, [`Self::then`] to
90/// handle the complete result, or [`Self::apply_fn`] to wrap a call with
91/// asynchronous middleware.
92///
93/// The chain implements [`Service`] when its enclosed composition does.
94/// It owns the enclosed service but does not store pipeline state; supply
95/// state through [`Service::pipeline`].
96///
97/// Binding, calls, readiness, and shutdown are forwarded to the enclosed
98/// service. The builder adds no independent readiness cache. Raw children
99/// share the enclosing readiness scope; use [`crate::ready()`] around a child
100/// that needs its own cache and call-time readiness check.
101///
102/// Cloning clones the enclosed service. Shared state and readiness depend on
103/// that service's clone implementation.
104///
105/// See the framework guide's [Service Pipelines](https://docs.ntex.rs/2-pipeline.html)
106/// chapter for composition and readiness semantics.
107pub struct ServiceChain<S, St, Req> {
108 service: S,
109 st: PhantomData<(St, Req)>,
110}
111
112/// A builder for composing service factories and combinators.
113///
114/// Created by [`factory()`] and factory combinators. Builder methods consume
115/// the chain and configure how future services are constructed; they do not
116/// create services immediately.
117///
118/// The chain implements [`ServiceFactory`] by forwarding creation to its
119/// enclosed factory. [`Self::pipeline`] additionally stores the supplied state
120/// with the created service and binds it for readiness notifications.
121///
122/// [`Self::map_err`] transforms call and readiness errors from created
123/// services, while [`Self::map_init_err`] transforms construction errors.
124/// [`Self::apply`] installs a [`Middleware`] wrapper on each created service.
125///
126/// Cloning clones the enclosed factory without creating a service. Whether
127/// the clones share factory state depends on the enclosed implementation.
128pub struct ServiceChainFactory<Sf, St, Req> {
129 pub(crate) factory: Sf,
130 pub(crate) _t: PhantomData<(St, Req)>,
131}
132
133impl<S: Service<St, Req>, St, Req> ServiceChain<S, St, Req> {
134 /// Calls another service after this service completes successfully.
135 ///
136 /// The current service's response becomes the next service's request. If
137 /// the current service returns an error, the next service is not called.
138 /// Otherwise, the next service's result becomes the chain's result.
139 ///
140 /// Both services must use the same state and error types. Binding,
141 /// readiness, and shutdown cover both children. See [`AndThen`] for
142 /// readiness behavior between calls.
143 pub fn and_then<Next, F>(self, service: F) -> ServiceChain<AndThen<S, Next>, St, Req>
144 where
145 Self: Sized,
146 F: IntoService<Next, St, S::Res>,
147 Next: Service<St, S::Res, Error = S::Error>,
148 {
149 ServiceChain {
150 service: AndThen::new(self.service, service.into_service()),
151 st: PhantomData,
152 }
153 }
154
155 /// Calls another service after this service completes.
156 ///
157 /// The next service receives the current service's complete `Result`, so it
158 /// can handle either a response or an error.
159 ///
160 /// Both services must use the same state and error types. The next service
161 /// determines the final response or error. Errors from the chain's readiness
162 /// check are returned directly, not passed to the next service as a request.
163 ///
164 /// See [`Then`] for an error-recovery example and lifecycle behavior.
165 pub fn then<Next, F>(self, service: F) -> ServiceChain<Then<S, Next>, St, Req>
166 where
167 Self: Sized,
168 F: IntoService<Next, St, Result<S::Res, S::Error>>,
169 Next: Service<St, Result<S::Res, S::Error>, Error = S::Error>,
170 {
171 ServiceChain {
172 service: Then::new(self.service, service.into_service()),
173 st: PhantomData,
174 }
175 }
176
177 /// Maps this service's response to a different type.
178 ///
179 /// Like [`Result::map`], this invokes the synchronous function only for
180 /// successful responses. Errors, requests, state, and lifecycle behavior
181 /// are unchanged. Use [`Self::and_then`] for asynchronous processing.
182 pub fn map<F, Res>(self, f: F) -> ServiceChain<Map<F, S, Res>, St, Req>
183 where
184 Self: Sized,
185 F: Fn(S::Res) -> Res,
186 {
187 ServiceChain {
188 service: Map::new(f, self.service),
189 st: PhantomData,
190 }
191 }
192
193 /// Maps this service's error to a different type.
194 ///
195 /// The synchronous function transforms errors from both calls and
196 /// readiness checks, making this useful for normalizing error types before
197 /// composing services. Successful responses, requests, and state are
198 /// unchanged. Binding and shutdown are forwarded without modification.
199 pub fn map_err<F, Err>(self, f: F) -> ServiceChain<MapErr<F, S, Err>, St, Req>
200 where
201 Self: Sized,
202 F: Fn(S::Error) -> Err,
203 {
204 ServiceChain {
205 service: MapErr::new(f, self.service),
206 st: PhantomData,
207 }
208 }
209
210 /// Adds a custom readiness check to the service chain.
211 ///
212 /// The callback and the wrapped service's readiness futures are polled
213 /// together; the callback does not wait for the service to become ready.
214 /// The chain is ready only when both succeed. Requests and responses pass
215 /// through unchanged.
216 ///
217 /// The callback must implement [`Clone`] for the resulting chain to
218 /// implement [`Service`]. A successful check can be cached by the enclosing
219 /// pipeline, so this is not a per-request callback.
220 ///
221 /// The callback receives only pipeline state. For scoped readiness and
222 /// change notifications, implement [`Service`] directly.
223 pub fn readiness<F>(
224 self,
225 ready: F,
226 ) -> ServiceChain<AndThen<S, FnReadiness<F, S::Error>>, St, Req>
227 where
228 Self: Sized,
229 F: AsyncFn(&St) -> Result<(), S::Error>,
230 {
231 ServiceChain {
232 service: AndThen::new(self.service, FnReadiness::new(ready)),
233 st: PhantomData,
234 }
235 }
236
237 /// Adds a callback invoked at most once when the service shuts down.
238 ///
239 /// The callback receives pipeline state and is polled alongside the
240 /// wrapped service's shutdown future, not after it completes. Shutdown
241 /// waits for both. Requests and responses are unchanged.
242 ///
243 /// The callback is consumed when first polled; cancellation does not make
244 /// it available for a later shutdown attempt. Dropping the chain alone
245 /// does not invoke it.
246 pub fn shutdown<F>(self, sh: F) -> ServiceChain<AndThen<S, FnShutdown<F, S::Error>>, St, Req>
247 where
248 Self: Sized,
249 F: AsyncFnOnce(&St),
250 {
251 ServiceChain {
252 service: AndThen::new(self.service, FnShutdown::new(sh)),
253 st: PhantomData,
254 }
255 }
256
257 /// Applies an asynchronous function as middleware to this service.
258 ///
259 /// This is shorthand for calling [`crate::apply_fn`] on the chained service.
260 /// The function receives an input request and an [`ApplyCtx`] for state
261 /// access and inner calls. It may change request, response, and error types,
262 /// or decide not to call the inner service.
263 ///
264 /// State is unchanged. Inner readiness errors are converted with [`From`];
265 /// errors from [`ApplyCtx::call`] retain their inner type. See
266 /// [`crate::apply_fn`] for call-time readiness behavior.
267 pub fn apply_fn<F, In, Out, Err>(
268 self,
269 f: F,
270 ) -> ServiceChain<Apply<S, St, Req, F, In, Out, Err>, St, In>
271 where
272 F: AsyncFn(In, &ApplyCtx<'_, S, St, Req>) -> Result<Out, Err>,
273 Err: From<S::Error>,
274 {
275 crate::apply_fn(self.service, f)
276 }
277}
278
279impl<S: Service<St, Req>, St, Req> Clone for ServiceChain<S, St, Req>
280where
281 S: Clone,
282{
283 fn clone(&self) -> Self {
284 ServiceChain {
285 service: self.service.clone(),
286 st: PhantomData,
287 }
288 }
289}
290
291impl<S: Service<St, Req>, St, Req> fmt::Debug for ServiceChain<S, St, Req>
292where
293 S: fmt::Debug,
294{
295 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
296 f.debug_struct("ServiceChain")
297 .field("service", &self.service)
298 .finish()
299 }
300}
301
302impl<S: Service<St, Req>, St, Req> Service<St, Req> for ServiceChain<S, St, Req> {
303 type Res = S::Res;
304 type Error = S::Error;
305
306 #[inline]
307 fn bind(&self, ctx: BindCtx<'_>) {
308 ctx.bind(&self.service);
309 }
310
311 #[inline]
312 fn call(
313 &self,
314 req: Req,
315 ctx: Ctx<'_, Self, St>,
316 ) -> impl Future<Output = Result<Self::Res, Self::Error>> {
317 self.service.call(req, ctx.cast())
318 }
319
320 #[inline]
321 fn ready(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = Result<(), Self::Error>> {
322 self.service.ready(ctx.cast())
323 }
324
325 #[inline]
326 fn shutdown(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = ()> {
327 self.service.shutdown(ctx.cast())
328 }
329}
330
331impl<Sf: ServiceFactory<St, Req>, St, Req> ServiceChainFactory<Sf, St, Req> {
332 /// Chains another factory after this factory's services.
333 ///
334 /// Each created service passes its response to the next service as its request.
335 /// If the first service returns an error, the next service is not called.
336 ///
337 /// Factories use the same state, service-error, and initialization-error
338 /// types. They are created sequentially with the same state reference; a
339 /// first-factory error prevents creation of the second service.
340 /// Initialization errors are returned unchanged. See [`AndThenFactory`].
341 pub fn and_then<U>(
342 self,
343 factory: impl IntoServiceFactory<U, St, Sf::Res>,
344 ) -> ServiceChainFactory<AndThenFactory<Sf, U>, St, Req>
345 where
346 Self: Sized,
347 U: ServiceFactory<St, Sf::Res, Error = Sf::Error, InitError = Sf::InitError>,
348 {
349 ServiceChainFactory {
350 factory: AndThenFactory::new(self.factory, factory.into_factory()),
351 _t: PhantomData,
352 }
353 }
354
355 /// Applies middleware to this service factory.
356 ///
357 /// This is shorthand for calling [`crate::apply`] on the chained factory.
358 /// The inner factory creates a service first, then the middleware wraps it
359 /// synchronously with the same state reference. Initialization errors
360 /// bypass the middleware.
361 ///
362 /// For the result to implement [`ServiceFactory`], the middleware's service
363 /// must accept the same state and request types. It may change response and
364 /// service-error types.
365 pub fn apply<U>(self, tr: U) -> ServiceChainFactory<ApplyMiddleware<U, Sf>, St, Req>
366 where
367 U: Middleware<Sf::Service, St>,
368 {
369 crate::apply(tr, self.factory)
370 }
371
372 /// Applies an asynchronous function as middleware to this service factory.
373 ///
374 /// This is shorthand for calling [`crate::apply_fn_factory`] on the chained
375 /// factory. Each successful creation wraps the service with a clone of the
376 /// function, which receives an input request and an [`ApplyCtx`].
377 ///
378 /// Request, response, and service-error types may change; state and
379 /// initialization errors remain unchanged. See [`crate::apply_fn`] for
380 /// lifecycle forwarding and readiness semantics.
381 pub fn apply_fn<F, In, Out, Err>(
382 self,
383 f: F,
384 ) -> ServiceChainFactory<ApplyFactory<F, Sf, St, Req, In, Out, Err>, St, In>
385 where
386 F: AsyncFn(In, &ApplyCtx<'_, Sf::Service, St, Req>) -> Result<Out, Err> + Clone,
387 Err: From<Sf::Error>,
388 {
389 crate::apply_fn_factory(self.factory, f)
390 }
391
392 /// Chains a factory whose services receive the preceding service's complete
393 /// `Result`.
394 ///
395 /// The second service can recover from a failed first call or transform a
396 /// successful response. Both services use the same state and error types.
397 /// Errors from the chain's readiness check are returned directly, rather
398 /// than passed to the second service.
399 ///
400 /// Factories must also share their initialization-error type. Creation is
401 /// sequential with the same state reference, and an initialization error
402 /// stops construction rather than being passed to the next factory.
403 /// See [`ThenFactory`] for an example.
404 pub fn then<F, U>(self, factory: F) -> ServiceChainFactory<ThenFactory<Sf, U>, St, Req>
405 where
406 Self: Sized,
407 F: IntoServiceFactory<U, St, Result<Sf::Res, Sf::Error>>,
408 U: ServiceFactory<
409 St,
410 Result<Sf::Res, Sf::Error>,
411 Error = Sf::Error,
412 InitError = Sf::InitError,
413 >,
414 {
415 ServiceChainFactory {
416 factory: ThenFactory::new(self.factory, factory.into_factory()),
417 _t: PhantomData,
418 }
419 }
420
421 /// Maps responses produced by this factory's services.
422 ///
423 /// Each successful creation clones the synchronous mapping function into
424 /// the new service. The function runs only on successful responses, not
425 /// during initialization. Request, state, service-error, and
426 /// initialization-error types are unchanged. See [`MapFactory`].
427 pub fn map<F, Res>(self, f: F) -> ServiceChainFactory<MapFactory<F, Sf, Res>, St, Req>
428 where
429 Self: Sized,
430 F: Fn(Sf::Res) -> Res + Clone,
431 {
432 ServiceChainFactory {
433 factory: MapFactory::new(f, self.factory),
434 _t: PhantomData,
435 }
436 }
437
438 /// Maps errors produced by this factory's services.
439 ///
440 /// Each successful creation clones the synchronous mapping function into
441 /// the new service. It transforms call and readiness errors, leaving
442 /// successful responses unchanged. Initialization errors are not mapped;
443 /// use [`Self::map_init_err`] for those. See [`MapErrFactory`].
444 pub fn map_err<F, E>(self, f: F) -> ServiceChainFactory<MapErrFactory<F, Sf, E>, St, Req>
445 where
446 Self: Sized,
447 F: Fn(Sf::Error) -> E + Clone,
448 {
449 ServiceChainFactory {
450 factory: MapErrFactory::new(f, self.factory),
451 _t: PhantomData,
452 }
453 }
454
455 /// Maps this factory's initialization error.
456 ///
457 /// The synchronous function runs only when creating the inner service
458 /// fails. Successful services are returned unchanged, including their
459 /// call and readiness error types. Use [`Self::map_err`] to map those.
460 pub fn map_init_err<F, E>(self, f: F) -> ServiceChainFactory<MapInitErr<F, Sf, E>, St, Req>
461 where
462 Self: Sized,
463 F: Fn(Sf::InitError) -> E + Clone,
464 {
465 ServiceChainFactory {
466 factory: MapInitErr::new(f, self.factory),
467 _t: PhantomData,
468 }
469 }
470
471 /// Adds a custom readiness check to each created service.
472 ///
473 /// Each created service gets a clone of the callback. Its readiness future
474 /// is polled alongside the wrapped service's readiness future; the service
475 /// is ready only when both succeed. Requests and responses are unchanged.
476 ///
477 /// The inner factory must have [`std::convert::Infallible`] initialization
478 /// errors for this composition to implement [`ServiceFactory`].
479 /// Successful readiness can be cached, so the callback need not run for
480 /// every request.
481 ///
482 /// The callback receives only pipeline state. For scoped readiness and
483 /// change notifications, implement [`Service`] directly.
484 pub fn readiness<F>(
485 self,
486 ready: F,
487 ) -> ServiceChainFactory<AndThenFactory<Sf, FnReadiness<F, Sf::Error>>, St, Req>
488 where
489 Self: Sized,
490 F: AsyncFn(&St) -> Result<(), Sf::Error> + Clone,
491 {
492 ServiceChainFactory {
493 factory: AndThenFactory::new(self.factory, FnReadiness::new(ready)),
494 _t: PhantomData,
495 }
496 }
497
498 /// Adds a shutdown callback to each created service.
499 ///
500 /// Each service gets its own callback, invoked at most once with pipeline
501 /// state. It is polled alongside the inner service's shutdown, and shutdown
502 /// waits for both. Cancellation does not restore a consumed callback;
503 /// dropping a service alone does not invoke it.
504 ///
505 /// The inner factory must have [`std::convert::Infallible`] initialization
506 /// errors for this composition to implement [`ServiceFactory`].
507 pub fn shutdown<F>(
508 self,
509 sh: F,
510 ) -> ServiceChainFactory<AndThenFactory<Sf, FnShutdown<F, Sf::Error>>, St, Req>
511 where
512 Self: Sized,
513 F: AsyncFnOnce(&St) + Clone,
514 {
515 ServiceChainFactory {
516 factory: AndThenFactory::new(self.factory, FnShutdown::new(sh)),
517 _t: PhantomData,
518 }
519 }
520
521 /// Creates a service and wraps it with its state in a [`Pipeline`].
522 ///
523 /// The factory first borrows `st` for creation, then the pipeline takes
524 /// ownership of both state and service and binds readiness notifications.
525 /// Creation errors are returned unchanged.
526 ///
527 /// This does not wait for service readiness. Use [`Pipeline::ready`] to
528 /// check it explicitly; [`Pipeline::call`] checks it before dispatch.
529 /// Each invocation creates a new service and enclosing pipeline readiness
530 /// scope, subject to any sharing introduced by the inner factory.
531 pub async fn pipeline(&self, st: St) -> Result<Pipeline<Req, Sf::Res, Sf::Error>, Sf::InitError>
532 where
533 Sf: 'static,
534 St: 'static,
535 Req: 'static,
536 {
537 let svc = self.factory.create(&st).await?;
538 Ok(Pipeline::new(st, svc))
539 }
540}
541
542impl<Sf, St, Req> Clone for ServiceChainFactory<Sf, St, Req>
543where
544 Sf: Clone,
545{
546 fn clone(&self) -> Self {
547 ServiceChainFactory {
548 factory: self.factory.clone(),
549 _t: PhantomData,
550 }
551 }
552}
553
554impl<Sf, St, Req> fmt::Debug for ServiceChainFactory<Sf, St, Req>
555where
556 Sf: fmt::Debug,
557{
558 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
559 f.debug_struct("ServiceChainFactory")
560 .field("factory", &self.factory)
561 .finish()
562 }
563}
564
565impl<Sf: ServiceFactory<St, Req>, St, Req> ServiceFactory<St, Req>
566 for ServiceChainFactory<Sf, St, Req>
567{
568 type Res = Sf::Res;
569 type Error = Sf::Error;
570
571 type Service = Sf::Service;
572 type InitError = Sf::InitError;
573
574 #[inline]
575 async fn create(&self, st: &St) -> Result<Sf::Service, Sf::InitError> {
576 self.factory.create(st).await
577 }
578}