Skip to main content

ntex_service/
macros.rs

1/// Forwards [`crate::Service::bind`], [`crate::Service::ready`], and
2/// [`crate::Service::shutdown`] to inner service fields.
3///
4/// This is the recommended way to write a wrapper service. For a
5/// [`crate::Pipeline`] field implement `bind` with [`crate::Pipeline::bind_to`].
6///
7/// - `forward!(St, field)`: forwards to a service field, readiness errors are
8///   converted with [`Into`].
9/// - `forward!(St, a, b, ...)`: forwards to several service fields. Readiness
10///   completes once all fields are ready, and shutdown waits for all of them.
11/// - `forward!(St, field, ..., map_err = f)`: converts readiness errors with `f`.
12///
13/// `St` is the state type of the `Service<St, Req>` impl, and each field is a
14/// named or tuple field such as `inner` or `0`. Call the inner services with
15/// [`crate::Ctx::call`].
16///
17/// ```
18/// use ntex_service::{Ctx, Service, forward};
19///
20/// struct Log<S>(S);
21///
22/// impl<S, St, Req> Service<St, Req> for Log<S>
23/// where
24///     S: Service<St, Req>,
25/// {
26///     type Res = S::Res;
27///     type Error = S::Error;
28///
29///     forward!(St, 0);
30///
31///     async fn call(&self, req: Req, ctx: Ctx<'_, Self, St>) -> Result<S::Res, S::Error> {
32///         println!("call");
33///         ctx.call(&self.0, req).await
34///     }
35/// }
36///
37/// struct Both<A, B> {
38///     first: A,
39///     second: B,
40/// }
41///
42/// impl<A, B, St, Req> Service<St, Req> for Both<A, B>
43/// where
44///     A: Service<St, Req, Res = Req>,
45///     B: Service<St, Req, Error = A::Error>,
46/// {
47///     type Res = B::Res;
48///     type Error = String;
49///
50///     forward!(St, first, second, map_err = |_| "not ready".to_string());
51///
52///     async fn call(&self, req: Req, ctx: Ctx<'_, Self, St>) -> Result<B::Res, String> {
53///         let req = ctx.call(&self.first, req).await.map_err(|_| "first".to_string())?;
54///         ctx.call(&self.second, req).await.map_err(|_| "second".to_string())
55///     }
56/// }
57/// ```
58#[macro_export]
59macro_rules! forward {
60    (@go $st:ty; [$field:tt]; map_err = $err:expr $(,)?) => {
61        #[inline]
62        fn bind(&self, ctx: $crate::BindCtx<'_>) {
63            ctx.bind::<_, $st, _>(&self.$field);
64        }
65
66        #[inline]
67        fn ready(
68            &self,
69            ctx: $crate::Ctx<'_, Self, $st>,
70        ) -> impl ::core::future::Future<Output = Result<(), Self::Error>> {
71            $crate::__private::map_output(ctx.ready(&self.$field), |res| res.map_err($err))
72        }
73
74        #[inline]
75        fn shutdown(
76            &self,
77            ctx: $crate::Ctx<'_, Self, $st>,
78        ) -> impl ::core::future::Future<Output = ()> {
79            ctx.shutdown(&self.$field)
80        }
81    };
82    (@go $st:ty; [$($field:tt)+]; map_err = $err:expr $(,)?) => {
83        #[inline]
84        fn bind(&self, ctx: $crate::BindCtx<'_>) {
85            $(ctx.bind::<_, $st, _>(&self.$field);)+
86        }
87
88        fn ready(
89            &self,
90            ctx: $crate::Ctx<'_, Self, $st>,
91        ) -> impl ::core::future::Future<Output = Result<(), Self::Error>> {
92            $crate::__private::map_output(
93                $crate::forward!(@ready ctx, self, $err; $($field)+),
94                |res| res.map(|_| ()),
95            )
96        }
97
98        fn shutdown(
99            &self,
100            ctx: $crate::Ctx<'_, Self, $st>,
101        ) -> impl ::core::future::Future<Output = ()> {
102            $crate::forward!(@shutdown ctx, self; $($field)+)
103        }
104    };
105    (@go $st:ty; []; map_err $($rest:tt)*) => {
106        ::core::compile_error!(
107            "forward!: list at least one service field before `map_err`, e.g. `forward!(St, service, map_err = f)`"
108        );
109    };
110    (@go $st:ty; [$($field:tt)*]; self . $($rest:tt)*) => {
111        ::core::compile_error!(
112            "forward!: write field names without `self.`, e.g. `forward!(St, service)`"
113        );
114    };
115    (@go $st:ty; [$($field:tt)*]; $next:tt . $($rest:tt)*) => {
116        ::core::compile_error!(
117            "forward!: nested field paths are not supported, implement `bind`, `ready`, and `shutdown` manually"
118        );
119    };
120    (@go $st:ty; [$($field:tt)+]; ) => {
121        $crate::forward!(@go $st; [$($field)+]; map_err = ::core::convert::Into::into);
122    };
123    (@go $st:ty; [$($field:tt)*]; $next:tt $(, $($rest:tt)*)?) => {
124        $crate::forward!(@go $st; [$($field)* $next]; $($($rest)*)?);
125    };
126    (@ready $ctx:ident, $this:tt, $err:expr; $field:tt) => {
127        $crate::__private::ready_field($ctx, &$this.$field, $err)
128    };
129    (@ready $ctx:ident, $this:tt, $err:expr; $field:tt $($rest:tt)+) => {
130        $crate::__private::ready_join(
131            $ctx,
132            move |$ctx| $crate::__private::ready_field($ctx, &$this.$field, $err),
133            move |$ctx| $crate::forward!(@ready $ctx, $this, $err; $($rest)+),
134        )
135    };
136    (@shutdown $ctx:ident, $this:tt; $field:tt) => {
137        $ctx.shutdown(&$this.$field)
138    };
139    (@shutdown $ctx:ident, $this:tt; $field:tt $($rest:tt)+) => {
140        $crate::__private::join(
141            $ctx.shutdown(&$this.$field),
142            $crate::forward!(@shutdown $ctx, $this; $($rest)+),
143        )
144    };
145    ($one:tt $(,)?) => {
146        ::core::compile_error!(
147            "forward!: expected a state type and at least one service field, e.g. `forward!(St, service)`"
148        );
149    };
150    ($st:ty, $($rest:tt)+) => {
151        $crate::forward!(@go $st; []; $($rest)+);
152    };
153}
154
155/// Forwards [`crate::Service::bind`] to one or more service fields.
156///
157/// For a single inner service prefer [`crate::forward!`].
158/// For additional sources or mixed pipeline/service children, implement `bind`
159/// explicitly using [`crate::BindCtx`].
160#[doc(hidden)]
161#[macro_export]
162macro_rules! forward_bind {
163    ($st:ty, $($field:tt),+ $(,)?) => {
164        #[inline]
165        fn bind(&self, ctx: $crate::BindCtx<'_>) {
166            $(ctx.bind::<_, $st, _>(&self.$field);)+
167        }
168    };
169    ($st:ty, $this:ident.$field:tt) => {
170        #[inline]
171        fn bind(&$this, ctx: $crate::BindCtx<'_>) {
172            ctx.bind::<_, $st, _>(&$this.$field);
173        }
174    };
175}
176
177/// An implementation of [`crate::Service::ready`] that forwards readiness checks to a field.
178///
179/// Preserves the calling context and any wrapped [`crate::ReadyBinding`]'s
180/// readiness. A raw service field is checked on each forwarded evaluation.
181/// The field must also be wired in `bind`.
182#[doc(hidden)]
183#[macro_export]
184macro_rules! forward_ready {
185    ($st:ty, $field:ident) => {
186        $crate::forward_ready!($st, self.$field, ::core::convert::Into::into);
187    };
188    ($st:ty, $field:ident, $err:expr) => {
189        $crate::forward_ready!($st, self.$field, $err);
190    };
191    ($st:ty, $this:ident.$field:tt) => {
192        $crate::forward_ready!($st, $this.$field, ::core::convert::Into::into);
193    };
194    ($st:ty, $this:ident.$field:tt, $err:expr) => {
195        #[inline]
196        fn ready(
197            &$this,
198            ctx: $crate::Ctx<'_, Self, $st>,
199        ) -> impl ::core::future::Future<Output = Result<(), Self::Error>> {
200            $crate::__private::map_output(ctx.ready(&$this.$field), |res| res.map_err($err))
201        }
202    };
203}
204
205/// An implementation of [`crate::Service::shutdown`] that forwards shutdown checks to a field.
206#[doc(hidden)]
207#[macro_export]
208macro_rules! forward_shutdown {
209    ($st:ty, $field:ident) => {
210        $crate::forward_shutdown!($st, self.$field);
211    };
212    ($st:ty, $this:ident.$field:tt) => {
213        #[inline]
214        fn shutdown(
215            &$this,
216            ctx: $crate::Ctx<'_, Self, $st>,
217        ) -> impl ::core::future::Future<Output = ()> {
218            ctx.shutdown(&$this.$field)
219        }
220    };
221}