rama_http/layer/retry/policy.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
use super::RetryBody;
use crate::Request;
use rama_core::Context;
use std::future::Future;
/// A "retry policy" to classify if a request should be retried.
///
/// # Example
///
/// ```
/// use rama_core::Context;
/// use rama_http::Request;
/// use rama_http::layer::retry::{Policy, PolicyResult, RetryBody};
/// use std::sync::Arc;
/// use parking_lot::Mutex;
///
/// struct Attempts(Arc<Mutex<usize>>);
///
/// impl<S, R, E> Policy<S, R, E> for Attempts
/// where
/// S: Clone + Send + Sync + 'static,
/// R: Send + 'static,
/// E: Send + Sync + 'static,
/// {
/// async fn retry(&self, ctx: Context<S>, req: Request<RetryBody>, result: Result<R, E>) -> PolicyResult<S, R, E> {
/// match result {
/// Ok(_) => {
/// // Treat all `Response`s as success,
/// // so don't retry...
/// PolicyResult::Abort(result)
/// },
/// Err(_) => {
/// // Treat all errors as failures...
/// // But we limit the number of attempts...
/// let mut attempts = self.0.lock();
/// if *attempts > 0 {
/// // Try again!
/// *attempts -= 1;
/// PolicyResult::Retry { ctx, req }
/// } else {
/// // Used all our attempts, no retry...
/// PolicyResult::Abort(result)
/// }
/// }
/// }
/// }
///
/// fn clone_input(&self, ctx: &Context<S>, req: &Request<RetryBody>) -> Option<(Context<S>, Request<RetryBody>)> {
/// Some((ctx.clone(), req.clone()))
/// }
/// }
/// ```
pub trait Policy<S, R, E>: Send + Sync + 'static {
/// Check the policy if a certain request should be retried.
///
/// This method is passed a reference to the original request, and either
/// the [`Service::Response`] or [`Service::Error`] from the inner service.
///
/// If the request should **not** be retried, return `None`.
///
/// If the request *should* be retried, return `Some` future that will delay
/// the next retry of the request. This can be used to sleep for a certain
/// duration, to wait for some external condition to be met before retrying,
/// or resolve right away, if the request should be retried immediately.
///
/// ## Mutating Requests
///
/// The policy MAY chose to mutate the `req`: if the request is mutated, the
/// mutated request will be sent to the inner service in the next retry.
/// This can be helpful for use cases like tracking the retry count in a
/// header.
///
/// ## Mutating Results
///
/// The policy MAY chose to mutate the result. This enables the retry
/// policy to convert a failure into a success and vice versa. For example,
/// if the policy is used to poll while waiting for a state change, the
/// policy can switch the result to emit a specific error when retries are
/// exhausted.
///
/// The policy can also record metadata on the request to include
/// information about the number of retries required or to record that a
/// failure failed after exhausting all retries.
///
/// [`Service::Response`]: rama_core::Service::Response
/// [`Service::Error`]: rama_core::Service::Error
fn retry(
&self,
ctx: Context<S>,
req: Request<RetryBody>,
result: Result<R, E>,
) -> impl Future<Output = PolicyResult<S, R, E>> + Send + '_;
/// Tries to clone a request before being passed to the inner service.
///
/// If the request cannot be cloned, return [`None`]. Moreover, the retry
/// function will not be called if the [`None`] is returned.
fn clone_input(
&self,
ctx: &Context<S>,
req: &Request<RetryBody>,
) -> Option<(Context<S>, Request<RetryBody>)>;
}
impl<P, S, R, E> Policy<S, R, E> for &'static P
where
P: Policy<S, R, E>,
{
fn retry(
&self,
ctx: Context<S>,
req: Request<RetryBody>,
result: Result<R, E>,
) -> impl Future<Output = PolicyResult<S, R, E>> + Send + '_ {
(**self).retry(ctx, req, result)
}
fn clone_input(
&self,
ctx: &Context<S>,
req: &Request<RetryBody>,
) -> Option<(Context<S>, Request<RetryBody>)> {
(**self).clone_input(ctx, req)
}
}
impl<P, S, R, E> Policy<S, R, E> for std::sync::Arc<P>
where
P: Policy<S, R, E>,
{
fn retry(
&self,
ctx: Context<S>,
req: Request<RetryBody>,
result: Result<R, E>,
) -> impl Future<Output = PolicyResult<S, R, E>> + Send + '_ {
(**self).retry(ctx, req, result)
}
fn clone_input(
&self,
ctx: &Context<S>,
req: &Request<RetryBody>,
) -> Option<(Context<S>, Request<RetryBody>)> {
(**self).clone_input(ctx, req)
}
}
/// The full result of a limit policy.
pub enum PolicyResult<S, R, E> {
/// The result should not be retried,
/// and the result should be returned to the caller.
Abort(Result<R, E>),
/// The result should be retried,
/// and the request should be passed to the inner service again.
Retry {
/// The context of the request.
ctx: Context<S>,
/// The request to be retried, with the above context.
req: Request<RetryBody>,
},
}
impl<S, R, E> std::fmt::Debug for PolicyResult<S, R, E>
where
S: std::fmt::Debug,
R: std::fmt::Debug,
E: std::fmt::Debug,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
PolicyResult::Abort(err) => write!(f, "PolicyResult::Abort({:?})", err),
PolicyResult::Retry { ctx, req } => write!(
f,
"PolicyResult::Retry {{ ctx: {:?}, req: {:?} }}",
ctx, req
),
}
}
}
macro_rules! impl_retry_policy_either {
($id:ident, $($param:ident),+ $(,)?) => {
impl<$($param),+, State, Response, Error> Policy<State, Response, Error> for rama_core::combinators::$id<$($param),+>
where
$($param: Policy<State, Response, Error>),+,
State: Clone + Send + Sync + 'static,
Response: Send + 'static,
Error: Send + Sync + 'static,
{
async fn retry(
&self,
ctx: Context<State>,
req: http::Request<RetryBody>,
result: Result<Response, Error>,
) -> PolicyResult<State, Response, Error> {
match self {
$(
rama_core::combinators::$id::$param(policy) => policy.retry(ctx, req, result).await,
)+
}
}
fn clone_input(
&self,
ctx: &Context<State>,
req: &http::Request<RetryBody>,
) -> Option<(Context<State>, http::Request<RetryBody>)> {
match self {
$(
rama_core::combinators::$id::$param(policy) => policy.clone_input(ctx, req),
)+
}
}
}
};
}
rama_core::combinators::impl_either!(impl_retry_policy_either);