Skip to main content

ntex_service/
binding.rs

1use crate::{BindCtx, Ctx, Middleware, Service, readiness::ReadyScope};
2
3/// Middleware that wraps each service in a fresh [`ReadyBinding`].
4///
5/// Each created service gets an independent, notification-invalidated readiness
6/// cache. Successful readiness survives calls and changes to sibling services.
7/// The inner service must subscribe to readiness-change notifications in
8/// [`Service::bind`], as described by [`ReadyBinding`].
9///
10/// Construction does not retain state, bind the service, or check readiness.
11/// The enclosing pipeline or service must bind the returned wrapper before use.
12///
13/// # Example
14///
15/// ```
16/// use ntex_service::{ReadyBindingMiddleware, factory, fn_service};
17///
18/// # async fn example() {
19/// let factory = factory(fn_service(async |req: u32| Ok::<_, ()>(req + 1)))
20///     .apply(ReadyBindingMiddleware);
21///
22/// let pipeline = factory.pipeline(()).await.unwrap();
23/// assert_eq!(pipeline.call(1).await, Ok(2));
24/// # }
25/// ```
26#[derive(Copy, Clone, Default, Debug, PartialEq, Eq)]
27pub struct ReadyBindingMiddleware;
28
29impl<S, St> Middleware<S, St> for ReadyBindingMiddleware {
30    type Service = ReadyBinding<S>;
31
32    #[inline]
33    fn create(&self, _: &St, service: S) -> Self::Service {
34        ReadyBinding::new(service)
35    }
36}
37
38/// A service paired with persistent readiness.
39///
40/// Construct directly with [`Self::new`] or apply [`ReadyBindingMiddleware`]
41/// to a factory to wrap each service it creates.
42///
43/// [`Ctx::ready`] and [`Ctx::call`] reuse the binding's successful readiness
44/// until a subscribed [`crate::ReadyNotifier`] invalidates it. Calls do not
45/// consume readiness. Services whose readiness can change must subscribe through
46/// [`BindCtx::subscribe`] in [`Service::bind`] and notify when it changes.
47/// Direct [`Service::call`] also checks this binding's cache through `Ctx`.
48///
49/// A binding owns its service, not pipeline state. Its scope is allocated lazily
50/// in the first pipeline that binds it. Rebinding within that pipeline reuses
51/// its scope and forwards binding to the wrapped service; binding the same
52/// instance to another pipeline panics.
53///
54/// [`Self::with_data`] assigns user data passed to every [`crate::ReadyCallback`]
55/// registered in this binding's scope. The default value is `0`.
56/// Cloning a binding preserves its data and clones the service into a fresh,
57/// unbound scope.
58/// Use [`std::rc::Rc<ReadyBinding<S>>`] to share readiness within one pipeline.
59/// To share a gate across pipelines, use [`crate::Pipeline`] or
60/// [`crate::pipeline::PipelineState`] and [`crate::ReadyLink`] instead.
61///
62/// Every enclosing service must forward [`Service::bind`] to this binding.
63/// Runtime operations panic if the calling scope has not bound it, rather than
64/// silently adding a dependency or losing readiness notifications.
65#[derive(Debug)]
66pub struct ReadyBinding<S> {
67    service: S,
68    scope: ReadyScope,
69    data: usize,
70}
71
72impl<S> ReadyBinding<S> {
73    /// Pairs a service with a fresh readiness scope and callback data `0`.
74    ///
75    /// Its dependencies are wired when a pipeline or enclosing service binds it.
76    pub fn new(service: S) -> Self {
77        Self::with_data(service, 0)
78    }
79
80    /// Pairs a service with a fresh readiness scope and user-defined callback data.
81    ///
82    /// Every callback registered in this scope receives `data`, including when
83    /// notified by a dependency. The value is installed before the inner
84    /// service's [`Service::bind`] hook and is preserved when the binding is
85    /// cloned or rebound. Construction does not allocate readiness storage.
86    pub fn with_data(service: S, data: usize) -> Self {
87        Self {
88            service,
89            scope: ReadyScope::new(),
90            data,
91        }
92    }
93
94    /// Returns a reference to the wrapped service.
95    pub fn get_ref(&self) -> &S {
96        &self.service
97    }
98
99    /// Transforms the service while preserving its scope, cached readiness, and data.
100    ///
101    /// The transformation must preserve the service's readiness dependencies,
102    /// notification sources, and the validity of any cached readiness. This does
103    /// not rebind the service or invalidate its cache. Use [`Self::new`] for a
104    /// replacement with different dependencies.
105    pub fn map<T>(self, f: impl FnOnce(S) -> T) -> ReadyBinding<T> {
106        ReadyBinding {
107            service: f(self.service),
108            scope: self.scope,
109            data: self.data,
110        }
111    }
112
113    /// Enters this binding's scope from a scope that has bound it.
114    fn enter<'a, T, St>(&'a self, ctx: Ctx<'a, Self, St>) -> Ctx<'a, T, St> {
115        ctx.scope().assert_dependency(&self.scope);
116        ctx.with_scope(&self.scope)
117    }
118
119    #[cfg(test)]
120    pub(crate) fn is_ready(&self) -> bool {
121        self.scope.is_ready()
122    }
123}
124
125impl<S: Clone> Clone for ReadyBinding<S> {
126    fn clone(&self) -> Self {
127        Self::with_data(self.service.clone(), self.data)
128    }
129}
130
131impl<S, St, Req> Service<St, Req> for ReadyBinding<S>
132where
133    S: Service<St, Req>,
134{
135    type Res = S::Res;
136    type Error = S::Error;
137
138    fn bind(&self, ctx: BindCtx<'_>) {
139        ctx.depend_on(&self.scope);
140        self.scope.set_data(self.data);
141        self.service.bind(BindCtx::new(&self.scope));
142    }
143
144    // Enters the scope inside the check closure, so the future stores `ctx`
145    // once; an `async fn` with an entered `ctx` local would keep two copies.
146    #[allow(clippy::manual_async_fn)]
147    fn ready(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = Result<(), Self::Error>> {
148        async move {
149            ctx.scope().assert_dependency(&self.scope);
150            self.scope
151                .check(|| self.service.ready(ctx.with_scope(&self.scope)))
152                .await
153        }
154    }
155
156    // An `async fn` would store `req` and `ctx` twice. The entered context
157    // borrows `self` and `ctx` under one lifetime, so it is created inside the block.
158    #[allow(clippy::manual_async_fn)]
159    fn call(
160        &self,
161        req: Req,
162        ctx: Ctx<'_, Self, St>,
163    ) -> impl Future<Output = Result<Self::Res, Self::Error>> {
164        async move {
165            let ctx = self.enter::<Self, _>(ctx);
166            if !self.scope.is_ready() {
167                // Boxed so the cold readiness wait is not inlined into the call future.
168                Box::pin(ctx.ready_cached(self)).await?;
169            }
170            self.service.call(req, ctx.cast()).await
171        }
172    }
173
174    // See `call`.
175    #[allow(clippy::manual_async_fn)]
176    fn shutdown(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = ()> {
177        async move { self.service.shutdown(self.enter(ctx)).await }
178    }
179}
180
181#[cfg(test)]
182#[path = "../tests/unit/binding.rs"]
183mod tests;