1use std::future::Future;
2use std::pin::Pin;
3use std::task::{Context, Poll};
4
5use futures_util::{ready, TryFuture};
6use pin_project::pin_project;
7
8use super::{Filter, FilterBase, Func, Internal};
9use crate::generic::Either;
10use crate::reject::IsReject;
11use crate::route;
12
13#[derive(Clone, Copy, Debug)]
14pub struct Recover<T, F> {
15 pub(super) filter: T,
16 pub(super) callback: F,
17}
18
19impl<T, F> FilterBase for Recover<T, F>
20where
21 T: Filter,
22 F: Func<T::Error> + Clone + Send,
23 F::Output: TryFuture + Send,
24 <F::Output as TryFuture>::Error: IsReject,
25{
26 type Extract = (Either<T::Extract, (<F::Output as TryFuture>::Ok,)>,);
27 type Error = <F::Output as TryFuture>::Error;
28 type Future = RecoverFuture<T, F>;
29 #[inline]
30 fn filter(&self, _: Internal) -> Self::Future {
31 let idx = route::with(|route| route.matched_path_index());
32 RecoverFuture {
33 state: State::First(self.filter.filter(Internal), self.callback.clone()),
34 original_path_index: PathIndex(idx),
35 }
36 }
37}
38
39#[allow(missing_debug_implementations)]
40#[pin_project]
41pub struct RecoverFuture<T: Filter, F>
42where
43 T: Filter,
44 F: Func<T::Error>,
45 F::Output: TryFuture + Send,
46 <F::Output as TryFuture>::Error: IsReject,
47{
48 #[pin]
49 state: State<T, F>,
50 original_path_index: PathIndex,
51}
52
53#[pin_project(project = StateProj)]
54enum State<T, F>
55where
56 T: Filter,
57 F: Func<T::Error>,
58 F::Output: TryFuture + Send,
59 <F::Output as TryFuture>::Error: IsReject,
60{
61 First(#[pin] T::Future, F),
62 Second(#[pin] F::Output),
63 Done,
64}
65
66#[derive(Copy, Clone)]
67struct PathIndex(usize);
68
69impl PathIndex {
70 fn reset_path(&self) {
71 route::with(|route| route.reset_matched_path_index(self.0));
72 }
73}
74
75impl<T, F> Future for RecoverFuture<T, F>
76where
77 T: Filter,
78 F: Func<T::Error>,
79 F::Output: TryFuture + Send,
80 <F::Output as TryFuture>::Error: IsReject,
81{
82 type Output = Result<
83 (Either<T::Extract, (<F::Output as TryFuture>::Ok,)>,),
84 <F::Output as TryFuture>::Error,
85 >;
86
87 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
88 loop {
89 let pin = self.as_mut().project();
90 let (err, second) = match pin.state.project() {
91 StateProj::First(first, second) => match ready!(first.try_poll(cx)) {
92 Ok(ex) => return Poll::Ready(Ok((Either::A(ex),))),
93 Err(err) => (err, second),
94 },
95 StateProj::Second(second) => {
96 let ex2 = match ready!(second.try_poll(cx)) {
97 Ok(ex2) => Ok((Either::B((ex2,)),)),
98 Err(e) => Err(e),
99 };
100 self.set(RecoverFuture {
101 state: State::Done,
102 ..*self
103 });
104 return Poll::Ready(ex2);
105 }
106 StateProj::Done => panic!("polled after complete"),
107 };
108
109 pin.original_path_index.reset_path();
110 let fut2 = second.call(err);
111 self.set(RecoverFuture {
112 state: State::Second(fut2),
113 ..*self
114 });
115 }
116 }
117}