ntex_service/and_then.rs
1use std::{future::Future, pin::Pin, task::Context, task::Poll};
2
3use super::{BindCtx, Ctx, Service, ServiceFactory, util};
4
5pin_project_lite::pin_project! {
6 /// Calls the first service, then passes its response to `next`.
7 ///
8 /// Unlike an `async fn`, the states do not keep storage for the request,
9 /// `self`, or `ctx` after they are moved into the call futures.
10 #[project = AndThenCallProj]
11 enum AndThenCall<F1, N, F2> {
12 First { #[pin] fut: F1, next: Option<N> },
13 Second { #[pin] fut: F2 },
14 }
15}
16
17impl<F1, N, F2, R, T, E> Future for AndThenCall<F1, N, F2>
18where
19 F1: Future<Output = Result<R, E>>,
20 N: FnOnce(R) -> F2,
21 F2: Future<Output = Result<T, E>>,
22{
23 type Output = Result<T, E>;
24
25 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
26 loop {
27 let fut = match self.as_mut().project() {
28 AndThenCallProj::First { fut, next } => match std::task::ready!(fut.poll(cx)) {
29 Ok(res) => next.take().expect("`AndThenCall` polled after completion")(res),
30 Err(err) => return Poll::Ready(Err(err)),
31 },
32 AndThenCallProj::Second { fut } => return fut.poll(cx),
33 };
34 self.set(AndThenCall::Second { fut });
35 }
36 }
37}
38
39#[derive(Debug, Clone)]
40/// Calls two services in sequence, passing the first response to the second.
41///
42/// Created by [`Service::and_then`] and [`crate::ServiceChain::and_then`].
43/// Both services use the same state and error types. The first service accepts
44/// the input request, and the second service produces the final response.
45/// If the first call fails, its error is returned without calling the second
46/// service. Errors from the second call are also returned unchanged.
47///
48/// To pass both successful responses and errors to the next service, use
49/// [`crate::ServiceChain::then`] instead.
50///
51/// # Readiness and lifecycle
52///
53/// Binding is forwarded to both children. Readiness succeeds only when both
54/// children are ready; a readiness error from either child is returned
55/// unchanged. Shutdown drives both children's shutdown futures to completion.
56///
57/// Children share the enclosing readiness scope unless explicitly wrapped
58/// with [`crate::ready()`]. Calls forward directly to each child without
59/// another readiness check for raw services. Wrap a child when it needs an
60/// independent readiness cache and a check at call time, especially when the
61/// second child's readiness can change while the first call is awaiting.
62///
63/// Cloning clones both children; any shared state or readiness depends on
64/// their clone implementations.
65///
66/// # Example
67///
68/// ```
69/// use ntex_service::{Service, fn_service};
70///
71/// # async fn example() -> Result<(), ()> {
72/// let pipeline = fn_service(async |req: u32| Ok::<_, ()>(req + 1))
73/// .and_then(fn_service(async |value: u32| Ok::<_, ()>(value.to_string())))
74/// .pipeline(());
75///
76/// assert_eq!(pipeline.call(41).await?, "42");
77/// # Ok(())
78/// # }
79/// ```
80///
81/// See the framework guide's [Service Pipelines](https://docs.ntex.rs/2-pipeline.html)
82/// chapter for composition and readiness semantics.
83pub struct AndThen<A, B> {
84 svc1: A,
85 svc2: B,
86}
87
88impl<A, B> AndThen<A, B> {
89 /// Creates a new `AndThen` service.
90 pub(crate) fn new(svc1: A, svc2: B) -> Self {
91 Self { svc1, svc2 }
92 }
93}
94
95impl<A, B, St, Req> Service<St, Req> for AndThen<A, B>
96where
97 A: Service<St, Req>,
98 B: Service<St, A::Res, Error = A::Error>,
99{
100 type Res = B::Res;
101 type Error = A::Error;
102
103 #[inline]
104 fn bind(&self, ctx: BindCtx<'_>) {
105 ctx.bind(&self.svc1);
106 ctx.bind(&self.svc2);
107 }
108
109 #[inline]
110 fn call(
111 &self,
112 req: Req,
113 ctx: Ctx<'_, Self, St>,
114 ) -> impl Future<Output = Result<B::Res, A::Error>> {
115 AndThenCall::First {
116 fut: self.svc1.call(req, ctx.cast()),
117 next: Some(move |res: A::Res| self.svc2.call(res, ctx.cast())),
118 }
119 }
120
121 #[inline]
122 fn ready(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = Result<(), Self::Error>> {
123 util::ready(&self.svc1, &self.svc2, ctx)
124 }
125
126 #[inline]
127 fn shutdown(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = ()> {
128 util::shutdown(&self.svc1, &self.svc2, ctx)
129 }
130}
131
132#[derive(Debug, Clone)]
133/// Creates an [`AndThen`] service from two service factories.
134///
135/// Created by [`ServiceFactory::and_then`],
136/// [`crate::ServiceChainFactory::and_then`], or [`Self::new`].
137/// Both factories use the same state, service-error, and initialization-error
138/// types. The first factory's response type is the second factory's request
139/// type.
140///
141/// Creation is sequential: the first factory completes before the second
142/// starts, and both receive the same state reference. If the first factory
143/// fails, the second is not invoked. Initialization errors from either
144/// factory are returned unchanged.
145///
146/// Created services use the call, binding, readiness, and shutdown behavior
147/// described in [`AndThen`]. Wrap a child factory with [`crate::ready_factory()`]
148/// to give each of its created services an independent readiness cache.
149///
150/// Cloning clones both factories without creating any services.
151pub struct AndThenFactory<A, B> {
152 svc1: A,
153 svc2: B,
154}
155
156impl<A, B> AndThenFactory<A, B> {
157 /// Combines two factories without creating their services yet.
158 ///
159 /// [`ServiceFactory::create`] creates the children in argument order and
160 /// joins them into an [`AndThen`] service.
161 ///
162 /// # Example
163 ///
164 /// ```
165 /// use ntex_service::{ServiceFactory, dev::AndThenFactory, fn_factory, fn_service};
166 ///
167 /// # async fn example() -> Result<(), ()> {
168 /// let first = fn_factory(async |offset: &u32| {
169 /// let offset = *offset;
170 /// Ok::<_, ()>(fn_service(async move |req: u32| Ok::<_, ()>(req + offset)))
171 /// });
172 /// let second = fn_factory(async |_: &u32| {
173 /// Ok::<_, ()>(fn_service(async |value: u32| Ok::<_, ()>(value.to_string())))
174 /// });
175 ///
176 /// let pipeline = AndThenFactory::new(first, second).pipeline(10).await?;
177 /// assert_eq!(pipeline.call(2).await?, "12");
178 /// # Ok(())
179 /// # }
180 /// ```
181 pub fn new(svc1: A, svc2: B) -> Self {
182 Self { svc1, svc2 }
183 }
184}
185
186impl<A, B, St, Req> ServiceFactory<St, Req> for AndThenFactory<A, B>
187where
188 A: ServiceFactory<St, Req>,
189 B: ServiceFactory<St, A::Res, Error = A::Error, InitError = A::InitError>,
190{
191 type Res = B::Res;
192 type Error = A::Error;
193
194 type Service = AndThen<A::Service, B::Service>;
195 type InitError = A::InitError;
196
197 #[inline]
198 async fn create(&self, st: &St) -> Result<Self::Service, Self::InitError> {
199 Ok(AndThen::new(
200 self.svc1.create(st).await?,
201 self.svc2.create(st).await?,
202 ))
203 }
204}
205
206#[cfg(test)]
207#[path = "../tests/unit/and_then.rs"]
208mod tests;