ntex_service/readiness.rs
1use std::cell::{Cell, OnceCell, Ref, RefCell};
2use std::future::{Future, poll_fn};
3use std::sync::Arc;
4use std::task::{Context, Poll, Wake, Waker};
5use std::{fmt, marker::PhantomData, mem, pin::Pin, rc::Rc, thread, thread::ThreadId};
6
7use crate::ctx::WaitersInner;
8
9const UNBOUND: &str = "ReadyBinding must be registered by Service::bind before use: \
10 the parent's `Service::bind` must call `ctx.bind(&self.inner)` for every child service \
11 (or use `forward!`); create lazy children with `Ctx::create`";
12
13const UNLINKED: &str = "ReadyBinding must be registered by Service::bind before use: \
14 it is bound to another parent; the calling service's `Service::bind` must also call \
15 `ctx.bind(&child)` (or use `forward!`)";
16
17const FOREIGN: &str = "ReadyBinding cannot be shared across pipelines: \
18 share a `Pipeline` instead and register it with `Pipeline::bind_to`";
19
20const UNLINKED_FOREIGN: &str = "ReadyBinding must be registered by Service::bind before use: \
21 it is bound to another pipeline; the calling service's `Service::bind` must call \
22 `ctx.bind(&child)`, and a service used by several pipelines must be shared as a \
23 `Pipeline` registered with `Pipeline::bind_to`";
24
25thread_local! {
26 static NOTIFICATION: RefCell<u64> = const { RefCell::new(0) };
27}
28
29/// A reusable callback invoked when a readiness scope receives a notification.
30///
31/// Register with [`crate::BindCtx::on_notify`] or [`crate::Pipeline::on_notify`].
32/// The callback runs synchronously when [`ReadyNotifier::notify`] reaches the
33/// registered scope, including notifications from dependencies and notifications
34/// received while already invalid. It does not run for successful checks,
35/// ordinary task wakeups, cached calls, or internal readiness resets.
36///
37/// The argument is the receiving scope's user data, configured with
38/// [`crate::ReadyBinding::with_data`], or `0` by default. Propagation delivers
39/// each scope's own value, not the originating scope's value. Pipeline roots
40/// always supply `0`. One callback can be shared by scopes with different data.
41///
42/// Clones share one callback identity. Registering the same handle repeatedly on
43/// a scope is idempotent. Repeated notifier subscriptions can invoke it more than
44/// once per notification. Each scope retains its registration until it is
45/// dropped, including across completed or cancelled checks.
46///
47/// Callbacks run after their scope is invalidated and its parents are visited,
48/// before its observers are woken. Later subscribers and unvisited ancestors
49/// may still be ready. Delivery borrows scope and callback storage in place,
50/// without snapshots or cloning callback handles. Registering callbacks on a
51/// scope currently executing callbacks, modifying borrowed scope storage, or
52/// notifying any source during delivery panics. Registrations on other scopes
53/// can take effect in the current notification.
54///
55/// Captures must be owned. Avoid capturing a pipeline that retains this callback
56/// or other strong references that would create a reference cycle.
57/// This type is neither `Send` nor `Sync`.
58#[derive(Clone)]
59pub struct ReadyCallback(Rc<dyn Fn(usize)>);
60
61impl ReadyCallback {
62 /// Creates an independent callback identity.
63 pub fn new(callback: impl Fn(usize) + 'static) -> Self {
64 Self(Rc::new(callback))
65 }
66}
67
68impl fmt::Debug for ReadyCallback {
69 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70 f.debug_struct("ReadyCallback").finish_non_exhaustive()
71 }
72}
73
74/// A source of readiness-change notifications.
75///
76/// A notification invalidates the cached readiness of subscribed scopes and
77/// their dependent ancestors as it visits them, delivering each scope's callbacks
78/// and observer wakes before continuing to later subscribers. It requests another
79/// readiness check; it does not grant readiness or run or drop readiness futures.
80///
81/// Clones share the same notification source. [`Default`] and [`new`](Self::new)
82/// each create an independent source. Subscriptions belong to readiness scopes
83/// and persist until the scope or source is dropped, even after a readiness
84/// check completes or is cancelled. Repeated subscriptions are not deduplicated
85/// and cause repeated invalidations and callback delivery. Entries for dropped
86/// scopes are ignored and pruned when later subscriptions double the number of
87/// entries, or when a notification finds more than half of them dropped. Until
88/// pruned, these entries retain waiter-store allocations, but not retired scope
89/// resources.
90///
91/// Notify after any change that can affect readiness, including consuming the
92/// last available slot and releasing capacity. The change and notification must
93/// happen before another caller can use cached readiness.
94///
95/// This type is neither `Send` nor `Sync`.
96/// Register sources with [`crate::BindCtx::subscribe`] in [`crate::Service::bind`].
97#[derive(Clone, Debug, Default)]
98pub struct ReadyNotifier(Rc<Endpoints>);
99
100impl ReadyNotifier {
101 /// Creates an independent notification source.
102 pub fn new() -> Self {
103 Self::default()
104 }
105
106 /// Visits subscribed scopes in registration order, invalidating each scope,
107 /// recursively visiting its parents, then invoking its [`ReadyCallback`]s
108 /// and waking its observers. Directly subscribed ancestors are deferred to
109 /// their own subscription entries.
110 ///
111 /// Every notification advances the affected scopes' generations, including
112 /// scopes that are already invalid or have a pending readiness check.
113 /// Shared ancestors are visited once; duplicate direct subscriptions still
114 /// invalidate and deliver callbacks repeatedly. Traversal uses stack space
115 /// proportional to dependency depth, without allocating traversal buffers.
116 ///
117 /// A callback panic propagates, waking already-invalidated scopes during
118 /// unwinding; unvisited scopes remain untouched. Wakers must not panic:
119 /// a panicking waker skips its remaining siblings and can abort if another
120 /// waker panics during unwinding.
121 ///
122 /// # Panics
123 ///
124 /// Panics if any readiness notification or internal readiness reset is
125 /// already being delivered on this thread. Subscribing to this source or
126 /// mutating borrowed scope or callback storage during delivery also panics.
127 pub fn notify(&self) {
128 let mut prune = false;
129 with_notification(|epoch| {
130 let scopes = self.0.borrow();
131 let mut dead = 0;
132 // Direct subscribers must not also be delivered as ancestors.
133 for endpoint in &*scopes {
134 let live = endpoint
135 .store
136 .scopes
137 .with(endpoint.scope, |s| s.direct_epoch.set(epoch));
138 dead += usize::from(live.is_none());
139 }
140 prune = dead * 2 > scopes.len();
141 for endpoint in &*scopes {
142 notify_scope(&endpoint.store, endpoint.scope, epoch, true, true);
143 }
144 });
145 if prune {
146 // Dropped after delivery and all borrows end; may release waiter stores.
147 drop(self.0.prune());
148 }
149 }
150}
151
152/// Runs one notification or reset with a fresh thread-local traversal epoch.
153///
154/// Holds the epoch's mutable borrow until delivery finishes, including unwinding.
155///
156/// # Panics
157///
158/// Panics on nested delivery on this thread or when the epoch counter overflows.
159fn with_notification(f: impl FnOnce(u64)) {
160 NOTIFICATION.with_borrow_mut(|epoch| {
161 *epoch = epoch
162 .checked_add(1)
163 .expect("readiness notification epoch exhausted");
164 f(*epoch);
165 });
166}
167
168/// Invalidates a live scope, visits its parents, then delivers callbacks and wakes.
169///
170/// Missing IDs are ignored. Indirect visits skip scopes already visited or marked
171/// for direct delivery in this epoch; duplicate direct visits remain effective.
172/// Setting `callbacks` to false suppresses callbacks throughout the traversal.
173///
174/// Scope and parent storage remain borrowed during recursion and delivery.
175/// Already-invalidated scopes wake their observers even if a callback panics;
176/// unvisited scopes remain untouched.
177fn notify_scope(store: &WaitersInner, id: usize, epoch: u64, direct: bool, callbacks: bool) {
178 store.scopes.with(id, |s| {
179 if !direct && (s.notify_epoch.get() == epoch || s.direct_epoch.get() == epoch) {
180 return;
181 }
182 s.notify_epoch.set(epoch);
183 s.invalidate(direct);
184 if id == 0 {
185 store.scopes.root_ready.set(false);
186 }
187 let _wake = NotifyObservers(&s.observers);
188 for &parent in s.parents.borrow().iter() {
189 notify_scope(store, parent, epoch, false, callbacks);
190 }
191 for parent in s.external_parents.borrow().iter() {
192 notify_scope(&parent.store, parent.scope, epoch, false, callbacks);
193 }
194 if callbacks {
195 for callback in s.callbacks.borrow().iter() {
196 (callback.0)(s.data.get());
197 }
198 }
199 });
200}
201
202struct NotifyObservers<'a>(&'a ReadyObservers);
203
204impl Drop for NotifyObservers<'_> {
205 /// Takes and wakes observer slots in place, skipping the scope's own checker.
206 ///
207 /// Uses the initial slab capacity as a bound rather than snapshotting wakers.
208 /// Releases each slot borrow before waking; a waker panic stops this pass.
209 fn drop(&mut self) {
210 // The local checker only forwards to these same slots.
211 let skip = self.0.checker.get().map(|c| Arc::as_ptr(c).cast());
212 let capacity = self.0.slots.borrow().capacity();
213 for idx in 0..capacity {
214 let waker = self
215 .0
216 .slots
217 .borrow_mut()
218 .get_mut(idx)
219 .and_then(Option::take);
220 if let Some(waker) = waker
221 && Some(waker.data()) != skip
222 {
223 waker.wake();
224 }
225 }
226 }
227}
228
229/// Wakers taken from observers, woken in order on drop.
230///
231/// Does not allocate for up to eight wakers.
232#[derive(Default)]
233struct Wakers {
234 inline: [Option<Waker>; 8],
235 rest: Vec<Waker>,
236}
237
238impl Wakers {
239 /// Queues a waker for delivery on drop, using inline storage for the first eight.
240 fn push(&mut self, waker: Waker) {
241 if let Some(slot) = self.inline.iter_mut().find(|slot| slot.is_none()) {
242 *slot = Some(waker);
243 } else {
244 self.rest.push(waker);
245 }
246 }
247}
248
249impl Drop for Wakers {
250 /// Wakes queued tasks in insertion order; a panic skips remaining delivery.
251 fn drop(&mut self) {
252 for slot in &mut self.inline {
253 if let Some(waker) = slot.take() {
254 waker.wake();
255 }
256 }
257 for waker in self.rest.drain(..) {
258 waker.wake();
259 }
260 }
261}
262
263/// Appends a dependency edge if absent, returning whether it was inserted.
264///
265/// Panics if the edge list is already borrowed.
266fn link<T: PartialEq>(links: &RefCell<Vec<T>>, item: T) -> bool {
267 let mut links = links.borrow_mut();
268 let new = !links.contains(&item);
269 if new {
270 links.push(item);
271 }
272 new
273}
274
275/// An explicit subscription endpoint for another pipeline's readiness.
276///
277/// Obtain a link with [`crate::Pipeline::readiness_link`] and register it with
278/// [`crate::BindCtx::subscribe_pipeline`]. Invalidation of the source pipeline
279/// invalidates the subscribing scope and its ancestors, including internal
280/// resets. A link does not check readiness or retain the source pipeline.
281/// The enclosing service must still await the source pipeline's readiness.
282///
283/// Registrations belong to the subscribing scope, not this handle. Dropping a
284/// temporary link does not unsubscribe it. Links become inert when their source
285/// pipeline is dropped. Links and registrations retain the waiter-store
286/// allocation, but not retired scope resources. Registrations of dropped scopes
287/// are pruned when later registrations on the same source double their number.
288/// This type is neither `Send` nor `Sync`.
289#[derive(Clone)]
290pub struct ReadyLink {
291 store: Rc<WaitersInner>,
292}
293
294impl fmt::Debug for ReadyLink {
295 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
296 f.debug_struct("ReadyLink")
297 .field("store", &Rc::as_ptr(&self.store))
298 .finish()
299 }
300}
301
302#[derive(Clone)]
303struct Endpoint {
304 store: Rc<WaitersInner>,
305 scope: usize,
306}
307
308impl PartialEq for Endpoint {
309 /// Compares scope IDs within the same waiter-store allocation.
310 fn eq(&self, other: &Self) -> bool {
311 self.scope == other.scope && Rc::ptr_eq(&self.store, &other.store)
312 }
313}
314
315impl Endpoint {
316 /// Returns false once the scope is retired; IDs are never reused.
317 ///
318 /// Treats a mutably borrowed scope table as live.
319 fn is_live(&self) -> bool {
320 self.store.scopes.slots.try_borrow().map_or(true, |slots| {
321 slots.get(self.scope).is_some_and(Option::is_some)
322 })
323 }
324}
325
326impl fmt::Debug for Endpoint {
327 /// Formats the store address and scope ID without accessing scope storage.
328 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
329 f.debug_struct("Endpoint")
330 .field("store", &Rc::as_ptr(&self.store))
331 .field("scope", &self.scope)
332 .finish()
333 }
334}
335
336/// Minimum number of entries before subscription pruning is considered.
337const PRUNE_MIN: usize = 32;
338
339/// Registered endpoints, pruned of retired scopes as the list grows.
340///
341/// Subscription prunes once the list reaches twice its size after the previous
342/// prune, keeping amortized cost constant. Pruning preserves order and
343/// duplicates of live entries. Removed endpoints are returned so callers can
344/// drop them after releasing borrows, since a final store release can drop
345/// wakers and other reentrant resources.
346#[derive(Debug, Default)]
347struct Endpoints {
348 list: RefCell<Vec<Endpoint>>,
349 prune_at: Cell<usize>,
350}
351
352impl Endpoints {
353 /// Borrows the registered endpoints in registration order.
354 fn borrow(&self) -> Ref<'_, Vec<Endpoint>> {
355 self.list.borrow()
356 }
357
358 /// Appends an endpoint, skipping an existing equal entry if `dedup` is set.
359 ///
360 /// Panics if the list is already borrowed.
361 #[must_use]
362 fn push(&self, endpoint: Endpoint, dedup: bool) -> Vec<Endpoint> {
363 let mut list = self.list.borrow_mut();
364 let dead = if list.len() >= self.prune_at.get().max(PRUNE_MIN) {
365 self.extract_dead(&mut list)
366 } else {
367 Vec::new()
368 };
369 if !dedup || !list.contains(&endpoint) {
370 list.push(endpoint);
371 }
372 dead
373 }
374
375 /// Removes retired entries, doing nothing while the list is borrowed.
376 #[must_use]
377 fn prune(&self) -> Vec<Endpoint> {
378 self.list
379 .try_borrow_mut()
380 .map(|mut list| self.extract_dead(&mut list))
381 .unwrap_or_default()
382 }
383
384 fn extract_dead(&self, list: &mut Vec<Endpoint>) -> Vec<Endpoint> {
385 let dead = list.extract_if(.., |e| !e.is_live()).collect();
386 self.prune_at.set(list.len() * 2);
387 dead
388 }
389}
390
391/// The append-only scope table owned by a pipeline's waiter store.
392#[derive(Debug)]
393pub(crate) struct ScopeStore {
394 slots: RefCell<Vec<Option<ScopeInner>>>,
395 // Mirrors the root scope's `ready` flag so the per-call check skips the
396 // table borrow; false once the root is retired.
397 root_ready: Cell<bool>,
398}
399
400impl Default for ScopeStore {
401 /// Creates root ID `0` with one owner reserved for the initial root handle.
402 fn default() -> Self {
403 Self {
404 slots: RefCell::new(vec![Some(ScopeInner::default())]),
405 root_ready: Cell::new(false),
406 }
407 }
408}
409
410impl ScopeStore {
411 /// Appends an unready scope with one owner and returns its never-reused ID.
412 ///
413 /// # Panics
414 ///
415 /// Panics if the store is retired or its scope table is already borrowed.
416 fn allocate(&self) -> usize {
417 let mut slots = self.slots.borrow_mut();
418 assert!(!slots.is_empty(), "readiness store has been retired");
419 let id = slots.len();
420 slots.push(Some(ScopeInner::default()));
421 id
422 }
423
424 /// Runs `f` with a live scope, returning `None` for missing or retired IDs.
425 ///
426 /// Keeps the table immutably borrowed throughout `f`; allocating or retiring
427 /// scopes during the closure panics.
428 fn with<R>(&self, id: usize, f: impl FnOnce(&ScopeInner) -> R) -> Option<R> {
429 self.slots.borrow().get(id).and_then(Option::as_ref).map(f)
430 }
431
432 /// Releases one logical scope owner, ignoring already-retired IDs.
433 ///
434 /// The last child owner removes its slot. The last root owner retires the
435 /// entire table, closing all checkers before dropping scope resources.
436 /// Retained endpoints keep only the waiter-store allocation alive.
437 ///
438 /// # Panics
439 ///
440 /// Panics if retirement requires mutating a borrowed scope table.
441 fn release(&self, id: usize) {
442 if self.with(id, |s| {
443 s.owners.set(s.owners.get() - 1);
444 s.owners.get() == 0
445 }) != Some(true)
446 {
447 return;
448 }
449 if id == 0 {
450 self.root_ready.set(false);
451 let slots = self.slots.take();
452 // Close every checker before dropping reentrant callback captures or wakers.
453 for scope in slots.iter().flatten() {
454 scope.observers.close();
455 }
456 } else {
457 let scope = self.slots.borrow_mut()[id].take().unwrap();
458 scope.observers.close();
459 }
460 }
461}
462
463/// A snapshot for one scope's readiness check, not a transferable readiness permit.
464#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
465pub struct Generation {
466 value: u64,
467 direct: u64,
468}
469
470impl From<Generation> for () {
471 /// Discards the snapshot when a caller only needs readiness completion.
472 fn from(_: Generation) {}
473}
474
475/// A lazily bound local scope handle; all scope data lives in its waiter store.
476#[derive(Clone, Debug, Default)]
477pub(crate) struct ReadyScope(OnceCell<ScopeRef>);
478
479#[derive(Debug)]
480struct ScopeRef {
481 store: Rc<WaitersInner>,
482 id: usize,
483}
484
485impl Clone for ScopeRef {
486 /// Acquires another logical owner of this live scope and clones its store.
487 ///
488 /// Panics if the scope has been retired.
489 fn clone(&self) -> Self {
490 self.store
491 .scopes
492 .with(self.id, |s| s.owners.set(s.owners.get() + 1))
493 .expect("readiness scope has been retired");
494 Self {
495 store: self.store.clone(),
496 id: self.id,
497 }
498 }
499}
500
501impl Drop for ScopeRef {
502 /// Releases logical ownership, retiring the scope on its last owner.
503 fn drop(&mut self) {
504 self.store.scopes.release(self.id);
505 }
506}
507
508impl ReadyScope {
509 /// Creates an unbound handle without allocating a scope or waiter store.
510 pub(crate) fn new() -> Self {
511 Self::default()
512 }
513
514 /// Adopts the initial owner of the store's preallocated root ID `0`.
515 ///
516 /// Does not increment the owner count; use cloning for additional handles.
517 pub(crate) fn root(store: Rc<WaitersInner>) -> Self {
518 Self(OnceCell::from(ScopeRef { store, id: 0 }))
519 }
520
521 /// Returns the assigned store and ID without checking whether the scope is live.
522 ///
523 /// Panics if service binding has not assigned this handle to a store.
524 fn bound(&self) -> &ScopeRef {
525 self.0.get().expect(UNBOUND)
526 }
527
528 /// Accesses this scope while holding an immutable borrow of its store's table.
529 ///
530 /// Panics if the handle is unbound or the scope is retired. The closure must
531 /// not allocate or retire scopes in the borrowed table.
532 fn with<R>(&self, f: impl FnOnce(&ScopeInner) -> R) -> R {
533 let scope = self.bound();
534 scope
535 .store
536 .scopes
537 .with(scope.id, f)
538 .expect("readiness scope has been retired")
539 }
540
541 /// Returns an endpoint retaining the store allocation, not a logical scope owner.
542 ///
543 /// Panics if this handle is unbound; retired scopes can still produce endpoints.
544 fn endpoint(&self) -> Endpoint {
545 let scope = self.bound();
546 Endpoint {
547 store: scope.store.clone(),
548 scope: scope.id,
549 }
550 }
551
552 /// Returns an explicit subscription link for this pipeline root.
553 ///
554 /// Panics if the handle is unbound or its scope ID is not `0`.
555 pub(crate) fn readiness_link(&self) -> ReadyLink {
556 assert_eq!(self.bound().id, 0);
557 ReadyLink {
558 store: self.bound().store.clone(),
559 }
560 }
561
562 /// Makes invalidation of the linked source root propagate to this scope.
563 ///
564 /// Deduplicates dependency edges, ignores root self-links, and does nothing
565 /// for retired sources. Same-store edges use local IDs; foreign edges retain
566 /// a destination endpoint without acquiring a logical scope owner.
567 ///
568 /// Panics if the source is live but this handle is unbound, or if registration
569 /// conflicts with a borrow of the source's parent list.
570 pub(crate) fn subscribe_pipeline(&self, source_link: &ReadyLink) {
571 // Pruned endpoints are dropped after the source table borrow ends.
572 let _dead = source_link.store.scopes.with(0, |source| {
573 let scope = self.bound();
574 if Rc::ptr_eq(&scope.store, &source_link.store) {
575 if scope.id != 0 {
576 link(&source.parents, scope.id);
577 }
578 Vec::new()
579 } else {
580 source.external_parents.push(self.endpoint(), true)
581 }
582 });
583 }
584
585 /// Returns the live scope's validation and direct-invalidation snapshot.
586 pub(crate) fn generation(&self) -> Generation {
587 self.with(|s| s.generation.get())
588 }
589
590 /// Returns whether no invalidation has occurred since the supplied snapshot.
591 pub(crate) fn is_current(&self, generation: Generation) -> bool {
592 self.generation() == generation
593 }
594
595 /// Returns whether direct invalidation has occurred since the snapshot.
596 ///
597 /// Invalidation propagated from a child changes the validation generation,
598 /// but only direct invalidation requires restarting an outstanding check.
599 pub(crate) fn is_directly_invalidated(&self, generation: Generation) -> bool {
600 self.generation().direct != generation.direct
601 }
602
603 /// Returns cached readiness, or false for an unbound or retired scope.
604 pub(crate) fn is_ready(&self) -> bool {
605 self.0.get().is_some_and(|scope| {
606 let scopes = &scope.store.scopes;
607 if scope.id == 0 {
608 let ready = scopes.root_ready.get();
609 debug_assert_eq!(ready, scopes.with(0, |s| s.ready.get()).unwrap_or(false));
610 ready
611 } else {
612 scopes.with(scope.id, |s| s.ready.get()).unwrap_or(false)
613 }
614 })
615 }
616
617 /// Directly invalidates this scope and visits its parents without callbacks.
618 ///
619 /// Wakes affected observers without running or dropping readiness futures.
620 /// Despite the name, this also supports nested scopes during service creation.
621 ///
622 /// Panics if this handle is unbound or another notification or reset is being
623 /// delivered on this thread. Retired scopes are ignored.
624 pub(crate) fn reset_root(&self) {
625 let scope = self.bound();
626 with_notification(|epoch| {
627 scope
628 .store
629 .scopes
630 .with(scope.id, |s| s.direct_epoch.set(epoch));
631 notify_scope(&scope.store, scope.id, epoch, true, false);
632 });
633 }
634
635 /// Records a successful check only if no dependency changed while checking.
636 ///
637 /// Returns false for a stale snapshot. Does not validate parents, invoke
638 /// callbacks, or wake observers.
639 pub(crate) fn set_ready(&self, generation: Generation) -> bool {
640 if self.is_current(generation) {
641 self.with(|s| s.ready.set(true));
642 let scope = self.bound();
643 if scope.id == 0 {
644 scope.store.scopes.root_ready.set(true);
645 }
646 true
647 } else {
648 false
649 }
650 }
651
652 /// Appends a persistent notifier subscription during service initialization.
653 ///
654 /// Does not deduplicate: repeated subscriptions cause repeated direct delivery.
655 /// Prunes retired entries as the list grows.
656 /// Panics if this handle is unbound or the source is delivering a notification.
657 pub(crate) fn subscribe(&self, source: &ReadyNotifier) {
658 let _dead = source.0.push(self.endpoint(), false);
659 }
660
661 /// Sets the callback payload before forwarding service binding.
662 ///
663 /// Does not invalidate readiness. Panics if the scope is unbound or retired.
664 pub(crate) fn set_data(&self, data: usize) {
665 self.with(|s| s.data.set(data));
666 }
667
668 /// Retains a callback until scope retirement, deduplicating its shared identity.
669 ///
670 /// Panics if the scope is unbound, retired, or currently delivering callbacks.
671 pub(crate) fn on_notify(&self, callback: &ReadyCallback) {
672 self.with(|s| {
673 let mut callbacks = s.callbacks.borrow_mut();
674 if !callbacks.iter().any(|c| Rc::ptr_eq(&c.0, &callback.0)) {
675 callbacks.push(callback.clone());
676 }
677 });
678 }
679
680 /// Binds an unbound child to this store and records this scope as its parent.
681 ///
682 /// Invalidation propagates from child to parent. Repeated edges and
683 /// self-dependencies are ignored; stale parent IDs need no cleanup.
684 ///
685 /// # Panics
686 ///
687 /// Panics if this handle is unbound, the child belongs to another store, or
688 /// allocation or registration conflicts with borrowed scope or parent storage.
689 pub(crate) fn depend_on(&self, child: &Self) {
690 let parent = self.bound();
691 let child = child.0.get_or_init(|| {
692 let id = parent.store.scopes.allocate();
693 ScopeRef {
694 store: parent.store.clone(),
695 id,
696 }
697 });
698 assert!(Rc::ptr_eq(&parent.store, &child.store), "{FOREIGN}");
699 if parent.id != child.id {
700 parent
701 .store
702 .scopes
703 .with(child.id, |s| link(&s.parents, parent.id));
704 }
705 }
706
707 /// Verifies that the child is this scope or records this scope as a local parent.
708 ///
709 /// Panics for unbound handles, foreign stores, or missing dependency edges.
710 pub(crate) fn assert_dependency(&self, child: &Self) {
711 let child = child.0.get().expect(UNBOUND);
712 let parent = self.bound();
713 assert!(
714 Rc::ptr_eq(&parent.store, &child.store),
715 "{UNLINKED_FOREIGN}"
716 );
717 assert!(
718 parent.id == child.id
719 || parent
720 .store
721 .scopes
722 .with(child.id, |s| s.parents.borrow().contains(&parent.id))
723 == Some(true),
724 "{UNLINKED}"
725 );
726 }
727
728 /// Allocates an empty observer slot for one independently waiting task.
729 ///
730 /// The returned handle removes its slot on drop without retaining the scope.
731 /// A waker is installed separately with [`ReadyObserver::register`].
732 pub(crate) fn observer(&self) -> ReadyObserver {
733 ReadyObserver {
734 store: self.bound().store.clone(),
735 scope: self.bound().id,
736 idx: self.with(|s| s.observers.slots.borrow_mut().insert(None)),
737 }
738 }
739
740 /// Returns the scope's shared, lazily allocated observer-forwarding waker.
741 ///
742 /// Waking it schedules observers without invalidating readiness and must
743 /// happen on the owning thread, even after the scope has been retired.
744 pub(crate) fn checker_waker(&self) -> Waker {
745 let endpoint = self.endpoint();
746 self.with(|s| s.observers.checker_waker(endpoint))
747 }
748
749 /// Drives or joins a shared check without allocating on a cached success.
750 ///
751 /// Only the current owner runs `check`; other callers wait for its result or
752 /// cancellation. Successful checks cache readiness only for a current
753 /// generation, while errors return to the owner without being cached.
754 /// Completion or cancellation releases ownership and wakes waiting callers,
755 /// which recheck the cache before claiming ownership themselves.
756 //
757 // A plain fn returning `async move` stores `check` once; an `async fn`
758 // would keep a second copy.
759 #[allow(clippy::manual_async_fn)]
760 pub(crate) fn check<F, Fut, E>(&self, mut check: F) -> impl Future<Output = Result<(), E>>
761 where
762 F: FnMut() -> Fut,
763 Fut: Future<Output = Result<(), E>>,
764 {
765 async move {
766 // Reused across retries. Cancellation drops the check, then ownership,
767 // then the observer.
768 let mut observer = None;
769 loop {
770 if self.is_ready() {
771 return Ok(());
772 }
773
774 let observer = observer.get_or_insert_with(|| self.observer());
775 let owner = poll_fn(|cx| {
776 observer.register(cx.waker());
777 if self.is_ready() {
778 Poll::Ready(None)
779 } else if self.with(|s| s.checking.replace(true)) {
780 Poll::Pending
781 } else {
782 Poll::Ready(Some(CheckOwner(self)))
783 }
784 })
785 .await;
786
787 if let Some(owner) = owner {
788 let result = RunCheck::new(self, &mut check).await.map(|generation| {
789 self.set_ready(generation);
790 });
791 drop(owner);
792 result?;
793 }
794 // Cleanup and handoff can reenter and invalidate the success.
795 }
796 }
797 }
798
799 /// Schedules observers without changing cached readiness or generations.
800 ///
801 /// Takes their wakers into a buffer and wakes them after releasing scope and
802 /// observer-storage borrows. Observer slots remain available for registration.
803 pub(crate) fn wake_observers(&self) {
804 let mut wakers = Wakers::default();
805 self.with(|s| s.observers.take_wakers(&mut wakers, None));
806 }
807}
808
809#[derive(Debug)]
810struct ScopeInner {
811 owners: Cell<usize>,
812 data: Cell<usize>,
813 generation: Cell<Generation>,
814 ready: Cell<bool>,
815 checking: Cell<bool>,
816 notify_epoch: Cell<u64>,
817 direct_epoch: Cell<u64>,
818 callbacks: RefCell<Vec<ReadyCallback>>,
819 parents: RefCell<Vec<usize>>,
820 external_parents: Endpoints,
821 observers: ReadyObservers,
822}
823
824impl Default for ScopeInner {
825 /// Creates an unready scope with one owner and no registrations or dependencies.
826 fn default() -> Self {
827 Self {
828 owners: Cell::new(1),
829 data: Cell::new(0),
830 generation: Cell::default(),
831 ready: Cell::default(),
832 checking: Cell::default(),
833 notify_epoch: Cell::default(),
834 direct_epoch: Cell::default(),
835 callbacks: RefCell::default(),
836 parents: RefCell::default(),
837 external_parents: Endpoints::default(),
838 observers: ReadyObservers::default(),
839 }
840 }
841}
842
843impl ScopeInner {
844 /// Advances the validation generation and clears cached readiness.
845 ///
846 /// Direct invalidation also advances the restart marker for pending checks.
847 /// Does not traverse dependencies or deliver callbacks or wakes.
848 ///
849 /// Panics when the generation counter overflows.
850 fn invalidate(&self, direct: bool) {
851 let mut generation = self.generation.get();
852 generation.value = generation
853 .value
854 .checked_add(1)
855 .expect("readiness generation exhausted");
856 if direct {
857 generation.direct = generation.value;
858 }
859 self.generation.set(generation);
860 self.ready.set(false);
861 }
862}
863
864#[derive(Debug, Default)]
865struct ReadyObservers {
866 slots: RefCell<slab::Slab<Option<Waker>>>,
867 checker: OnceCell<Arc<CheckerWake>>,
868 _local: PhantomData<Rc<()>>,
869}
870
871impl ReadyObservers {
872 /// Returns the cached checker waker, creating it for this scope's endpoint.
873 ///
874 /// The endpoint must identify the scope owning these observers. Its waker
875 /// forwards wakes only on the thread that first creates it.
876 fn checker_waker(&self, endpoint: Endpoint) -> Waker {
877 let checker = self.checker.get_or_init(|| {
878 Arc::new(CheckerWake {
879 owner: thread::current().id(),
880 endpoint: mem::ManuallyDrop::new(endpoint),
881 closed: Cell::new(false),
882 })
883 });
884 Waker::from(checker.clone())
885 }
886
887 /// Disables any cached checker without waking tasks or removing observer slots.
888 ///
889 /// Repeated calls are harmless; retained closed wakers still enforce ownership.
890 fn close(&self) {
891 if let Some(checker) = self.checker.get() {
892 checker.closed.set(true);
893 }
894 }
895
896 /// Moves registered wakers into the delivery buffer without removing slots.
897 ///
898 /// Wakers matching `skip` data remain registered. Drop the buffer only after
899 /// releasing scope and observer borrows, since delivery may reenter.
900 fn take_wakers(&self, wakers: &mut Wakers, skip: Option<*const ()>) {
901 // Waker clone/drop/wake may reenter; keep them outside the borrow.
902 for (_, waker) in self.slots.borrow_mut().iter_mut() {
903 if let Some(waker) = waker.take_if(|waker| Some(waker.data()) != skip) {
904 wakers.push(waker);
905 }
906 }
907 }
908}
909
910impl Drop for ReadyObservers {
911 /// Closes the cached checker before destroying the observer storage.
912 fn drop(&mut self) {
913 self.close();
914 }
915}
916
917struct CheckerWake {
918 owner: ThreadId,
919 closed: Cell<bool>,
920 endpoint: mem::ManuallyDrop<Endpoint>,
921}
922
923// SAFETY: Arc reference counts are atomic. The Rc endpoint is accessed and
924// destroyed only on its owning thread; rejected destruction leaves it intact.
925unsafe impl Send for CheckerWake {}
926// SAFETY: The Cell and Rc endpoint are accessed only on the owning thread.
927// Foreign-thread access, including Debug, only reads the immutable owner ID.
928unsafe impl Sync for CheckerWake {}
929
930impl CheckerWake {
931 /// Checks thread ownership without accessing the thread-local endpoint.
932 fn is_owner(&self) -> bool {
933 thread::current().id() == self.owner
934 }
935}
936
937impl fmt::Debug for CheckerWake {
938 /// Formats only thread-safe metadata without inspecting the local endpoint.
939 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
940 f.debug_struct("CheckerWake")
941 .field("owner", &self.owner)
942 .finish_non_exhaustive()
943 }
944}
945
946impl Drop for CheckerWake {
947 /// Drops the endpoint only on its owning thread.
948 ///
949 /// Foreign-thread destruction leaks the endpoint and panics unless already
950 /// unwinding, avoiding non-atomic reference-count access and a second panic.
951 fn drop(&mut self) {
952 if self.is_owner() {
953 // SAFETY: The owner thread is the only thread that touches this Rc.
954 unsafe { mem::ManuallyDrop::drop(&mut self.endpoint) };
955 } else if !thread::panicking() {
956 // Never drop the Rc on this thread, even while unwinding.
957 panic!("ntex-service readiness observers can only be accessed on their owning thread");
958 }
959 }
960}
961
962impl Wake for CheckerWake {
963 /// Consumes this handle and forwards to owner-thread observer delivery.
964 fn wake(self: Arc<Self>) {
965 self.wake_by_ref();
966 }
967
968 /// Wakes observers without invalidating readiness or waking this checker again.
969 ///
970 /// Closed checkers and retired scopes are ignored after checking ownership.
971 ///
972 /// # Panics
973 ///
974 /// Panics on a foreign thread, even if the checker has already been closed.
975 fn wake_by_ref(self: &Arc<Self>) {
976 assert!(
977 self.is_owner(),
978 "ntex-service readiness observers can only be accessed on their owning thread"
979 );
980 if self.closed.get() {
981 return;
982 }
983 // Checks polled by this waker register it too. Waking it would only
984 // repeat this pass, so it stays registered for later notifications.
985 let this = Arc::as_ptr(self).cast::<()>();
986 let mut wakers = Wakers::default();
987 self.endpoint.store.scopes.with(self.endpoint.scope, |s| {
988 s.observers.take_wakers(&mut wakers, Some(this));
989 });
990 }
991}
992
993struct CheckOwner<'a>(&'a ReadyScope);
994
995impl Drop for CheckOwner<'_> {
996 /// Releases shared-check ownership and wakes observers to retry or use the cache.
997 fn drop(&mut self) {
998 self.0.with(|s| s.checking.set(false));
999 self.0.wake_observers();
1000 }
1001}
1002
1003/// One task's registration, independent of the scope's persistent subscriptions.
1004#[derive(Debug)]
1005pub(crate) struct ReadyObserver {
1006 store: Rc<WaitersInner>,
1007 scope: usize,
1008 idx: usize,
1009}
1010
1011impl ReadyObserver {
1012 /// Clears this task's waker without removing its reusable observer slot.
1013 ///
1014 /// Retired scopes are ignored; the removed waker is dropped outside all borrows.
1015 pub(crate) fn clear(&self) {
1016 let waker = self.store.scopes.with(self.scope, |s| {
1017 s.observers.slots.borrow_mut()[self.idx].take()
1018 });
1019 drop(waker);
1020 }
1021
1022 /// Registers this task's waker before checking readiness to avoid missed wakes.
1023 ///
1024 /// Reuses an equivalent waker; otherwise clones and drops wakers outside
1025 /// storage borrows. Returns false if the scope retires before registration.
1026 pub(crate) fn register(&self, waker: &Waker) -> bool {
1027 let Some(registered) = self.store.scopes.with(self.scope, |s| {
1028 s.observers.slots.borrow()[self.idx]
1029 .as_ref()
1030 .is_some_and(|prev| prev.will_wake(waker))
1031 }) else {
1032 return false;
1033 };
1034 if registered {
1035 return true;
1036 }
1037
1038 // Waker clone/drop implementations can reenter, just like wake.
1039 let mut waker = Some(waker.clone());
1040 let previous = self.store.scopes.with(self.scope, |s| {
1041 std::mem::replace(&mut s.observers.slots.borrow_mut()[self.idx], waker.take())
1042 });
1043 let registered = previous.is_some();
1044 drop(previous);
1045 registered
1046 }
1047}
1048
1049impl Drop for ReadyObserver {
1050 /// Removes the task's slot if still live, dropping its waker outside all borrows.
1051 fn drop(&mut self) {
1052 let waker = self.store.scopes.with(self.scope, |s| {
1053 s.observers.slots.borrow_mut().remove(self.idx)
1054 });
1055 drop(waker);
1056 }
1057}
1058
1059pin_project_lite::pin_project! {
1060 /// Runs a check until it completes without being invalidated.
1061 ///
1062 /// Hand-written instead of an `async fn` to keep nested service readiness
1063 /// futures shallow, deep `async` nesting overflows the compiler's query depth.
1064 pub(crate) struct RunCheck<'a, F, Fut> {
1065 scope: &'a ReadyScope,
1066 check: F,
1067 // Dropped before `observer`.
1068 #[pin]
1069 fut: Option<Fut>,
1070 observer: Option<ReadyObserver>,
1071 generation: Generation,
1072 }
1073}
1074
1075impl<'a, F, Fut, E> RunCheck<'a, F, Fut>
1076where
1077 F: FnMut() -> Fut,
1078 Fut: Future<Output = Result<(), E>>,
1079{
1080 /// Creates an idle runner without invoking the check factory until polled.
1081 ///
1082 /// Does not acquire shared-check ownership or populate the readiness cache;
1083 /// callers handle those steps when caching a successful generation.
1084 pub(crate) fn new(scope: &'a ReadyScope, check: F) -> Self {
1085 Self {
1086 scope,
1087 check,
1088 fut: None,
1089 observer: None,
1090 generation: Generation::default(),
1091 }
1092 }
1093
1094 /// Returns the scope whose invalidations govern this runner's checks.
1095 pub(crate) fn scope(&self) -> &'a ReadyScope {
1096 self.scope
1097 }
1098}
1099
1100impl<F, Fut, E> Future for RunCheck<'_, F, Fut>
1101where
1102 F: FnMut() -> Fut,
1103 Fut: Future<Output = Result<(), E>>,
1104{
1105 type Output = Result<Generation, E>;
1106
1107 /// Polls until a successful check belongs to an unchanged generation.
1108 ///
1109 /// Direct invalidation replaces an outstanding check. Propagated invalidation
1110 /// lets it finish, but retries stale successes; errors return without retry.
1111 /// Repeated invalidation yields to the executor instead of spinning.
1112 /// After completion, the next poll starts a new check.
1113 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1114 let mut this = self.project();
1115 let mut restarted = false;
1116 loop {
1117 // `&Option<Fut>` would retag the whole future and invalidate
1118 // borrows it holds into itself, `&mut` to a `!Unpin` future is not retagged.
1119 if this.fut.as_mut().as_pin_mut().is_none() {
1120 *this.generation = this.scope.generation();
1121 this.fut.set(Some((this.check)()));
1122 }
1123 if let Some(observer) = this.observer.as_ref() {
1124 observer.register(cx.waker());
1125 }
1126 let result = if this.scope.is_directly_invalidated(*this.generation) {
1127 None
1128 } else {
1129 let before_poll = this.scope.generation();
1130 match this.fut.as_mut().as_pin_mut().unwrap().poll(cx) {
1131 Poll::Ready(result) => Some(result),
1132 Poll::Pending => {
1133 let scope = *this.scope;
1134 this.observer
1135 .get_or_insert_with(|| scope.observer())
1136 .register(cx.waker());
1137 // A first-poll notification may precede registration.
1138 if !this.scope.is_current(before_poll) {
1139 cx.waker().wake_by_ref();
1140 }
1141 return Poll::Pending;
1142 }
1143 }
1144 };
1145 this.fut.set(None);
1146 if let Some(result) = result {
1147 *this.observer = None;
1148 result?;
1149 if this.scope.is_current(*this.generation) {
1150 return Poll::Ready(Ok(*this.generation));
1151 }
1152 }
1153 // A check that keeps invalidating its own scope must not starve the executor.
1154 if restarted {
1155 cx.waker().wake_by_ref();
1156 return Poll::Pending;
1157 }
1158 restarted = true;
1159 }
1160 }
1161}
1162
1163#[cfg(test)]
1164#[path = "../tests/unit/readiness.rs"]
1165mod tests;