|
| 1 | +/* |
| 2 | + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | + |
| 6 | +use aws_smithy_types::byte_stream::error::Error as ByteStreamError; |
| 7 | +use futures_util::future; |
| 8 | +use std::sync::Arc; |
| 9 | +use tower::retry::budget::{Budget, TpsBudget}; |
| 10 | + |
| 11 | +/// A `tower::retry::Policy` implementation for retrying requests |
| 12 | +#[derive(Debug, Clone)] |
| 13 | +pub(crate) struct RetryPolicy { |
| 14 | + budget: Arc<TpsBudget>, |
| 15 | + remaining_attempts: usize, |
| 16 | +} |
| 17 | + |
| 18 | +impl Default for RetryPolicy { |
| 19 | + fn default() -> Self { |
| 20 | + Self { |
| 21 | + budget: Arc::new(TpsBudget::default()), |
| 22 | + remaining_attempts: 2, |
| 23 | + } |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +fn find_source<'a, E: std::error::Error + 'static>( |
| 28 | + err: &'a (dyn std::error::Error + 'static), |
| 29 | +) -> Option<&'a E> { |
| 30 | + let mut next = Some(err); |
| 31 | + while let Some(err) = next { |
| 32 | + if let Some(matching_err) = err.downcast_ref::<E>() { |
| 33 | + return Some(matching_err); |
| 34 | + } |
| 35 | + next = err.source(); |
| 36 | + } |
| 37 | + None |
| 38 | +} |
| 39 | + |
| 40 | +impl<Req, Res, E> tower::retry::Policy<Req, Res, E> for RetryPolicy |
| 41 | +where |
| 42 | + Req: Clone, |
| 43 | + E: std::error::Error + 'static, |
| 44 | +{ |
| 45 | + type Future = future::Ready<()>; |
| 46 | + |
| 47 | + fn retry(&mut self, _req: &mut Req, result: &mut Result<Res, E>) -> Option<Self::Future> { |
| 48 | + match result { |
| 49 | + Ok(_) => { |
| 50 | + self.budget.deposit(); |
| 51 | + None |
| 52 | + } |
| 53 | + Err(err) => { |
| 54 | + // the only type of error we care about at this point is errors that come from |
| 55 | + // reading the body, all other errors go through the SDK retry implementation |
| 56 | + // already |
| 57 | + find_source::<ByteStreamError>(err)?; |
| 58 | + if self.remaining_attempts == 0 || !self.budget.withdraw() { |
| 59 | + return None; |
| 60 | + } |
| 61 | + self.remaining_attempts -= 1; |
| 62 | + Some(future::ready(())) |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + fn clone_request(&mut self, req: &Req) -> Option<Req> { |
| 68 | + Some(req.clone()) |
| 69 | + } |
| 70 | +} |
0 commit comments