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    /// Enters this binding's scope from a scope that has bound it.
95    fn enter<'a, T, St>(&'a self, ctx: Ctx<'a, Self, St>) -> Ctx<'a, T, St> {
96        ctx.scope().assert_dependency(&self.scope);
97        ctx.with_scope(&self.scope)
98    }
99
100    #[cfg(test)]
101    pub(crate) fn is_ready(&self) -> bool {
102        self.scope.is_ready()
103    }
104}
105
106impl<S: Clone> Clone for ReadyBinding<S> {
107    fn clone(&self) -> Self {
108        Self::with_data(self.service.clone(), self.data)
109    }
110}
111
112impl<S, St, Req> Service<St, Req> for ReadyBinding<S>
113where
114    S: Service<St, Req>,
115{
116    type Res = S::Res;
117    type Error = S::Error;
118
119    fn bind(&self, ctx: BindCtx<'_>) {
120        ctx.depend_on(&self.scope);
121        self.scope.set_data(self.data);
122        self.service.bind(BindCtx::new(&self.scope));
123    }
124
125    async fn ready(&self, ctx: Ctx<'_, Self, St>) -> Result<(), Self::Error> {
126        let ctx = self.enter(ctx);
127        self.scope.check(|| self.service.ready(ctx)).await
128    }
129
130    async fn call(&self, req: Req, ctx: Ctx<'_, Self, St>) -> Result<Self::Res, Self::Error> {
131        let ctx = self.enter::<Self, _>(ctx);
132        if !ctx.is_call_nowait() {
133            ctx.ready_cached(self).await?;
134        }
135        self.service.call(req, ctx.cast()).await
136    }
137
138    async fn shutdown(&self, ctx: Ctx<'_, Self, St>) {
139        self.service.shutdown(self.enter(ctx)).await;
140    }
141}
142
143#[cfg(test)]
144#[path = "../tests/unit/binding.rs"]
145mod tests;