Skip to main content

ntex_service/
pl_state.rs

1use std::{fmt, future::poll_fn, marker::PhantomPinned, ptr, rc::Rc, task::Context, task::Poll};
2
3use crate::ctx::{NO_SLOT, WaitersRef};
4use crate::ready_call::ReadyThenCall;
5use crate::util::{BoxFuture, CallFuture, CallPool, PoolOwner};
6use crate::{BindCtx, Ctx, IntoService, ReadyCallback, ReadyLink, Service};
7
8use crate::pipeline::PipelineBinding;
9use crate::pl_inner::{PipelineApi, PipelineInternalApi, PipelineReadiness, detach};
10use crate::readiness::ReadyScope;
11
12/// Execution container for a service whose state is supplied per operation.
13///
14/// Unlike [`crate::Pipeline`], this type does not own a state value. Callers
15/// provide a state reference when checking readiness, calling, or shutting
16/// down the service.
17///
18/// All bindings share one readiness cache and checker, including bindings with
19/// different state values. Readiness may inspect state, but must describe the
20/// shared pipeline-wide gate. Independent gates require separate pipelines.
21///
22/// Shutdown is advisory, as for [`crate::Pipeline`]: readiness checks return
23/// `Ok(())` once shutdown has started, and calls are still forwarded to the
24/// service. Callers that must stop admitting work check
25/// [`PipelineState::is_shutdown`].
26pub struct PipelineState<St, Req, Res, Err> {
27    api: Rc<dyn PipelineStateApi<St, Req, Res, Err>>,
28}
29
30impl<St, Req, Res, Err> PipelineState<St, Req, Res, Err>
31where
32    St: 'static,
33    Req: 'static,
34    Res: 'static,
35    Err: 'static,
36{
37    #[inline]
38    /// Creates a state-independent pipeline containing `service`.
39    pub fn new<S>(service: impl IntoService<S, St, Req>) -> Self
40    where
41        S: Service<St, Req, Res = Res, Error = Err> + 'static,
42        St: 'static,
43    {
44        let waiters = WaitersRef::new();
45        let s = service.into_service();
46        s.bind(BindCtx::new(waiters.scope()));
47        PipelineState {
48            api: Rc::new(PipelineInner {
49                s,
50                readiness: PipelineReadiness::new(waiters.scope()),
51                waiters,
52                _pinned: PhantomPinned,
53                pool: CallPool::new(),
54            }),
55        }
56    }
57
58    #[inline]
59    /// Returns when the pipeline is ready to process requests.
60    ///
61    /// Successful readiness is shared and reused until a subscribed
62    /// [`crate::ReadyNotifier`] invalidates it. Calls do not consume it.
63    /// Reusing valid readiness does not allocate a readiness future.
64    ///
65    /// The first caller that finds readiness invalid runs the shared check in its
66    /// own future, and other waiters wait for it. Like a held lock, a pending
67    /// future must be polled or dropped: keeping it alive without polling stalls
68    /// every other readiness waiter on this pipeline.
69    /// Returns successfully if pipeline shutdown has started.
70    pub fn ready<'a>(&'a self, st: &'a St) -> impl Future<Output = Result<(), Err>> {
71        let mut check = None;
72        poll_fn(move |cx| {
73            let check = match check {
74                Some(ref mut check) => check,
75                None if self.is_ready() || self.is_shutdown() => return Poll::Ready(Ok(())),
76                None => check.insert(self.api.ready(0, st)),
77            };
78            check.as_mut().poll(cx)
79        })
80    }
81
82    #[inline]
83    /// Returns `true` while the pipeline's shared readiness is valid.
84    ///
85    /// Does not run or register a readiness check. `false` means readiness is
86    /// unknown or was invalidated, not that the service is not ready.
87    pub fn is_ready(&self) -> bool {
88        self.api.scope().is_ready()
89    }
90
91    #[inline]
92    /// Waits for readiness, then calls the service with `st`.
93    ///
94    /// Reuses valid shared readiness without consuming it. Calls are forwarded
95    /// even after shutdown has started; see [`PipelineState`].
96    pub fn call<'a>(&'a self, req: Req, st: &'a St) -> impl Future<Output = Result<Res, Err>> {
97        self.api.call(req, st)
98    }
99
100    #[inline]
101    /// Shuts down the enclosed service.
102    ///
103    /// Marks the pipeline as shutting down, then waits for the service's
104    /// shutdown. Later calls are not rejected; see [`PipelineState`].
105    pub fn shutdown<'a>(&'a self, st: &'a St) -> impl Future<Output = ()> {
106        self.api.shutdown(0, st)
107    }
108
109    #[inline]
110    /// Checks whether pipeline shutdown has been initiated.
111    ///
112    /// The pipeline does not reject calls after shutdown; callers use this to
113    /// stop admitting new work.
114    pub fn is_shutdown(&self) -> bool {
115        self.api.is_shutdown()
116    }
117
118    #[inline]
119    /// Returns `Ready` when the pipeline is ready to process requests.
120    ///
121    /// Registers the task for readiness changes and reuses valid shared
122    /// readiness. A pending check is retained by the pipeline, even if this
123    /// task stops polling; other callers can continue driving it.
124    /// The retained check and its wake sources run on this pipeline's thread.
125    /// Its checker wakers must also be finally dropped on that thread, even
126    /// after the pipeline is dropped; foreign wakes or final drops panic.
127    /// Returns `Ready(Ok(()))` if pipeline shutdown has started, like
128    /// [`crate::Pipeline::poll_ready`].
129    pub fn poll_ready(&self, cx: &mut Context<'_>, st: &St) -> Poll<Result<(), Err>>
130    where
131        St: Clone,
132    {
133        if self.is_shutdown() {
134            Poll::Ready(Ok(()))
135        } else {
136            self.api.poll_ready(cx, st)
137        }
138    }
139
140    #[inline]
141    /// Creates a binding that accepts state per call.
142    ///
143    /// The binding can be used to call the service.
144    pub fn bind(&self) -> PipelineStateBinding<St, Req, Res, Err> {
145        PipelineStateBinding {
146            idx: self.api.reg(),
147            api: self.api.clone(),
148        }
149    }
150
151    #[inline]
152    /// Creates a standard pipeline binding by attaching an owned state value.
153    ///
154    /// The binding can be used to call the service.
155    pub fn bind_state(&self, st: St) -> PipelineBinding<Req, Res, Err>
156    where
157        St: Clone,
158    {
159        let internal = PipelineInternal {
160            st,
161            api: self.api.clone(),
162        };
163
164        PipelineBinding::with(self.api.reg(), PipelineApi::with(internal))
165    }
166
167    #[inline]
168    /// Registers a callback for notifications reaching this pipeline's scope.
169    ///
170    /// Registration is shared by all bindings, regardless of their state, and
171    /// persists until the scope is dropped. Repeated registration of the same
172    /// handle is idempotent. The callback receives `0` for this root scope.
173    /// See [`ReadyCallback`] for notification semantics.
174    pub fn on_notify(&self, callback: &ReadyCallback) {
175        self.api.scope().on_notify(callback);
176    }
177
178    #[inline]
179    /// Registers this pipeline as a readiness dependency of the enclosing service.
180    ///
181    /// Call from [`Service::bind`] so changes to this pipeline's readiness also
182    /// invalidate the enclosing scope. Repeated registration is idempotent and
183    /// does not rebind the inner service or create another runtime handle.
184    pub fn bind_to(&self, ctx: &BindCtx<'_>) {
185        ctx.subscribe_pipeline(&self.readiness_link());
186    }
187
188    /// Returns this pipeline's readiness endpoint, shared by all state bindings.
189    ///
190    /// Register with [`BindCtx::subscribe_pipeline`]. The link propagates
191    /// invalidation without checking readiness or retaining the pipeline.
192    pub fn readiness_link(&self) -> ReadyLink {
193        self.api.scope().readiness_link()
194    }
195}
196
197impl<St, Req, Res, Err> Drop for PipelineState<St, Req, Res, Err> {
198    #[inline]
199    fn drop(&mut self) {
200        self.api.unreg(0);
201    }
202}
203
204// ========================== `PipelineStateBinding` ===========================
205
206/// An independently registered handle to a [`PipelineState`].
207pub struct PipelineStateBinding<St, Req, Res, Err> {
208    idx: u32,
209    api: Rc<dyn PipelineStateApi<St, Req, Res, Err>>,
210}
211
212impl<St, Req, Res, Err> Drop for PipelineStateBinding<St, Req, Res, Err> {
213    #[inline]
214    fn drop(&mut self) {
215        self.api.unreg(self.idx);
216    }
217}
218
219impl<St, Req, Res, Err> Clone for PipelineStateBinding<St, Req, Res, Err> {
220    #[inline]
221    fn clone(&self) -> Self {
222        PipelineStateBinding {
223            idx: self.api.reg(),
224            api: self.api.clone(),
225        }
226    }
227}
228
229impl<St, Req, Res, Err> PipelineStateBinding<St, Req, Res, Err>
230where
231    St: 'static,
232    Req: 'static,
233    Res: 'static,
234    Err: 'static,
235{
236    #[inline]
237    /// Waits for readiness, then calls the service with `st`.
238    ///
239    /// Reuses valid shared readiness without consuming it, regardless of `st`.
240    /// Calls are forwarded even after shutdown has started; see [`PipelineState`].
241    pub fn call<'a>(&'a self, req: Req, st: &'a St) -> impl Future<Output = Result<Res, Err>> {
242        self.api.call(req, st)
243    }
244
245    #[inline]
246    /// Checks whether pipeline shutdown has been initiated.
247    ///
248    /// See [`PipelineState::is_shutdown`].
249    pub fn is_shutdown(&self) -> bool {
250        self.api.is_shutdown()
251    }
252
253    #[inline]
254    /// Registers a callback on the shared pipeline scope, independently of state.
255    ///
256    /// The callback receives `0` for this root scope.
257    /// Dropping this binding does not remove the registration.
258    /// See [`PipelineState::on_notify`] and [`ReadyCallback`] for details.
259    pub fn on_notify(&self, callback: &ReadyCallback) {
260        self.api.scope().on_notify(callback);
261    }
262
263    #[inline]
264    /// Registers this handle's pipeline as a readiness dependency.
265    ///
266    /// Call from [`Service::bind`]. See [`PipelineState::bind_to`] for details.
267    pub fn bind_to(&self, ctx: &BindCtx<'_>) {
268        ctx.subscribe_pipeline(&self.readiness_link());
269    }
270
271    /// Returns the shared pipeline's readiness endpoint.
272    ///
273    /// See [`PipelineState::readiness_link`] and [`ReadyLink`].
274    pub fn readiness_link(&self) -> ReadyLink {
275        self.api.scope().readiness_link()
276    }
277}
278
279// ========================== `PipelineApi` ===========================
280
281struct PipelineInternal<St, Req, Res, Err> {
282    st: St,
283    api: Rc<dyn PipelineStateApi<St, Req, Res, Err>>,
284}
285
286// Owner of `call_static` futures. One pointer, like the `&PipelineInner` owner
287// of `call` futures, so both kinds of futures share the pool's block layout.
288impl<St, Req, Res, Err> PoolOwner for Rc<PipelineInternal<St, Req, Res, Err>> {
289    fn pool(&self) -> &CallPool {
290        self.api.pool()
291    }
292}
293
294impl<St, Req, Res, Err> PipelineInternalApi<Req, Res, Err> for PipelineInternal<St, Req, Res, Err> {
295    fn scope(&self) -> &ReadyScope {
296        self.api.scope()
297    }
298
299    fn reg(&self) -> u32 {
300        self.api.reg()
301    }
302
303    fn unreg(&self, idx: u32) {
304        self.api.unreg(idx);
305    }
306
307    fn ready(&self, idx: u32) -> BoxFuture<'_, Result<(), Err>> {
308        self.api.ready(idx, &self.st)
309    }
310
311    fn call(&self, req: Req) -> CallFuture<'_, Result<Res, Err>> {
312        self.api.call(req, &self.st)
313    }
314
315    fn call_static(self: Rc<Self>, req: Req) -> CallFuture<'static, Result<Res, Err>> {
316        self.api.clone().call_static(req, self)
317    }
318
319    fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Err>> {
320        unreachable!()
321    }
322
323    fn poll_shutdown(&self, _: &mut Context<'_>) -> Poll<()> {
324        unreachable!()
325    }
326
327    fn is_shutdown(&self) -> bool {
328        self.api.is_shutdown()
329    }
330}
331
332// ========================== `PipelineStateApi` ===========================
333
334struct PipelineInner<S, E> {
335    s: S,
336    waiters: WaitersRef,
337    readiness: PipelineReadiness<E>,
338    // The pending readiness future borrows the other fields. `!Unpin` keeps
339    // `&mut self` in `Drop` from invalidating those borrows.
340    _pinned: PhantomPinned,
341    // Blocks of finished call futures, shared by all states. Declared last,
342    // so it is dropped after the other fields.
343    pool: CallPool,
344}
345
346impl<S, E> PoolOwner for &PipelineInner<S, E> {
347    fn pool(&self) -> &CallPool {
348        &self.pool
349    }
350}
351
352impl<S, E> PipelineInner<S, E> {
353    fn call_impl<'a, St, Req>(
354        &'a self,
355        idx: u32,
356        req: Req,
357        st: &'a St,
358    ) -> impl Future<Output = Result<S::Res, E>>
359    where
360        S: Service<St, Req, Error = E>,
361    {
362        ReadyThenCall::new(
363            (self, Ctx::<'a, S, St>::new(idx, &self.waiters, st)),
364            req,
365            |&(this, ctx): &(&'a Self, Ctx<'a, S, St>)| {
366                (!this.waiters.scope().is_ready())
367                    .then(|| this.readiness.ready(move || ctx.ready_generation(&this.s)))
368            },
369            |(this, ctx): (&'a Self, Ctx<'a, S, St>), req| this.s.call(req, ctx.into_call()),
370        )
371    }
372}
373
374impl<S, E> Drop for PipelineInner<S, E> {
375    fn drop(&mut self) {
376        // The readiness future borrows `s` and `waiters`, so it must be dropped
377        // before the fields it references
378        self.readiness.cancel();
379    }
380}
381
382trait PipelineStateApi<St, Req, Res, Err> {
383    fn scope(&self) -> &ReadyScope;
384
385    fn pool(&self) -> &CallPool;
386
387    fn reg(&self) -> u32;
388    fn unreg(&self, idx: u32);
389
390    /// Calls the service without registering a waiter slot.
391    fn call<'a>(&'a self, req: Req, st: &'a St) -> CallFuture<'a, Result<Res, Err>>
392    where
393        Req: 'a;
394
395    /// Calls with a future that keeps `owner` alive. `owner` holds the state,
396    /// and its `api` must be the `Rc` that holds `self`.
397    fn call_static(
398        &self,
399        req: Req,
400        owner: Rc<PipelineInternal<St, Req, Res, Err>>,
401    ) -> CallFuture<'static, Result<Res, Err>>;
402
403    fn ready<'a>(&'a self, idx: u32, st: &'a St) -> BoxFuture<'a, Result<(), Err>>
404    where
405        Req: 'a;
406
407    fn poll_ready(&self, cx: &mut Context<'_>, st: &St) -> Poll<Result<(), Err>>
408    where
409        St: Clone;
410
411    fn shutdown<'a>(&'a self, idx: u32, st: &'a St) -> BoxFuture<'a, ()>;
412
413    fn is_shutdown(&self) -> bool;
414}
415
416impl<S, St, Req, E> PipelineStateApi<St, Req, S::Res, S::Error> for PipelineInner<S, E>
417where
418    S: Service<St, Req, Error = E> + 'static,
419    St: 'static,
420    Req: 'static,
421    E: 'static,
422{
423    fn scope(&self) -> &ReadyScope {
424        self.waiters.scope()
425    }
426
427    fn pool(&self) -> &CallPool {
428        &self.pool
429    }
430
431    fn reg(&self) -> u32 {
432        self.waiters.insert()
433    }
434
435    fn unreg(&self, idx: u32) {
436        if idx == 0 {
437            self.readiness.unregister();
438        }
439        self.waiters.remove(idx);
440    }
441
442    fn ready<'a>(&'a self, idx: u32, st: &'a St) -> BoxFuture<'a, Result<(), S::Error>>
443    where
444        Req: 'a,
445    {
446        Box::pin(self.readiness.ready(move || async move {
447            Ctx::<'_, S, St>::new(idx, &self.waiters, st)
448                .ready_generation(&self.s)
449                .await
450        }))
451    }
452
453    fn shutdown<'a>(&'a self, idx: u32, st: &'a St) -> BoxFuture<'a, ()> {
454        Box::pin(async move {
455            self.waiters.shutdown();
456            self.readiness.cancel();
457
458            Ctx::<'_, S, St>::new(idx, &self.waiters, st)
459                .shutdown(&self.s)
460                .await;
461        })
462    }
463
464    fn call<'a>(&'a self, req: Req, st: &'a St) -> CallFuture<'a, Result<S::Res, S::Error>>
465    where
466        Req: 'a,
467    {
468        CallFuture::pooled(self, |&pl| pl.call_impl(NO_SLOT, req, st))
469    }
470
471    fn call_static(
472        &self,
473        req: Req,
474        owner: Rc<PipelineInternal<St, Req, S::Res, S::Error>>,
475    ) -> CallFuture<'static, Result<S::Res, S::Error>> {
476        debug_assert!(ptr::addr_eq(Rc::as_ptr(&owner.api), self));
477        CallFuture::pooled(owner, |owner| {
478            // SAFETY: `owner` and `owner.api`, which holds `self`, are `Rc`-allocated,
479            // and the call future is dropped before `owner`
480            let (pl, st) = unsafe { (detach(self), &detach(&**owner).st) };
481            pl.call_impl(NO_SLOT, req, st)
482        })
483    }
484
485    fn poll_ready(&self, cx: &mut Context<'_>, st: &St) -> Poll<Result<(), S::Error>>
486    where
487        St: Clone,
488    {
489        self.readiness.poll_ready(cx, || {
490            // SAFETY: the future is stored in `self.readiness`
491            let pl = unsafe { detach(self) };
492            let st = st.clone();
493            Box::pin(async move {
494                let registration = pl.waiters.register();
495                Ctx::<'_, S, St>::new(registration.idx, &pl.waiters, &st)
496                    .ready_generation(&pl.s)
497                    .await
498            })
499        })
500    }
501
502    fn is_shutdown(&self) -> bool {
503        self.waiters.is_shutdown()
504    }
505}
506
507impl<St, Req, Res, Err> fmt::Debug for PipelineState<St, Req, Res, Err> {
508    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
509        f.debug_struct("PipelineState").finish()
510    }
511}
512
513impl<St, Req, Res, Err> fmt::Debug for PipelineStateBinding<St, Req, Res, Err> {
514    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
515        f.debug_struct("PipelineStateBinding").finish()
516    }
517}
518
519#[cfg(test)]
520#[path = "../tests/unit/pl_state.rs"]
521mod tests;