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
12pub 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 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 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 pub fn is_ready(&self) -> bool {
88 self.api.scope().is_ready()
89 }
90
91 #[inline]
92 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 pub fn shutdown<'a>(&'a self, st: &'a St) -> impl Future<Output = ()> {
106 self.api.shutdown(0, st)
107 }
108
109 #[inline]
110 pub fn is_shutdown(&self) -> bool {
115 self.api.is_shutdown()
116 }
117
118 #[inline]
119 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 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 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 pub fn on_notify(&self, callback: &ReadyCallback) {
175 self.api.scope().on_notify(callback);
176 }
177
178 #[inline]
179 pub fn bind_to(&self, ctx: &BindCtx<'_>) {
185 ctx.subscribe_pipeline(&self.readiness_link());
186 }
187
188 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
204pub 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 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 pub fn is_shutdown(&self) -> bool {
250 self.api.is_shutdown()
251 }
252
253 #[inline]
254 pub fn on_notify(&self, callback: &ReadyCallback) {
260 self.api.scope().on_notify(callback);
261 }
262
263 #[inline]
264 pub fn bind_to(&self, ctx: &BindCtx<'_>) {
268 ctx.subscribe_pipeline(&self.readiness_link());
269 }
270
271 pub fn readiness_link(&self) -> ReadyLink {
275 self.api.scope().readiness_link()
276 }
277}
278
279struct PipelineInternal<St, Req, Res, Err> {
282 st: St,
283 api: Rc<dyn PipelineStateApi<St, Req, Res, Err>>,
284}
285
286impl<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
332struct PipelineInner<S, E> {
335 s: S,
336 waiters: WaitersRef,
337 readiness: PipelineReadiness<E>,
338 _pinned: PhantomPinned,
341 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 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 fn call<'a>(&'a self, req: Req, st: &'a St) -> CallFuture<'a, Result<Res, Err>>
392 where
393 Req: 'a;
394
395 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 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 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;