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
9pub(crate) const NO_SLOT: u32 = u32::MAX - 1;
14
15pub struct Ctx<'a, Svc: ?Sized, St = ()> {
26 idx: u32,
27 st: &'a St,
28 waiters: &'a WaitersRef,
29 scope: &'a ReadyScope,
30 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 scratch: cell::RefCell<Vec<Waker>>,
50 indexes: cell::UnsafeCell<slab::Slab<Option<Waker>>>,
51 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 unsafe { &mut *self.indexes.get() }
80 }
81
82 #[allow(clippy::mut_from_ref)]
83 fn get_calls(&self) -> &mut slab::Slab<Option<Waker>> {
84 unsafe { &mut *self.calls.get() }
87 }
88
89 #[allow(clippy::mut_from_ref)]
90 pub(crate) fn get_wakers(&self) -> &mut Vec<u32> {
91 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 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 let mut scratch = self.scratch.borrow_mut();
145 if wakers.capacity() > scratch.capacity() {
146 *scratch = wakers;
147 }
148 }
149
150 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 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 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 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 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 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 self.queue_wake(idx);
252 return Poll::Pending;
253 }
254
255 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 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 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
318struct 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 pub(crate) fn into_call(mut self) -> Self {
373 self.in_call = true;
374 self
375 }
376
377 #[inline]
378 pub fn id(&self) -> u32 {
383 self.idx
384 }
385
386 #[inline]
387 pub fn st(&self) -> &'a St {
389 self.st
390 }
391
392 #[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 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 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 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 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 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 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 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
604pin_project_lite::pin_project! {
606 struct ReadyCall<'a, F, Fut, O> {
607 #[pin]
608 check: RunCheck<'a, F, Fut>,
609 waiters: &'a WaitersRef,
610 idx: u32,
612 lazy: bool,
614 in_call: bool,
615 key: Option<u32>,
617 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 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 Ok(generation) if !this.check.scope().is_current(generation) => {}
669 result => return Poll::Ready(result.map(O::from)),
670 }
671 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;