ntex_service/then.rs
1use super::{BindCtx, Ctx, Service, ServiceFactory, util};
2
3#[derive(Debug, Clone)]
4/// Passes a service's complete call result to a second service.
5///
6/// Created by [`crate::ServiceChain::then`]. The second service receives
7/// `Result<A::Res, A::Error>` and can transform a successful response, recover
8/// from an error, or return an error of its own. Its result becomes the final
9/// result. Both services use the same state and error types.
10///
11/// Unlike [`crate::dev::AndThen`], this invokes the second service even when
12/// the first call fails.
13///
14/// # Readiness and lifecycle
15///
16/// Binding is forwarded to both children. Readiness succeeds only when both
17/// children are ready. Errors from the chain's readiness check are returned
18/// directly, not passed to the second service as a request. Shutdown drives
19/// both children's shutdown futures to completion.
20///
21/// Raw children share the enclosing readiness scope, and calls forward
22/// directly without an extra readiness check. Wrap a child with
23/// [`crate::ready()`] when it needs an independent cache and a call-time check,
24/// particularly when the second child's readiness can change while the first
25/// call is awaiting.
26///
27/// Cloning clones both children; shared state and readiness depend on their
28/// clone implementations.
29///
30/// # Example
31///
32/// ```
33/// use ntex_service::{Service, fn_service, service};
34///
35/// # async fn example() -> Result<(), &'static str> {
36/// let pipeline = service(fn_service(async |req: u32| {
37/// if req == 0 { Err("missing value") } else { Ok(req) }
38/// }))
39/// .then(fn_service(async |result: Result<u32, &'static str>| {
40/// Ok::<_, &'static str>(result.unwrap_or(10) * 2)
41/// }))
42/// .pipeline(());
43///
44/// assert_eq!(pipeline.call(3).await?, 6);
45/// assert_eq!(pipeline.call(0).await?, 20);
46/// # Ok(())
47/// # }
48/// ```
49pub struct Then<A, B> {
50 svc1: A,
51 svc2: B,
52}
53
54impl<A, B> Then<A, B> {
55 /// Creates a new `Then` service.
56 pub(crate) fn new(svc1: A, svc2: B) -> Then<A, B> {
57 Self { svc1, svc2 }
58 }
59}
60
61impl<A, B, St, Req> Service<St, Req> for Then<A, B>
62where
63 A: Service<St, Req>,
64 B: Service<St, Result<A::Res, A::Error>, Error = A::Error>,
65{
66 type Res = B::Res;
67 type Error = B::Error;
68
69 #[inline]
70 fn bind(&self, ctx: BindCtx<'_>) {
71 ctx.bind(&self.svc1);
72 ctx.bind(&self.svc2);
73 }
74
75 #[inline]
76 #[allow(clippy::manual_async_fn)]
77 fn call(
78 &self,
79 req: Req,
80 ctx: Ctx<'_, Self, St>,
81 ) -> impl Future<Output = Result<B::Res, B::Error>> {
82 // An `async fn` would store `req` and `ctx` twice.
83 async move {
84 let result = self.svc1.call(req, ctx.cast()).await;
85 self.svc2.call(result, ctx.cast()).await
86 }
87 }
88
89 #[inline]
90 fn ready(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = Result<(), Self::Error>> {
91 util::ready(&self.svc1, &self.svc2, ctx)
92 }
93
94 #[inline]
95 fn shutdown(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = ()> {
96 util::shutdown(&self.svc1, &self.svc2, ctx)
97 }
98}
99
100#[derive(Debug, Clone)]
101/// Creates a [`Then`] service from two service factories.
102///
103/// Created by [`crate::ServiceChainFactory::then`]. Both factories use the
104/// same state, service-error, and initialization-error types. The second
105/// factory creates services whose request is the first service's complete
106/// `Result`, rather than just its successful response.
107///
108/// Creation is sequential with the same state reference. The second factory
109/// is invoked only after the first succeeds. An initialization error from
110/// either factory is returned unchanged; it is not passed to the second
111/// factory or handled as a service-call result.
112///
113/// Created services use the call and lifecycle behavior described in [`Then`].
114/// Wrap a child factory with [`crate::ready_factory()`] to give each of its
115/// created services an independent readiness cache. Cloning clones both
116/// factories without creating services.
117///
118/// # Example
119///
120/// ```
121/// use ntex_service::{factory, fn_factory, fn_service};
122///
123/// # async fn example() -> Result<(), &'static str> {
124/// let factory = factory(fn_factory(async |_: &()| {
125/// Ok::<_, &'static str>(fn_service(async |_: u32| Err::<u32, _>("unavailable")))
126/// }))
127/// .then(fn_factory(async |_: &()| {
128/// Ok::<_, &'static str>(fn_service(async |result: Result<u32, &'static str>| {
129/// Ok::<_, &'static str>(result.unwrap_or(42))
130/// }))
131/// }));
132///
133/// let pipeline = factory.pipeline(()).await?;
134/// assert_eq!(pipeline.call(1).await?, 42);
135/// # Ok(())
136/// # }
137/// ```
138pub struct ThenFactory<A, B> {
139 svc1: A,
140 svc2: B,
141}
142
143impl<A, B> ThenFactory<A, B> {
144 /// Creates a new `ThenFactory`.
145 pub(crate) fn new(svc1: A, svc2: B) -> Self {
146 Self { svc1, svc2 }
147 }
148}
149
150impl<A, B, St, Req> ServiceFactory<St, Req> for ThenFactory<A, B>
151where
152 A: ServiceFactory<St, Req>,
153 B: ServiceFactory<St, Result<A::Res, A::Error>, Error = A::Error, InitError = A::InitError>,
154{
155 type Res = B::Res;
156 type Error = A::Error;
157
158 type Service = Then<A::Service, B::Service>;
159 type InitError = A::InitError;
160
161 async fn create(&self, st: &St) -> Result<Self::Service, Self::InitError> {
162 Ok(Then::new(
163 self.svc1.create(st).await?,
164 self.svc2.create(st).await?,
165 ))
166 }
167}
168
169#[cfg(test)]
170#[path = "../tests/unit/then.rs"]
171mod tests;