Skip to main content

ntex_service/
ready.rs

1use crate::{
2    BindCtx, Ctx, IntoService, IntoServiceFactory, ReadyBinding, Service, ServiceChain,
3    ServiceChainFactory, ServiceFactory,
4};
5
6/// Wraps a service with independent, notification-invalidated readiness.
7///
8/// Unlike raw children of combinators, the wrapped service retains its own
9/// successful readiness and checks it on each call. Changes to a sibling do not
10/// discard this cache. The service must subscribe to all readiness-change
11/// sources in [`Service::bind`] and notify when readiness changes.
12///
13/// Calls do not consume readiness. Cloning the wrapper creates a fresh cache;
14/// an [`std::rc::Rc`] around the wrapper shares the service and its cache.
15///
16/// ```
17/// use ntex_service::{Service, fn_service, ready};
18///
19/// # async fn example() -> Result<(), ()> {
20/// let pipeline = ready(fn_service(async |req: u8| Ok::<_, ()>(req)))
21///     .and_then(ready(fn_service(async |req: u8| Ok::<_, ()>(req + 1))))
22///     .pipeline(());
23/// assert_eq!(pipeline.call(1).await?, 2);
24/// # Ok(())
25/// # }
26/// ```
27pub fn ready<S, St, Req>(service: impl IntoService<S, St, Req>) -> ServiceChain<Ready<S>, St, Req>
28where
29    S: Service<St, Req>,
30{
31    crate::service(Ready {
32        service: ReadyBinding::new(service.into_service()),
33    })
34}
35
36/// Wraps each service created by a factory with independent readiness.
37///
38/// Every successful creation gets a fresh readiness cache, even if the factory
39/// returns shared handles to the same inner service. See [`ready()`].
40pub fn ready_factory<Sf, St, Req>(
41    factory: impl IntoServiceFactory<Sf, St, Req>,
42) -> ServiceChainFactory<ReadyFactory<Sf>, St, Req>
43where
44    Sf: ServiceFactory<St, Req>,
45{
46    crate::factory(ReadyFactory {
47        factory: factory.into_factory(),
48    })
49}
50
51/// Service produced by [`ready()`].
52///
53/// Uses its own readiness cache, independently of the calling scope's cache.
54/// Enclosing services must forward [`Service::bind`] to this wrapper.
55#[derive(Debug, Clone)]
56pub struct Ready<S> {
57    service: ReadyBinding<S>,
58}
59
60impl<S, St, Req> Service<St, Req> for Ready<S>
61where
62    S: Service<St, Req>,
63{
64    type Res = S::Res;
65    type Error = S::Error;
66
67    #[inline]
68    fn bind(&self, ctx: BindCtx<'_>) {
69        ctx.bind(&self.service);
70    }
71
72    #[inline]
73    fn ready(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = Result<(), Self::Error>> {
74        self.service.ready(ctx.cast())
75    }
76
77    #[inline]
78    fn call(
79        &self,
80        req: Req,
81        ctx: Ctx<'_, Self, St>,
82    ) -> impl Future<Output = Result<Self::Res, Self::Error>> {
83        self.service.call(req, ctx.cast())
84    }
85
86    #[inline]
87    fn shutdown(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = ()> {
88        self.service.shutdown(ctx.cast())
89    }
90}
91
92/// Factory produced by [`ready_factory`].
93#[derive(Debug, Clone)]
94pub struct ReadyFactory<Sf> {
95    factory: Sf,
96}
97
98impl<Sf, St, Req> ServiceFactory<St, Req> for ReadyFactory<Sf>
99where
100    Sf: ServiceFactory<St, Req>,
101{
102    type Res = Sf::Res;
103    type Error = Sf::Error;
104    type InitError = Sf::InitError;
105    type Service = Ready<Sf::Service>;
106
107    #[inline]
108    async fn create(&self, st: &St) -> Result<Self::Service, Self::InitError> {
109        Ok(Ready {
110            service: ReadyBinding::new(self.factory.create(st).await?),
111        })
112    }
113}