Compare commits

...

20 Commits

Author SHA1 Message Date
joshbenaron 6c0916eecb
Merge df3bf79873 into afd53045d4 2026-01-09 22:40:37 +08:00
dependabot[bot] afd53045d4
build(deps): bump taiki-e/cache-cargo-install-action from 2.3.1 to 3.0.0 (#3867)
Bumps [taiki-e/cache-cargo-install-action](https://github.com/taiki-e/cache-cargo-install-action) from 2.3.1 to 3.0.0.
- [Release notes](https://github.com/taiki-e/cache-cargo-install-action/releases)
- [Changelog](https://github.com/taiki-e/cache-cargo-install-action/blob/main/CHANGELOG.md)
- [Commits](7447f04c51...25ef989260)

---
updated-dependencies:
- dependency-name: taiki-e/cache-cargo-install-action
  dependency-version: 3.0.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-01-06 22:08:06 +00:00
dependabot[bot] d0b9f46e50
build(deps): bump tokio-util from 0.7.17 to 0.7.18 (#3871)
Bumps [tokio-util](https://github.com/tokio-rs/tokio) from 0.7.17 to 0.7.18.
- [Release notes](https://github.com/tokio-rs/tokio/releases)
- [Commits](https://github.com/tokio-rs/tokio/compare/tokio-util-0.7.17...tokio-util-0.7.18)

---
updated-dependencies:
- dependency-name: tokio-util
  dependency-version: 0.7.18
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-01-06 22:08:00 +00:00
dependabot[bot] e04b8d548d
build(deps): bump tokio from 1.48.0 to 1.49.0 (#3872)
Bumps [tokio](https://github.com/tokio-rs/tokio) from 1.48.0 to 1.49.0.
- [Release notes](https://github.com/tokio-rs/tokio/releases)
- [Commits](https://github.com/tokio-rs/tokio/compare/tokio-1.48.0...tokio-1.49.0)

---
updated-dependencies:
- dependency-name: tokio
  dependency-version: 1.49.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-01-06 22:07:57 +00:00
dependabot[bot] 12db2a4d30
build(deps): bump tokio-stream from 0.1.17 to 0.1.18 (#3869)
Bumps [tokio-stream](https://github.com/tokio-rs/tokio) from 0.1.17 to 0.1.18.
- [Release notes](https://github.com/tokio-rs/tokio/releases)
- [Commits](https://github.com/tokio-rs/tokio/compare/tokio-stream-0.1.17...tokio-stream-0.1.18)

---
updated-dependencies:
- dependency-name: tokio-stream
  dependency-version: 0.1.18
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-01-05 21:23:55 +00:00
dependabot[bot] d2a2c15ef1
build(deps): bump codecov/codecov-action from 5.5.1 to 5.5.2 (#3856)
Bumps [codecov/codecov-action](https://github.com/codecov/codecov-action) from 5.5.1 to 5.5.2.
- [Release notes](https://github.com/codecov/codecov-action/releases)
- [Changelog](https://github.com/codecov/codecov-action/blob/main/CHANGELOG.md)
- [Commits](5a1091511a...671740ac38)

---
updated-dependencies:
- dependency-name: codecov/codecov-action
  dependency-version: 5.5.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-01-05 21:08:09 +00:00
dependabot[bot] 9b25a18383
build(deps): bump proc-macro2 from 1.0.103 to 1.0.104 (#3870)
Bumps [proc-macro2](https://github.com/dtolnay/proc-macro2) from 1.0.103 to 1.0.104.
- [Release notes](https://github.com/dtolnay/proc-macro2/releases)
- [Commits](https://github.com/dtolnay/proc-macro2/compare/1.0.103...1.0.104)

---
updated-dependencies:
- dependency-name: proc-macro2
  dependency-version: 1.0.104
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-01-05 21:06:24 +00:00
dependabot[bot] 564b364638
build(deps): bump taiki-e/install-action from 2.65.6 to 2.65.12 (#3868)
Bumps [taiki-e/install-action](https://github.com/taiki-e/install-action) from 2.65.6 to 2.65.12.
- [Release notes](https://github.com/taiki-e/install-action/releases)
- [Changelog](https://github.com/taiki-e/install-action/blob/main/CHANGELOG.md)
- [Commits](28a9d316db...cc33365ec7)

---
updated-dependencies:
- dependency-name: taiki-e/install-action
  dependency-version: 2.65.12
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-01-05 21:04:28 +00:00
dependabot[bot] 024addfc40
build(deps): bump serde_json from 1.0.145 to 1.0.148 (#3865)
Bumps [serde_json](https://github.com/serde-rs/json) from 1.0.145 to 1.0.148.
- [Release notes](https://github.com/serde-rs/json/releases)
- [Commits](https://github.com/serde-rs/json/compare/v1.0.145...v1.0.148)

---
updated-dependencies:
- dependency-name: serde_json
  dependency-version: 1.0.148
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-12-30 00:51:22 +00:00
dependabot[bot] 06ad9309b8
build(deps): bump itoa from 1.0.15 to 1.0.17 (#3863)
Bumps [itoa](https://github.com/dtolnay/itoa) from 1.0.15 to 1.0.17.
- [Release notes](https://github.com/dtolnay/itoa/releases)
- [Commits](https://github.com/dtolnay/itoa/compare/1.0.15...1.0.17)

---
updated-dependencies:
- dependency-name: itoa
  dependency-version: 1.0.17
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-12-30 00:51:03 +00:00
dependabot[bot] 9f9855d1a2
build(deps): bump tracing from 0.1.43 to 0.1.44 (#3864)
Bumps [tracing](https://github.com/tokio-rs/tracing) from 0.1.43 to 0.1.44.
- [Release notes](https://github.com/tokio-rs/tracing/releases)
- [Commits](https://github.com/tokio-rs/tracing/compare/tracing-0.1.43...tracing-0.1.44)

---
updated-dependencies:
- dependency-name: tracing
  dependency-version: 0.1.44
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-12-30 00:50:49 +00:00
dependabot[bot] 4c62e88edb
build(deps): bump derive_more from 2.1.0 to 2.1.1 (#3862)
Bumps [derive_more](https://github.com/JelteF/derive_more) from 2.1.0 to 2.1.1.
- [Release notes](https://github.com/JelteF/derive_more/releases)
- [Changelog](https://github.com/JelteF/derive_more/blob/master/CHANGELOG.md)
- [Commits](https://github.com/JelteF/derive_more/compare/v2.1.0...v2.1.1)

---
updated-dependencies:
- dependency-name: derive_more
  dependency-version: 2.1.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-12-29 23:15:28 +00:00
dependabot[bot] 2d84d20ebd
build(deps): bump taiki-e/install-action from 2.63.1 to 2.65.6 (#3861)
Bumps [taiki-e/install-action](https://github.com/taiki-e/install-action) from 2.63.1 to 2.65.6.
- [Release notes](https://github.com/taiki-e/install-action/releases)
- [Changelog](https://github.com/taiki-e/install-action/blob/main/CHANGELOG.md)
- [Commits](61e5998d10...28a9d316db)

---
updated-dependencies:
- dependency-name: taiki-e/install-action
  dependency-version: 2.65.6
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-12-29 23:15:16 +00:00
dependabot[bot] 2b8db90c4d
build(deps): bump rustls-pki-types from 1.13.1 to 1.13.2 (#3860)
Bumps [rustls-pki-types](https://github.com/rustls/pki-types) from 1.13.1 to 1.13.2.
- [Release notes](https://github.com/rustls/pki-types/releases)
- [Commits](https://github.com/rustls/pki-types/compare/v/1.13.1...v/1.13.2)

---
updated-dependencies:
- dependency-name: rustls-pki-types
  dependency-version: 1.13.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-12-29 01:06:46 +00:00
Rob Ede df3bf79873
Merge branch 'master' into origin/feature/awc-retry-middleware 2024-06-11 01:13:42 +01:00
fakeshadow 58dfc3ba22
Merge branch 'master' into origin/feature/awc-retry-middleware 2021-05-29 20:42:20 +08:00
joshbenaron e87e636e84 Fix formatting 2021-04-02 19:06:39 +01:00
joshbenaron 22e40613e8 Improved readability and logic 2021-04-02 18:50:07 +01:00
joshbenaron 58904b9ebc Fixed invalid tests 2021-04-02 14:50:43 +01:00
joshbenaron bb1bf5f2be Add awc retry middleware 2021-04-02 13:27:30 +01:00
7 changed files with 387 additions and 31 deletions

View File

@ -49,7 +49,7 @@ jobs:
toolchain: ${{ matrix.version.version }}
- name: Install just, cargo-hack, cargo-nextest, cargo-ci-cache-clean
uses: taiki-e/install-action@61e5998d108b2b55a81b9b386c18bd46e4237e4f # v2.63.1
uses: taiki-e/install-action@cc33365ec7e3350bc47bf935f247582cc6f68344 # v2.65.12
with:
tool: just,cargo-hack,cargo-nextest,cargo-ci-cache-clean
@ -83,7 +83,7 @@ jobs:
uses: actions-rust-lang/setup-rust-toolchain@1780873c7b576612439a134613cc4cc74ce5538c # v1.15.2
- name: Install just, cargo-hack
uses: taiki-e/install-action@61e5998d108b2b55a81b9b386c18bd46e4237e4f # v2.63.1
uses: taiki-e/install-action@cc33365ec7e3350bc47bf935f247582cc6f68344 # v2.65.12
with:
tool: just,cargo-hack

View File

@ -64,7 +64,7 @@ jobs:
toolchain: ${{ matrix.version.version }}
- name: Install just, cargo-hack, cargo-nextest, cargo-ci-cache-clean
uses: taiki-e/install-action@61e5998d108b2b55a81b9b386c18bd46e4237e4f # v2.63.1
uses: taiki-e/install-action@cc33365ec7e3350bc47bf935f247582cc6f68344 # v2.65.12
with:
tool: just,cargo-hack,cargo-nextest,cargo-ci-cache-clean
@ -117,7 +117,7 @@ jobs:
toolchain: nightly
- name: Install just
uses: taiki-e/install-action@61e5998d108b2b55a81b9b386c18bd46e4237e4f # v2.63.1
uses: taiki-e/install-action@cc33365ec7e3350bc47bf935f247582cc6f68344 # v2.65.12
with:
tool: just

View File

@ -24,7 +24,7 @@ jobs:
components: llvm-tools
- name: Install just, cargo-llvm-cov, cargo-nextest
uses: taiki-e/install-action@61e5998d108b2b55a81b9b386c18bd46e4237e4f # v2.63.1
uses: taiki-e/install-action@cc33365ec7e3350bc47bf935f247582cc6f68344 # v2.65.12
with:
tool: just,cargo-llvm-cov,cargo-nextest
@ -32,7 +32,7 @@ jobs:
run: just test-coverage-codecov
- name: Upload coverage to Codecov
uses: codecov/codecov-action@5a1091511ad55cbe89839c7260b706298ca349f7 # v5.5.1
uses: codecov/codecov-action@671740ac38dd9b0130fbe1cec585b89eea48d3de # v5.5.2
with:
files: codecov.json
fail_ci_if_error: true

View File

@ -77,12 +77,12 @@ jobs:
toolchain: ${{ vars.RUST_VERSION_EXTERNAL_TYPES }}
- name: Install just
uses: taiki-e/install-action@61e5998d108b2b55a81b9b386c18bd46e4237e4f # v2.63.1
uses: taiki-e/install-action@cc33365ec7e3350bc47bf935f247582cc6f68344 # v2.65.12
with:
tool: just
- name: Install cargo-check-external-types
uses: taiki-e/cache-cargo-install-action@7447f04c51f2ba27ca35e7f1e28fab848c5b3ba7 # v2.3.1
uses: taiki-e/cache-cargo-install-action@25ef9892608d184944df486ae09ffae168b3cda3 # v3.0.0
with:
tool: cargo-check-external-types

52
Cargo.lock generated
View File

@ -1117,18 +1117,18 @@ dependencies = [
[[package]]
name = "derive_more"
version = "2.1.0"
version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10b768e943bed7bf2cab53df09f4bc34bfd217cdb57d971e769874c9a6710618"
checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134"
dependencies = [
"derive_more-impl",
]
[[package]]
name = "derive_more-impl"
version = "2.1.0"
version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6d286bfdaf75e988b4a78e013ecd79c581e06399ab53fbacd2d916c2f904f30b"
checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb"
dependencies = [
"convert_case",
"proc-macro2",
@ -1833,9 +1833,9 @@ dependencies = [
[[package]]
name = "itoa"
version = "1.0.15"
version = "1.0.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c"
checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2"
[[package]]
name = "jiff"
@ -2262,9 +2262,9 @@ dependencies = [
[[package]]
name = "proc-macro2"
version = "1.0.103"
version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ee95bc4ef87b8d5ba32e8b7714ccc834865276eab0aed5c9958d00ec45f49e8"
checksum = "9695f8df41bb4f3d222c95a67532365f569318332d03d5f3f67f37b20e6ebdf0"
dependencies = [
"unicode-ident",
]
@ -2544,9 +2544,9 @@ dependencies = [
[[package]]
name = "rustls-pki-types"
version = "1.13.1"
version = "1.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "708c0f9d5f54ba0272468c1d306a52c495b31fa155e91bc25371e6df7996908c"
checksum = "21e6f2ab2928ca4291b86736a8bd920a277a399bba1589409d72154ff87c1282"
dependencies = [
"zeroize",
]
@ -2697,15 +2697,15 @@ dependencies = [
[[package]]
name = "serde_json"
version = "1.0.145"
version = "1.0.148"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "402a6f66d8c709116cf22f558eab210f5a50187f702eb4d7e5ef38d9a7f1c79c"
checksum = "3084b546a1dd6289475996f182a22aba973866ea8e8b02c51d9f46b1336a22da"
dependencies = [
"itoa",
"memchr",
"ryu",
"serde",
"serde_core",
"zmij",
]
[[package]]
@ -3033,9 +3033,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "tokio"
version = "1.48.0"
version = "1.49.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff360e02eab121e0bc37a2d3b4d4dc622e6eda3a8e5253d5435ecf5bd4c68408"
checksum = "72a2903cd7736441aac9df9d7688bd0ce48edccaadf181c3b90be801e81d3d86"
dependencies = [
"bytes",
"libc",
@ -3114,9 +3114,9 @@ dependencies = [
[[package]]
name = "tokio-stream"
version = "0.1.17"
version = "0.1.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eca58d7bba4a75707817a2c44174253f9236b2d5fbd055602e9d5c07c139a047"
checksum = "32da49809aab5c3bc678af03902d4ccddea2a87d028d86392a4b1560c6906c70"
dependencies = [
"futures-core",
"pin-project-lite",
@ -3140,9 +3140,9 @@ dependencies = [
[[package]]
name = "tokio-util"
version = "0.7.17"
version = "0.7.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2efa149fe76073d6e8fd97ef4f4eca7b67f599660115591483572e406e165594"
checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098"
dependencies = [
"bytes",
"futures-core",
@ -3192,9 +3192,9 @@ checksum = "df8b2b54733674ad286d16267dcfc7a71ed5c776e4ac7aa3c3e2561f7c637bf2"
[[package]]
name = "tracing"
version = "0.1.43"
version = "0.1.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d15d90a0b5c19378952d479dc858407149d7bb45a14de0142f6c534b16fc647"
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
dependencies = [
"log",
"pin-project-lite",
@ -3215,9 +3215,9 @@ dependencies = [
[[package]]
name = "tracing-core"
version = "0.1.35"
version = "0.1.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a04e24fab5c89c6a36eb8558c9656f30d81de51dfa4d3b45f26b21d61fa0a6c"
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
dependencies = [
"once_cell",
]
@ -3872,6 +3872,12 @@ dependencies = [
"syn",
]
[[package]]
name = "zmij"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f4a4e8e9dc5c62d159f04fcdbe07f4c3fb710415aab4754bf11505501e3251d"
[[package]]
name = "zstd"
version = "0.13.3"

View File

@ -1,10 +1,12 @@
mod redirect;
mod retry;
use std::marker::PhantomData;
use actix_service::Service;
pub use self::redirect::Redirect;
pub use self::retry::Retry;
/// Trait for transform a type to another one.
/// Both the input and output type should impl [actix_service::Service] trait.

348
awc/src/middleware/retry.rs Normal file
View File

@ -0,0 +1,348 @@
use super::Transform;
use crate::RequestHead;
use crate::{ConnectRequest, ConnectResponse};
use actix_http::body::Body;
use actix_http::client::SendRequestError;
use actix_http::http::{HeaderMap, StatusCode};
use actix_http::RequestHeadType;
use actix_service::Service;
use futures_core::future::LocalBoxFuture;
use std::ops::Deref;
use std::rc::Rc;
use std::task::{Context, Poll};
pub struct Retry(Inner);
struct Inner {
/// Number of retries. So each request will be tried [max_retry + 1] times
max_retry: u8,
policies: Vec<RetryPolicy>,
}
impl Retry {
pub fn new(retries: u8) -> Self {
Retry(Inner {
max_retry: retries,
policies: vec![],
})
}
/// Allows you to add a retry policy to the [`policies`]
/// It allows two types of policy:
/// - `Vec<StatusCode>` and will retry if one of them is received
/// - `Fn(&ResponseHead) -> bool` and will retry when this function resolves to false
///
/// # example
///
///```
///
/// // Creates a policy which will try each request a max of 5 times if any policies resolve to true
/// // i.e.
/// // if you receive a 401 or 501 status code
/// // or
/// // the response doesn't have a [`SOME_HEADER`] header
/// use awc::http::{StatusCode, HeaderMap};
/// use awc::middleware::Retry;
///
/// let retry_policies = Retry::new(5)
/// .policy(vec![StatusCode::INTERNAL_SERVER_ERROR, StatusCode::UNAUTHORIZED])
/// .policy(|code: StatusCode, headers: &HeaderMap| {
/// return if headers.contains_key("SOME_HEADER") {
/// true
/// } else {
/// false
/// };
/// });
///
/// // Creates awc client
/// let client = awc::Client::builder()
/// .wrap(retry_policies)
/// .finish();
///```
pub fn policy<T>(mut self, p: T) -> Self
where
T: IntoRetryPolicy,
{
self.0.policies.push(p.into_policy());
self
}
}
#[non_exhaustive]
pub enum RetryPolicy {
Status(Vec<StatusCode>),
Custom(Box<dyn Fn(StatusCode, &HeaderMap) -> bool>),
}
pub trait IntoRetryPolicy {
fn into_policy(self) -> RetryPolicy;
}
impl<T> IntoRetryPolicy for T
where
T: for<'a> Fn(StatusCode, &'a HeaderMap) -> bool + 'static,
{
fn into_policy(self) -> RetryPolicy {
RetryPolicy::Custom(Box::new(self))
}
}
impl IntoRetryPolicy for Vec<StatusCode> {
fn into_policy(self) -> RetryPolicy {
RetryPolicy::Status(self)
}
}
impl<S> Transform<S, ConnectRequest> for Retry
where
S: Service<ConnectRequest, Response = ConnectResponse, Error = SendRequestError> + 'static,
{
type Transform = RetryService<S>;
fn new_transform(self, service: S) -> Self::Transform {
RetryService {
max_retry: self.0.max_retry,
policies: self.0.policies.into_boxed_slice().into(),
connector: service.into(),
}
}
}
#[derive(Clone)]
pub struct RetryService<S> {
policies: Rc<[RetryPolicy]>,
max_retry: u8,
connector: Rc<S>,
}
impl<S> Service<ConnectRequest> for RetryService<S>
where
S: Service<ConnectRequest, Response = ConnectResponse, Error = SendRequestError> + 'static,
{
type Response = S::Response;
type Error = S::Error;
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.connector.poll_ready(ctx)
}
fn call(&self, req: ConnectRequest) -> Self::Future {
let connector = self.connector.clone();
let policies = self.policies.clone();
let max_retry = self.max_retry;
Box::pin(async move {
match req {
ConnectRequest::Client(head, body, addr) => {
for _ in 0..max_retry {
let h = clone_request_head_type(&head);
let result = connector
.call(ConnectRequest::Client(h, body_to_retry_body(&body), addr))
.await;
if let Ok(res) = result {
match &res {
ConnectResponse::Client(ref r) => {
if is_valid_response(
policies.as_ref(),
r.status(),
r.headers(),
) {
return Ok(res);
}
}
ConnectResponse::Tunnel(ref head, _) => {
if is_valid_response(
policies.as_ref(),
head.status,
head.headers(),
) {
return Ok(res);
}
}
}
}
}
// Exceed max retry so just return whatever response is received
log::debug!("Request max retry reached");
connector
.call(ConnectRequest::Client(head, body, addr))
.await
}
ConnectRequest::Tunnel(head, addr) => {
for _ in 1..max_retry {
let h = clone_request_head(&head);
let result = connector.call(ConnectRequest::Tunnel(h, addr)).await;
if let Ok(res) = result {
match &res {
ConnectResponse::Client(r) => {
if is_valid_response(&policies, r.status(), r.headers()) {
return Ok(res);
}
}
ConnectResponse::Tunnel(head, _) => {
if is_valid_response(&policies, head.status, head.headers())
{
return Ok(res);
}
}
}
}
}
// Exceed max retry so just return whatever response is received
log::debug!("Request max retry reached");
connector.call(ConnectRequest::Tunnel(head, addr)).await
}
}
})
}
}
fn body_to_retry_body(body: &Body) -> Body {
match body {
Body::Empty => Body::Empty,
Body::Bytes(b) => Body::Bytes(b.clone()),
_ => Body::None,
}
}
#[doc(hidden)]
/// Clones [RequestHeadType] except for the extensions (not required for this middleware)
fn clone_request_head_type(head_type: &RequestHeadType) -> RequestHeadType {
match head_type {
RequestHeadType::Owned(h) => {
let mut inner_head = RequestHead::default();
inner_head.uri = h.uri.clone();
inner_head.method = h.method.clone();
inner_head.version = h.version;
inner_head.peer_addr = h.peer_addr;
inner_head.headers = h.headers.clone();
RequestHeadType::Owned(inner_head)
}
RequestHeadType::Rc(h, header_map) => {
RequestHeadType::Rc(h.clone(), header_map.clone())
}
}
}
#[doc(hidden)]
/// Clones [RequestHeadType] except for the extensions (not required for this middleware)
fn clone_request_head(head: &RequestHead) -> RequestHead {
let mut new_head = RequestHead::default();
new_head.uri = head.uri.clone();
new_head.method = head.method.clone();
new_head.version = head.version;
new_head.headers = head.headers.clone();
new_head.peer_addr = head.peer_addr;
new_head
}
#[doc(hidden)]
/// Checks whether the response matches the policies
fn is_valid_response(
policies: &[RetryPolicy],
status_code: StatusCode,
headers: &HeaderMap,
) -> bool {
policies.iter().all(|policy| {
match policy {
RetryPolicy::Status(v) => {
// is valid if:
// - the list of status codes is empty
// or
// - the list doesn't contain the received status code
v.is_empty() || !v.contains(&status_code)
}
RetryPolicy::Custom(func) => {
// custom policy
(func.deref())(status_code, headers)
}
}
})
}
#[cfg(test)]
mod tests {
use actix_web::{web, App, Error, HttpResponse};
use super::*;
use crate::ClientBuilder;
#[actix_rt::test]
async fn test_basic_policy() {
let client = ClientBuilder::new()
.disable_redirects()
.wrap(Retry::new(1).policy(vec![StatusCode::INTERNAL_SERVER_ERROR]))
.finish();
let srv = actix_test::start(|| {
App::new().service(web::resource("/test").route(web::to(|| async {
Ok::<_, Error>(HttpResponse::InternalServerError().finish())
})))
});
let res = client.get(srv.url("/test")).send().await.unwrap();
assert_eq!(res.status().as_u16(), 500);
}
#[actix_rt::test]
async fn test_header_policy() {
let client = ClientBuilder::new()
.disable_redirects()
.wrap(
Retry::new(2).policy(|code: StatusCode, headers: &HeaderMap| {
code.is_success() && headers.contains_key("SOME_HEADER")
}),
)
.finish();
let srv = actix_test::start(|| {
App::new().service(web::resource("/test").route(web::to(|| async {
Ok::<_, Error>(
HttpResponse::Ok()
.insert_header(("SOME_HEADER", "test"))
.finish(),
)
})))
});
let res = client.get(srv.url("/test")).send().await.unwrap();
assert_eq!(res.status().as_u16(), 200);
}
#[actix_rt::test]
async fn test_bad_header_policy() {
let client = ClientBuilder::new()
.disable_redirects()
.wrap(
Retry::new(3).policy(|code: StatusCode, headers: &HeaderMap| {
code.is_success() && headers.contains_key("WRONG_HEADER")
}),
)
.finish();
let srv = actix_test::start(|| {
App::new().service(web::resource("/test").route(web::to(|| async {
Ok::<_, Error>(
HttpResponse::Ok()
.insert_header(("SOME_HEADER", "test"))
.finish(),
)
})))
});
let res = client.get(srv.url("/test")).send().await.unwrap();
assert_eq!(res.status().as_u16(), 200);
}
}