Skip to main content

ntex_service/
ctx.rs

1use std::{
2    cell, fmt, future::Future, marker, mem, ops, pin, pin::Pin, rc::Rc, task::Context, task::Poll,
3    task::Waker,
4};
5
6use crate::readiness::{Generation, ReadyScope, RunCheck, ScopeStore};
7use crate::{BindCtx, Service, ServiceFactory, ready_call::ReadyThenCall};
8
9/// Waiter index of contexts of individual pipeline calls.
10///
11/// Calls do not register a waiter slot; their readiness checks insert one
12/// only when they need the pipeline gate.
13pub(crate) const NO_SLOT: u32 = u32::MAX - 1;
14
15/// Context provided to [`Service`] lifecycle methods.
16///
17/// A context gives a service access to pipeline state and coordinates calls to
18/// inner services with the pipeline's readiness and shutdown machinery.
19/// It borrows the current readiness scope from a pipeline or service binding.
20/// Copying or mapping the context preserves that scope; calling a binding
21/// selects the binding's own scope without changing the caller's context.
22/// Existing dependencies must be registered in [`Service::bind`] using
23/// [`BindCtx`]. Lazily created children can be initialized with [`Ctx::create`];
24/// readiness checks, calls, and shutdown never register dependencies implicitly.
25pub struct Ctx<'a, Svc: ?Sized, St = ()> {
26    idx: u32,
27    st: &'a St,
28    waiters: &'a WaitersRef,
29    scope: &'a ReadyScope,
30    // Readiness checks made while handling a call don't wait for the pipeline gate.
31    in_call: bool,
32    _t: marker::PhantomData<Rc<Svc>>,
33}
34
35#[derive(Debug)]
36pub(crate) struct WaitersRef {
37    scope: ReadyScope,
38    inner: Rc<WaitersInner>,
39}
40
41#[derive(Debug)]
42pub(crate) struct WaitersInner {
43    pub(crate) scopes: ScopeStore,
44    cur: cell::Cell<u32>,
45    running: cell::Cell<bool>,
46    shutdown: cell::Cell<bool>,
47    wakers: cell::UnsafeCell<Vec<u32>>,
48    /// Reused buffer for wakers collected by `notify`.
49    scratch: cell::RefCell<Vec<Waker>>,
50    indexes: cell::UnsafeCell<slab::Slab<Option<Waker>>>,
51    /// Wakers of pending call-time checks that bypass the gate owner.
52    calls: cell::UnsafeCell<slab::Slab<Option<Waker>>>,
53}
54
55impl WaitersRef {
56    pub(crate) fn new() -> Self {
57        let mut waiters = slab::Slab::with_capacity(4);
58        waiters.insert(None);
59        let inner = Rc::new(WaitersInner {
60            scopes: ScopeStore::default(),
61            cur: cell::Cell::new(u32::MAX),
62            running: cell::Cell::new(false),
63            shutdown: cell::Cell::new(false),
64            indexes: cell::UnsafeCell::new(waiters),
65            calls: cell::UnsafeCell::new(slab::Slab::new()),
66            wakers: cell::UnsafeCell::new(Vec::default()),
67            scratch: cell::RefCell::default(),
68        });
69        WaitersRef {
70            scope: ReadyScope::root(inner.clone()),
71            inner,
72        }
73    }
74
75    #[allow(clippy::mut_from_ref)]
76    pub(crate) fn get(&self) -> &mut slab::Slab<Option<Waker>> {
77        // SAFETY: `WaitersRef` is `!Sync`, and callers do not hold the returned
78        // reference across calls that access `indexes` again.
79        unsafe { &mut *self.indexes.get() }
80    }
81
82    #[allow(clippy::mut_from_ref)]
83    fn get_calls(&self) -> &mut slab::Slab<Option<Waker>> {
84        // SAFETY: `WaitersRef` is `!Sync`, and callers do not hold the returned
85        // reference across calls that access `calls` again.
86        unsafe { &mut *self.calls.get() }
87    }
88
89    #[allow(clippy::mut_from_ref)]
90    pub(crate) fn get_wakers(&self) -> &mut Vec<u32> {
91        // SAFETY: `WaitersRef` is `!Sync`, and callers do not hold the returned
92        // reference across calls that access `wakers` again.
93        unsafe { &mut *self.wakers.get() }
94    }
95
96    fn queue_wake(&self, idx: u32) {
97        let wakers = self.get_wakers();
98        if !wakers.contains(&idx) {
99            wakers.push(idx);
100        }
101    }
102
103    pub(crate) fn insert(&self) -> u32 {
104        self.get().insert(None) as u32
105    }
106
107    pub(crate) fn remove(&self, idx: u32) {
108        self.get().remove(idx as usize);
109
110        if self.cur.get() == idx {
111            self.notify();
112        }
113    }
114
115    pub(crate) fn notify(&self) {
116        // Collect before waking, wakers can re-enter. Both buffers keep their capacity.
117        let mut wakers = self.scratch.take();
118        let indexes = self.get();
119        for idx in self.get_wakers().drain(..) {
120            if let Some(item) = indexes.get_mut(idx as usize)
121                && let Some(waker) = item.take()
122            {
123                wakers.push(waker);
124            }
125        }
126        self.take_calls(&mut wakers);
127
128        self.cur.set(u32::MAX);
129        self.wake_all(wakers);
130    }
131
132    fn take_calls(&self, wakers: &mut Vec<Waker>) {
133        let calls = self.get_calls();
134        if !calls.is_empty() {
135            wakers.extend(calls.iter_mut().filter_map(|(_, waker)| waker.take()));
136        }
137    }
138
139    fn wake_all(&self, mut wakers: Vec<Waker>) {
140        for waker in wakers.drain(..) {
141            waker.wake();
142        }
143        // A reentrant notify may have stored its own buffer, keep the larger one.
144        let mut scratch = self.scratch.borrow_mut();
145        if wakers.capacity() > scratch.capacity() {
146            *scratch = wakers;
147        }
148    }
149
150    /// Wakes the gate owner and pending call-time checks after a call-time
151    /// check that bypassed the owner completes or is dropped.
152    ///
153    /// The check may have replaced their wakers in a shared service. Nothing to
154    /// do without an owner: pending call-time checks were woken when the owner
155    /// released the gate, and later polls take the free gate.
156    fn wake_checks(&self) {
157        let cur = self.cur.get();
158        if cur == u32::MAX {
159            return;
160        }
161        let mut wakers = self.scratch.take();
162        // Clone outside the slab borrow, cloning can re-enter and modify it.
163        if let Some(waker) = self.get().get_mut(cur as usize).and_then(Option::take) {
164            wakers.push(waker.clone());
165            if let Some(slot @ None) = self.get().get_mut(cur as usize) {
166                *slot = Some(waker);
167            }
168        }
169        self.take_calls(&mut wakers);
170        self.wake_all(wakers);
171    }
172
173    /// Stores `waker` in the slab slot `key` unless the slot already holds an
174    /// equivalent waker. Returns `false` if the slot does not exist.
175    ///
176    /// Cloning and dropping wakers runs user code that can re-enter and modify
177    /// the slab, so no reference into the slab is held across either.
178    fn store_waker(
179        &self,
180        slab: fn(&Self) -> &mut slab::Slab<Option<Waker>>,
181        key: u32,
182        waker: &Waker,
183    ) -> bool {
184        match slab(self).get(key as usize) {
185            None => return false,
186            Some(Some(w)) if w.will_wake(waker) => return true,
187            Some(_) => {}
188        }
189        let waker = waker.clone();
190        let old = match slab(self).get_mut(key as usize) {
191            Some(slot) => slot.replace(waker),
192            // removed by re-entrant code
193            None => Some(waker),
194        };
195        drop(old);
196        true
197    }
198
199    fn remove_call(&self, key: &mut Option<u32>) {
200        if let Some(key) = key.take() {
201            self.get_calls().remove(key as usize);
202        }
203    }
204
205    /// Runs a readiness check made while handling a call.
206    ///
207    /// Takes the gate if it is free. Otherwise runs without waiting for the
208    /// owner, which can wait for resources held by this call.
209    fn run_call<F, R>(
210        &self,
211        idx: &mut u32,
212        key: &mut Option<u32>,
213        cx: &mut Context<'_>,
214        f: F,
215    ) -> Poll<R>
216    where
217        F: FnOnce(&mut Context<'_>) -> Poll<R>,
218    {
219        let cur = self.cur.get();
220        if cur == u32::MAX || cur == *idx {
221            self.remove_call(key);
222            return self.run(self.slot(idx), cx, f);
223        }
224
225        let result = f(cx);
226        if result.is_pending() {
227            if !key.is_some_and(|key| self.store_waker(Self::get_calls, key, cx.waker())) {
228                let waker = cx.waker().clone();
229                *key = Some(self.get_calls().insert(Some(waker)) as u32);
230            }
231        } else {
232            self.remove_call(key);
233            self.wake_checks();
234        }
235        result
236    }
237
238    pub(crate) fn run<F, R>(&self, idx: u32, cx: &mut Context<'_>, f: F) -> Poll<R>
239    where
240        F: FnOnce(&mut Context<'_>) -> Poll<R>,
241    {
242        // store the caller's waker for queued wake-ups,
243        // nested readiness checks poll with the same waker
244        self.store_waker(Self::get, idx, cx.waker());
245
246        let cur = self.cur.get();
247        if cur == u32::MAX {
248            self.cur.set(idx);
249        } else if cur != idx {
250            // Another pipeline binding owns the readiness check.
251            self.queue_wake(idx);
252            return Poll::Pending;
253        }
254
255        // Only the outermost readiness check manages waiters.
256        if self.running.replace(true) {
257            return f(cx);
258        }
259        let guard = RunGuard(self);
260        let result = f(cx);
261        mem::forget(guard);
262        if result.is_pending() {
263            self.queue_wake(idx);
264        } else {
265            self.notify();
266        }
267        self.running.set(false);
268        result
269    }
270
271    /// Returns the waiter slot of a check, inserting one for a pipeline call.
272    fn slot(&self, idx: &mut u32) -> u32 {
273        if *idx == NO_SLOT {
274            *idx = self.insert();
275        }
276        *idx
277    }
278
279    pub(crate) fn shutdown(&self) {
280        self.shutdown.set(true);
281    }
282
283    pub(crate) fn scope(&self) -> &ReadyScope {
284        &self.scope
285    }
286
287    pub(crate) fn register(&self) -> WaiterRegistration<'_> {
288        WaiterRegistration {
289            idx: self.insert(),
290            waiters: self,
291        }
292    }
293
294    pub(crate) fn is_shutdown(&self) -> bool {
295        self.shutdown.get()
296    }
297}
298
299impl ops::Deref for WaitersRef {
300    type Target = WaitersInner;
301
302    fn deref(&self) -> &Self::Target {
303        &self.inner
304    }
305}
306
307impl Drop for WaitersRef {
308    fn drop(&mut self) {
309        // Scope/observer handles can outlive the scheduling owner.
310        let indexes = mem::take(self.get());
311        let calls = mem::take(self.get_calls());
312        let scratch = self.scratch.take();
313        self.get_wakers().clear();
314        drop((indexes, calls, scratch));
315    }
316}
317
318/// Releases readiness-check ownership if the check unwinds,
319/// so other bindings are woken and can retry.
320struct RunGuard<'a>(&'a WaitersRef);
321
322impl Drop for RunGuard<'_> {
323    fn drop(&mut self) {
324        self.0.running.set(false);
325        self.0.notify();
326    }
327}
328
329pub(crate) struct WaiterRegistration<'a> {
330    pub(crate) idx: u32,
331    waiters: &'a WaitersRef,
332}
333
334impl Drop for WaiterRegistration<'_> {
335    fn drop(&mut self) {
336        self.waiters.remove(self.idx);
337    }
338}
339
340impl<'a, Svc, St> Ctx<'a, Svc, St> {
341    pub(crate) fn new(idx: u32, waiters: &'a WaitersRef, st: &'a St) -> Self {
342        Self {
343            idx,
344            waiters,
345            st,
346            scope: &waiters.scope,
347            in_call: false,
348            _t: marker::PhantomData,
349        }
350    }
351
352    pub(crate) fn scope(&self) -> &'a ReadyScope {
353        self.scope
354    }
355
356    pub(crate) fn cast<S>(self) -> Ctx<'a, S, St> {
357        self.with_scope(self.scope)
358    }
359
360    pub(crate) fn with_scope<S>(self, scope: &'a ReadyScope) -> Ctx<'a, S, St> {
361        Ctx {
362            idx: self.idx,
363            st: self.st,
364            waiters: self.waiters,
365            scope,
366            in_call: self.in_call,
367            _t: marker::PhantomData,
368        }
369    }
370
371    /// Marks a context passed to [`Service::call`].
372    pub(crate) fn into_call(mut self) -> Self {
373        self.in_call = true;
374        self
375    }
376
377    #[inline]
378    /// Returns the identifier of the current pipeline binding.
379    ///
380    /// Contexts of calls made through a pipeline or a pipeline binding are not
381    /// bound to a waiter slot and share a placeholder identifier.
382    pub fn id(&self) -> u32 {
383        self.idx
384    }
385
386    #[inline]
387    /// Returns the pipeline state.
388    pub fn st(&self) -> &'a St {
389        self.st
390    }
391
392    /// Creates a child service and binds it to this context's readiness scope.
393    ///
394    /// Uses the current pipeline state to create the service, then invokes its
395    /// [`Service::bind`] hook before returning it. Successful creation invalidates
396    /// this scope's cached readiness and its ancestors. Failed or cancelled
397    /// creation does not bind a service or change this scope's dependencies.
398    ///
399    /// The service is returned unchanged, without checking readiness or adding
400    /// a cache. Use [`crate::ready_factory`] for independent child readiness.
401    /// Retain the created service for subsequent calls rather than recreating it
402    /// on each readiness check. Other scopes must bind it separately before use.
403    #[inline]
404    pub async fn create<Sf, Req>(&self, factory: &Sf) -> Result<Sf::Service, Sf::InitError>
405    where
406        Sf: ServiceFactory<St, Req>,
407    {
408        let service = factory.create(self.st).await?;
409        service.bind(BindCtx::new(self.scope));
410        self.scope.reset_root();
411        Ok(service)
412    }
413
414    /// Waits until `svc` is ready to process a request.
415    ///
416    /// A [`crate::ReadyBinding`] reuses successful readiness until a subscribed
417    /// source changes. A raw service is checked on every invocation.
418    pub fn ready<'b, S, Req>(
419        &self,
420        svc: &'b S,
421    ) -> impl Future<Output = Result<(), S::Error>> + use<'a, 'b, Svc, St, S, Req>
422    where
423        S: Service<St, Req>,
424    {
425        self.ready_call(svc)
426    }
427
428    pub(crate) fn ready_generation<'b, S, Req>(
429        &self,
430        svc: &'b S,
431    ) -> impl Future<Output = Result<Generation, S::Error>> + use<'a, 'b, Svc, St, S, Req>
432    where
433        S: Service<St, Req>,
434    {
435        self.ready_call(svc)
436    }
437
438    fn ready_call<'b, S, Req, O>(
439        &self,
440        svc: &'b S,
441    ) -> impl Future<Output = Result<O, S::Error>> + use<'a, 'b, Svc, St, S, Req, O>
442    where
443        S: Service<St, Req>,
444        O: From<Generation>,
445    {
446        let ctx = *self;
447        ReadyCall {
448            check: RunCheck::new(self.scope, move || svc.ready(ctx.cast())),
449            waiters: self.waiters,
450            idx: self.idx,
451            lazy: self.idx == NO_SLOT,
452            in_call: self.in_call,
453            key: None,
454            active: false,
455            _t: marker::PhantomData,
456        }
457    }
458
459    #[inline]
460    /// Waits for `svc` to become ready, then calls it.
461    ///
462    /// Uses the nearest upstream scope carried by this context. A valid cache
463    /// allows immediate dispatch; otherwise, only `svc` is checked, without
464    /// marking the enclosing scope ready. A [`crate::ReadyBinding`] also
465    /// checks its own cache when called directly, independently of this scope.
466    /// Calls do not consume cached readiness.
467    ///
468    /// Calling after an explicit readiness check is cheap: a valid cache avoids
469    /// another readiness check or readiness allocation, while invalidation before
470    /// dispatch is still observed.
471    /// Raw [`Self::ready`] calls do not populate the upstream cache; use
472    /// [`crate::ready()`] for independent child caching.
473    ///
474    /// Readiness checks made while handling a call, including this one, do not
475    /// wait for another binding's pipeline-level readiness check, which may itself
476    /// be waiting for resources held by the call. They may run concurrently with it.
477    ///
478    /// ```
479    /// use ntex_service::{Ctx, Service};
480    ///
481    /// struct Forward<S> {
482    ///     inner: S,
483    /// }
484    ///
485    /// impl<S: Service<(), usize>> Service<(), usize> for Forward<S> {
486    ///     type Res = S::Res;
487    ///     type Error = S::Error;
488    ///
489    ///     ntex_service::forward!((), inner);
490    ///
491    ///     async fn call(&self, req: usize, ctx: Ctx<'_, Self>) -> Result<S::Res, S::Error> {
492    ///         ctx.call(&self.inner, req).await
493    ///     }
494    /// }
495    /// ```
496    pub fn call<'b, S, Req>(
497        &self,
498        svc: &'b S,
499        req: Req,
500    ) -> impl Future<Output = Result<S::Res, S::Error>> + use<'a, 'b, Svc, St, S, Req>
501    where
502        S: Service<St, Req>,
503    {
504        ReadyThenCall::new(
505            (svc, self.cast::<S>()),
506            req,
507            |&(svc, ctx): &(&'b S, Ctx<'a, S, St>)| {
508                (!ctx.scope.is_ready()).then(|| ctx.ready_cached(svc))
509            },
510            |(svc, ctx): (&'b S, Ctx<'a, S, St>), req| svc.call(req, ctx.into_call()),
511        )
512    }
513
514    #[allow(clippy::manual_async_fn)]
515    pub(crate) fn ready_cached<'b, S, Req>(
516        self,
517        svc: &'b S,
518    ) -> impl Future<Output = Result<(), S::Error>> + use<'a, 'b, Svc, St, S, Req>
519    where
520        S: Service<St, Req>,
521    {
522        // An `async fn` would store `self` and `svc` twice.
523        async move {
524            while !self.scope.is_ready() {
525                let result = {
526                    let observer = self.scope.observer();
527                    let mut ready = pin::pin!(self.ready_generation(svc));
528                    std::future::poll_fn(|cx| {
529                        observer.register(cx.waker());
530                        // A queued caller can use success published by another checker.
531                        if self.scope.is_ready() {
532                            Poll::Ready(Ok(None))
533                        } else {
534                            ready.as_mut().poll(cx).map(|result| result.map(Some))
535                        }
536                    })
537                    .await
538                };
539                let generation = result?;
540                // Dropping the check or its observer can invalidate its success.
541                if self.scope.is_ready()
542                    || generation.is_some_and(|generation| self.scope.is_current(generation))
543                {
544                    return Ok(());
545                }
546            }
547            Ok(())
548        }
549    }
550
551    #[inline]
552    /// Shuts down `svc`.
553    pub fn shutdown<'b, S, Req>(
554        &self,
555        svc: &'b S,
556    ) -> impl Future<Output = ()> + use<'a, 'b, Svc, St, S, Req>
557    where
558        S: Service<St, Req>,
559    {
560        svc.shutdown(self.cast())
561    }
562
563    #[inline]
564    /// Returns a context that uses `st` as its state.
565    pub fn map_state<NewSt>(&'a self, st: &'a NewSt) -> Ctx<'a, Self, NewSt> {
566        Ctx {
567            st,
568            idx: self.idx,
569            waiters: self.waiters,
570            scope: self.scope,
571            in_call: self.in_call,
572            _t: marker::PhantomData,
573        }
574    }
575}
576
577impl<S, St> Copy for Ctx<'_, S, St> {}
578
579impl<S, St> Clone for Ctx<'_, S, St> {
580    #[inline]
581    fn clone(&self) -> Self {
582        *self
583    }
584}
585
586impl<S, St> ops::Deref for Ctx<'_, S, St> {
587    type Target = St;
588
589    #[inline]
590    fn deref(&self) -> &St {
591        self.st
592    }
593}
594
595impl<S, St> fmt::Debug for Ctx<'_, S, St> {
596    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
597        f.debug_struct("Ctx")
598            .field("idx", &self.idx)
599            .field("waiters", &self.waiters.get().len())
600            .finish()
601    }
602}
603
604// Hand-written to keep nested service readiness futures shallow, see `RunCheck`.
605pin_project_lite::pin_project! {
606    struct ReadyCall<'a, F, Fut, O> {
607        #[pin]
608        check: RunCheck<'a, F, Fut>,
609        waiters: &'a WaitersRef,
610        // `NO_SLOT` until a check of a pipeline call inserts its own slot.
611        idx: u32,
612        // A check of a pipeline call, it removes its inserted slot on drop.
613        lazy: bool,
614        in_call: bool,
615        // Pending call-time check that bypassed the gate owner.
616        key: Option<u32>,
617        // A started check that has not completed.
618        active: bool,
619        _t: marker::PhantomData<O>,
620    }
621
622    impl<F, Fut, O> PinnedDrop for ReadyCall<'_, F, Fut, O> {
623        fn drop(this: Pin<&mut Self>) {
624            let this = this.project();
625            if this.key.is_some() {
626                this.waiters.remove_call(this.key);
627                this.waiters.wake_checks();
628            } else if *this.active && this.waiters.cur.get() == *this.idx {
629                this.waiters.notify();
630            }
631            if *this.lazy && *this.idx != NO_SLOT {
632                this.waiters.remove(*this.idx);
633            }
634        }
635    }
636}
637
638impl<F, Fut, E, O> Future for ReadyCall<'_, F, Fut, O>
639where
640    F: FnMut() -> Fut,
641    Fut: Future<Output = Result<(), E>>,
642    O: From<Generation>,
643{
644    type Output = Result<O, E>;
645
646    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
647        let mut this = self.project();
648        let mut restarted = false;
649        loop {
650            *this.active = true;
651            let mut check = this.check.as_mut();
652            let mut f = |cx: &mut Context<'_>| check.as_mut().poll(cx);
653            let result = if *this.idx == NO_SLOT && this.waiters.running.get() {
654                // Nested in the running check, which owns the gate; a call
655                // reaches it only from its own check.
656                f(cx)
657            } else if *this.in_call {
658                this.waiters.run_call(this.idx, this.key, cx, f)
659            } else {
660                this.waiters.run(this.waiters.slot(this.idx), cx, f)
661            };
662            let Poll::Ready(result) = result else {
663                return Poll::Pending;
664            };
665            *this.active = false;
666            match result {
667                // Scheduling another waiter can invalidate the completed check.
668                Ok(generation) if !this.check.scope().is_current(generation) => {}
669                result => return Poll::Ready(result.map(O::from)),
670            }
671            // Waking other checks can invalidate this one on every pass, see `RunCheck`.
672            if restarted {
673                cx.waker().wake_by_ref();
674                return Poll::Pending;
675            }
676            restarted = true;
677        }
678    }
679}
680
681#[cfg(test)]
682#[path = "../tests/unit/ctx.rs"]
683mod tests;