ntex_service/chain.rs
1use std::{fmt, marker::PhantomData};
2
3use crate::and_then::{AndThen, AndThenFactory};
4use crate::apply::{Apply, ApplyCtx, ApplyFactory};
5use crate::ctx::Ctx;
6use crate::fn_ready::FnReadiness;
7use crate::fn_shutdown::FnShutdown;
8use crate::map::{Map, MapFactory};
9use crate::map_err::{MapErr, MapErrFactory};
10use crate::map_init_err::MapInitErr;
11use crate::middleware::{ApplyMiddleware, Middleware};
12use crate::pipeline::Pipeline;
13use crate::then::{Then, ThenFactory};
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 for the resulting
141 /// chain to implement [`Service`]. Binding, readiness, and shutdown cover
142 /// both children. See [`AndThen`] for 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>,
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 for the resulting
161 /// chain to implement [`Service`]. The next service determines the final
162 /// response or error. Errors from the chain's readiness check are returned
163 /// directly, not passed to the next service as a request.
164 ///
165 /// See [`Then`] for an error-recovery example and lifecycle behavior.
166 pub fn then<Next, F>(self, service: F) -> ServiceChain<Then<S, Next>, St, Req>
167 where
168 Self: Sized,
169 F: IntoService<Next, St, Result<S::Res, S::Error>>,
170 Next: Service<St, Result<S::Res, S::Error>>,
171 {
172 ServiceChain {
173 service: Then::new(self.service, service.into_service()),
174 st: PhantomData,
175 }
176 }
177
178 /// Maps this service's response to a different type.
179 ///
180 /// Like [`Result::map`], this invokes the synchronous function only for
181 /// successful responses. Errors, requests, state, and lifecycle behavior
182 /// are unchanged. Use [`Self::and_then`] for asynchronous processing.
183 pub fn map<F, Res>(self, f: F) -> ServiceChain<Map<F, S, Res>, St, Req>
184 where
185 Self: Sized,
186 F: Fn(S::Res) -> Res,
187 {
188 ServiceChain {
189 service: Map::new(f, self.service),
190 st: PhantomData,
191 }
192 }
193
194 /// Maps this service's error to a different type.
195 ///
196 /// The synchronous function transforms errors from both calls and
197 /// readiness checks, making this useful for normalizing error types before
198 /// composing services. Successful responses, requests, and state are
199 /// unchanged. Binding and shutdown are forwarded without modification.
200 pub fn map_err<F, Err>(self, f: F) -> ServiceChain<MapErr<F, S, Err>, St, Req>
201 where
202 Self: Sized,
203 F: Fn(S::Error) -> Err,
204 {
205 ServiceChain {
206 service: MapErr::new(f, self.service),
207 st: PhantomData,
208 }
209 }
210
211 /// Adds a custom readiness check to the service chain.
212 ///
213 /// The callback and the wrapped service's readiness futures are polled
214 /// together; the callback does not wait for the service to become ready.
215 /// The chain is ready only when both succeed. Requests and responses pass
216 /// through unchanged.
217 ///
218 /// The callback must implement [`Clone`] for the resulting chain to
219 /// implement [`Service`]. A successful check can be cached by the enclosing
220 /// pipeline, so this is not a per-request callback.
221 ///
222 /// The callback receives only pipeline state. For scoped readiness and
223 /// change notifications, implement [`Service`] directly.
224 pub fn readiness<F>(
225 self,
226 ready: F,
227 ) -> ServiceChain<AndThen<S, FnReadiness<F, S::Error>>, St, Req>
228 where
229 Self: Sized,
230 F: AsyncFn(&St) -> Result<(), S::Error>,
231 {
232 ServiceChain {
233 service: AndThen::new(self.service, FnReadiness::new(ready)),
234 st: PhantomData,
235 }
236 }
237
238 /// Adds a callback invoked at most once when the service shuts down.
239 ///
240 /// The callback receives pipeline state and is polled alongside the
241 /// wrapped service's shutdown future, not after it completes. Shutdown
242 /// waits for both. Requests and responses are unchanged.
243 ///
244 /// The callback is consumed when first polled; cancellation does not make
245 /// it available for a later shutdown attempt. Dropping the chain alone
246 /// does not invoke it.
247 pub fn shutdown<F>(self, sh: F) -> ServiceChain<AndThen<S, FnShutdown<F, S::Error>>, St, Req>
248 where
249 Self: Sized,
250 F: AsyncFnOnce(&St),
251 {
252 ServiceChain {
253 service: AndThen::new(self.service, FnShutdown::new(sh)),
254 st: PhantomData,
255 }
256 }
257
258 /// Applies an asynchronous function as middleware to this service.
259 ///
260 /// This is shorthand for calling [`crate::apply_fn`] on the chained service.
261 /// The function receives an input request and an [`ApplyCtx`] for state
262 /// access and inner calls. It may change request, response, and error types,
263 /// or decide not to call the inner service.
264 ///
265 /// State is unchanged. Inner readiness errors are converted with [`From`];
266 /// errors from [`ApplyCtx::call`] retain their inner type. See
267 /// [`crate::apply_fn`] for call-time readiness behavior.
268 pub fn apply_fn<F, In, Out, Err>(
269 self,
270 f: F,
271 ) -> ServiceChain<Apply<S, St, Req, F, In, Out, Err>, St, In>
272 where
273 F: AsyncFn(In, &ApplyCtx<'_, S, St, Req>) -> Result<Out, Err>,
274 Err: From<S::Error>,
275 {
276 crate::apply_fn(self.service, f)
277 }
278}
279
280impl<S: Service<St, Req>, St, Req> Clone for ServiceChain<S, St, Req>
281where
282 S: Clone,
283{
284 fn clone(&self) -> Self {
285 ServiceChain {
286 service: self.service.clone(),
287 st: PhantomData,
288 }
289 }
290}
291
292impl<S: Service<St, Req>, St, Req> fmt::Debug for ServiceChain<S, St, Req>
293where
294 S: fmt::Debug,
295{
296 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
297 f.debug_struct("ServiceChain")
298 .field("service", &self.service)
299 .finish()
300 }
301}
302
303impl<S: Service<St, Req>, St, Req> Service<St, Req> for ServiceChain<S, St, Req> {
304 type Res = S::Res;
305 type Error = S::Error;
306
307 crate::forward_bind!(St, service);
308
309 #[inline]
310 async fn call(&self, req: Req, ctx: Ctx<'_, Self, St>) -> Result<Self::Res, Self::Error> {
311 self.service.call(req, ctx.cast()).await
312 }
313
314 #[inline]
315 async fn ready(&self, ctx: Ctx<'_, Self, St>) -> Result<(), Self::Error> {
316 self.service.ready(ctx.cast()).await
317 }
318
319 #[inline]
320 async fn shutdown(&self, ctx: Ctx<'_, Self, St>) {
321 self.service.shutdown(ctx.cast()).await;
322 }
323}
324
325impl<Sf: ServiceFactory<St, Req>, St, Req> ServiceChainFactory<Sf, St, Req> {
326 /// Chains another factory after this factory's services.
327 ///
328 /// Each created service passes its response to the next service as its request.
329 /// If the first service returns an error, the next service is not called.
330 ///
331 /// Factories use the same state, service-error, and initialization-error
332 /// types. They are created sequentially with the same state reference; a
333 /// first-factory error prevents creation of the second service.
334 /// Initialization errors are returned unchanged. See [`AndThenFactory`].
335 pub fn and_then<U>(
336 self,
337 factory: impl IntoServiceFactory<U, St, Sf::Res>,
338 ) -> ServiceChainFactory<AndThenFactory<Sf, U>, St, Req>
339 where
340 Self: Sized,
341 U: ServiceFactory<St, Sf::Res, Error = Sf::Error, InitError = Sf::InitError>,
342 {
343 ServiceChainFactory {
344 factory: AndThenFactory::new(self.factory, factory.into_factory()),
345 _t: PhantomData,
346 }
347 }
348
349 /// Applies middleware to this service factory.
350 ///
351 /// This is shorthand for calling [`crate::apply`] on the chained factory.
352 /// The inner factory creates a service first, then the middleware wraps it
353 /// synchronously with the same state reference. Initialization errors
354 /// bypass the middleware.
355 ///
356 /// For the result to implement [`ServiceFactory`], the middleware's service
357 /// must accept the same state and request types. It may change response and
358 /// service-error types.
359 pub fn apply<U>(self, tr: U) -> ServiceChainFactory<ApplyMiddleware<U, Sf>, St, Req>
360 where
361 U: Middleware<Sf::Service, St>,
362 {
363 crate::apply(tr, self.factory)
364 }
365
366 /// Applies an asynchronous function as middleware to this service factory.
367 ///
368 /// This is shorthand for calling [`crate::apply_fn_factory`] on the chained
369 /// factory. Each successful creation wraps the service with a clone of the
370 /// function, which receives an input request and an [`ApplyCtx`].
371 ///
372 /// Request, response, and service-error types may change; state and
373 /// initialization errors remain unchanged. See [`crate::apply_fn`] for
374 /// lifecycle forwarding and readiness semantics.
375 pub fn apply_fn<F, In, Out, Err>(
376 self,
377 f: F,
378 ) -> ServiceChainFactory<ApplyFactory<F, Sf, St, Req, In, Out, Err>, St, In>
379 where
380 F: AsyncFn(In, &ApplyCtx<'_, Sf::Service, St, Req>) -> Result<Out, Err> + Clone,
381 Err: From<Sf::Error>,
382 {
383 crate::apply_fn_factory(self.factory, f)
384 }
385
386 /// Chains a factory whose services receive the preceding service's complete
387 /// `Result`.
388 ///
389 /// The second service can recover from a failed first call or transform a
390 /// successful response. Both services use the same state and error types.
391 /// Errors from the chain's readiness check are returned directly, rather
392 /// than passed to the second service.
393 ///
394 /// Factories must also share their initialization-error type. Creation is
395 /// sequential with the same state reference, and an initialization error
396 /// stops construction rather than being passed to the next factory.
397 /// See [`ThenFactory`] for an example.
398 pub fn then<F, U>(self, factory: F) -> ServiceChainFactory<ThenFactory<Sf, U>, St, Req>
399 where
400 Self: Sized,
401 F: IntoServiceFactory<U, St, Result<Sf::Res, Sf::Error>>,
402 U: ServiceFactory<
403 St,
404 Result<Sf::Res, Sf::Error>,
405 Error = Sf::Error,
406 InitError = Sf::InitError,
407 >,
408 {
409 ServiceChainFactory {
410 factory: ThenFactory::new(self.factory, factory.into_factory()),
411 _t: PhantomData,
412 }
413 }
414
415 /// Maps responses produced by this factory's services.
416 ///
417 /// Each successful creation clones the synchronous mapping function into
418 /// the new service. The function runs only on successful responses, not
419 /// during initialization. Request, state, service-error, and
420 /// initialization-error types are unchanged. See [`MapFactory`].
421 pub fn map<F, Res>(self, f: F) -> ServiceChainFactory<MapFactory<F, Sf, Res>, St, Req>
422 where
423 Self: Sized,
424 F: Fn(Sf::Res) -> Res + Clone,
425 {
426 ServiceChainFactory {
427 factory: MapFactory::new(f, self.factory),
428 _t: PhantomData,
429 }
430 }
431
432 /// Maps errors produced by this factory's services.
433 ///
434 /// Each successful creation clones the synchronous mapping function into
435 /// the new service. It transforms call and readiness errors, leaving
436 /// successful responses unchanged. Initialization errors are not mapped;
437 /// use [`Self::map_init_err`] for those. See [`MapErrFactory`].
438 pub fn map_err<F, E>(self, f: F) -> ServiceChainFactory<MapErrFactory<F, Sf, E>, St, Req>
439 where
440 Self: Sized,
441 F: Fn(Sf::Error) -> E + Clone,
442 {
443 ServiceChainFactory {
444 factory: MapErrFactory::new(f, self.factory),
445 _t: PhantomData,
446 }
447 }
448
449 /// Maps this factory's initialization error.
450 ///
451 /// The synchronous function runs only when creating the inner service
452 /// fails. Successful services are returned unchanged, including their
453 /// call and readiness error types. Use [`Self::map_err`] to map those.
454 pub fn map_init_err<F, E>(self, f: F) -> ServiceChainFactory<MapInitErr<F, Sf, E>, St, Req>
455 where
456 Self: Sized,
457 F: Fn(Sf::InitError) -> E + Clone,
458 {
459 ServiceChainFactory {
460 factory: MapInitErr::new(f, self.factory),
461 _t: PhantomData,
462 }
463 }
464
465 /// Adds a custom readiness check to each created service.
466 ///
467 /// Each created service gets a clone of the callback. Its readiness future
468 /// is polled alongside the wrapped service's readiness future; the service
469 /// is ready only when both succeed. Requests and responses are unchanged.
470 ///
471 /// The inner factory must have [`std::convert::Infallible`] initialization
472 /// errors for this composition to implement [`ServiceFactory`].
473 /// Successful readiness can be cached, so the callback need not run for
474 /// every request.
475 ///
476 /// The callback receives only pipeline state. For scoped readiness and
477 /// change notifications, implement [`Service`] directly.
478 pub fn readiness<F>(
479 self,
480 ready: F,
481 ) -> ServiceChainFactory<AndThenFactory<Sf, FnReadiness<F, Sf::Error>>, St, Req>
482 where
483 Self: Sized,
484 F: AsyncFn(&St) -> Result<(), Sf::Error> + Clone,
485 {
486 ServiceChainFactory {
487 factory: AndThenFactory::new(self.factory, FnReadiness::new(ready)),
488 _t: PhantomData,
489 }
490 }
491
492 /// Adds a shutdown callback to each created service.
493 ///
494 /// Each service gets its own callback, invoked at most once with pipeline
495 /// state. It is polled alongside the inner service's shutdown, and shutdown
496 /// waits for both. Cancellation does not restore a consumed callback;
497 /// dropping a service alone does not invoke it.
498 ///
499 /// The inner factory must have [`std::convert::Infallible`] initialization
500 /// errors for this composition to implement [`ServiceFactory`].
501 pub fn shutdown<F>(
502 self,
503 sh: F,
504 ) -> ServiceChainFactory<AndThenFactory<Sf, FnShutdown<F, Sf::Error>>, St, Req>
505 where
506 Self: Sized,
507 F: AsyncFnOnce(&St) + Clone,
508 {
509 ServiceChainFactory {
510 factory: AndThenFactory::new(self.factory, FnShutdown::new(sh)),
511 _t: PhantomData,
512 }
513 }
514
515 /// Creates a service and wraps it with its state in a [`Pipeline`].
516 ///
517 /// The factory first borrows `st` for creation, then the pipeline takes
518 /// ownership of both state and service and binds readiness notifications.
519 /// Creation errors are returned unchanged.
520 ///
521 /// This does not wait for service readiness. Use [`Pipeline::ready`] to
522 /// check it explicitly; [`Pipeline::call`] checks it before dispatch.
523 /// Each invocation creates a new service and enclosing pipeline readiness
524 /// scope, subject to any sharing introduced by the inner factory.
525 pub async fn pipeline(&self, st: St) -> Result<Pipeline<Req, Sf::Res, Sf::Error>, Sf::InitError>
526 where
527 Sf: 'static,
528 St: 'static,
529 Req: 'static,
530 {
531 let svc = self.factory.create(&st).await?;
532 Ok(Pipeline::new(st, svc))
533 }
534}
535
536impl<Sf, St, Req> Clone for ServiceChainFactory<Sf, St, Req>
537where
538 Sf: Clone,
539{
540 fn clone(&self) -> Self {
541 ServiceChainFactory {
542 factory: self.factory.clone(),
543 _t: PhantomData,
544 }
545 }
546}
547
548impl<Sf, St, Req> fmt::Debug for ServiceChainFactory<Sf, St, Req>
549where
550 Sf: fmt::Debug,
551{
552 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
553 f.debug_struct("ServiceChainFactory")
554 .field("factory", &self.factory)
555 .finish()
556 }
557}
558
559impl<Sf: ServiceFactory<St, Req>, St, Req> ServiceFactory<St, Req>
560 for ServiceChainFactory<Sf, St, Req>
561{
562 type Res = Sf::Res;
563 type Error = Sf::Error;
564
565 type Service = Sf::Service;
566 type InitError = Sf::InitError;
567
568 #[inline]
569 async fn create(&self, st: &St) -> Result<Sf::Service, Sf::InitError> {
570 self.factory.create(st).await
571 }
572}