Compare commits

...

18 Commits

Author SHA1 Message Date
joshbenaron d0f37b6eba
Merge df3bf79873 into 2196aeac0a 2026-06-01 06:26:42 +08:00
Yuki Okushi 2196aeac0a
fix(files): fix panic in `Files` containing `.` (#4083) 2026-05-28 07:33:25 +01:00
dependabot[bot] 0d6b4a0c52
build(deps): bump serde_json from 1.0.149 to 1.0.150 (#4080)
Bumps [serde_json](https://github.com/serde-rs/json) from 1.0.149 to 1.0.150.
- [Release notes](https://github.com/serde-rs/json/releases)
- [Commits](https://github.com/serde-rs/json/compare/v1.0.149...v1.0.150)

---
updated-dependencies:
- dependency-name: serde_json
  dependency-version: 1.0.150
  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-05-27 12:07:09 +00:00
dependabot[bot] ab80ff75de
build(deps): bump EmbarkStudios/cargo-deny-action from 2.0.18 to 2.0.19 (#4079)
Bumps [EmbarkStudios/cargo-deny-action](https://github.com/embarkstudios/cargo-deny-action) from 2.0.18 to 2.0.19.
- [Release notes](https://github.com/embarkstudios/cargo-deny-action/releases)
- [Commits](6c8f9facfa...a531616d8c)

---
updated-dependencies:
- dependency-name: EmbarkStudios/cargo-deny-action
  dependency-version: 2.0.19
  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-05-27 12:07:05 +00:00
dependabot[bot] 9a7c961949
build(deps): bump taiki-e/install-action from 2.79.0 to 2.79.7 (#4081)
Bumps [taiki-e/install-action](https://github.com/taiki-e/install-action) from 2.79.0 to 2.79.7.
- [Release notes](https://github.com/taiki-e/install-action/releases)
- [Changelog](https://github.com/taiki-e/install-action/blob/main/CHANGELOG.md)
- [Commits](7be9fd86bd...d9be7d8cda)

---
updated-dependencies:
- dependency-name: taiki-e/install-action
  dependency-version: 2.79.7
  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-05-27 10:00:28 +00:00
dependabot[bot] 15743c4010
build(deps): bump codecov/codecov-action from 6.0.0 to 6.0.1 (#4078)
Bumps [codecov/codecov-action](https://github.com/codecov/codecov-action) from 6.0.0 to 6.0.1.
- [Release notes](https://github.com/codecov/codecov-action/releases)
- [Changelog](https://github.com/codecov/codecov-action/blob/main/CHANGELOG.md)
- [Commits](57e3a136b7...e79a6962e0)

---
updated-dependencies:
- dependency-name: codecov/codecov-action
  dependency-version: 6.0.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>
2026-05-27 10:00:10 +00:00
dependabot[bot] 263fde9648
build(deps): bump zizmorcore/zizmor-action from 0.5.3 to 0.5.6 (#4073)
Bumps [zizmorcore/zizmor-action](https://github.com/zizmorcore/zizmor-action) from 0.5.3 to 0.5.6.
- [Release notes](https://github.com/zizmorcore/zizmor-action/releases)
- [Commits](b1d7e1fb5d...5f14fd08f7)

---
updated-dependencies:
- dependency-name: zizmorcore/zizmor-action
  dependency-version: 0.5.6
  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-05-20 10:16:44 +00:00
dependabot[bot] 52136f16d5
build(deps): bump openssl from 0.10.79 to 0.10.80 (#4076)
Bumps [openssl](https://github.com/rust-openssl/rust-openssl) from 0.10.79 to 0.10.80.
- [Release notes](https://github.com/rust-openssl/rust-openssl/releases)
- [Commits](https://github.com/rust-openssl/rust-openssl/compare/openssl-v0.10.79...openssl-v0.10.80)

---
updated-dependencies:
- dependency-name: openssl
  dependency-version: 0.10.80
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-05-20 10:16:39 +00:00
dependabot[bot] 955ada1b84
build(deps): bump EmbarkStudios/cargo-deny-action from 2.0.17 to 2.0.18 (#4074)
Bumps [EmbarkStudios/cargo-deny-action](https://github.com/embarkstudios/cargo-deny-action) from 2.0.17 to 2.0.18.
- [Release notes](https://github.com/embarkstudios/cargo-deny-action/releases)
- [Commits](91bf2b620e...6c8f9facfa)

---
updated-dependencies:
- dependency-name: EmbarkStudios/cargo-deny-action
  dependency-version: 2.0.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-05-20 09:30:50 +00:00
dependabot[bot] 9449a9666c
build(deps): bump filetime from 0.2.28 to 0.2.29 (#4071)
Bumps [filetime](https://github.com/alexcrichton/filetime) from 0.2.28 to 0.2.29.
- [Commits](https://github.com/alexcrichton/filetime/compare/0.2.28...0.2.29)

---
updated-dependencies:
- dependency-name: filetime
  dependency-version: 0.2.29
  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-05-20 09:27:00 +00:00
dependabot[bot] 2409270803
build(deps): bump taiki-e/install-action from 2.77.4 to 2.79.0 (#4072)
Bumps [taiki-e/install-action](https://github.com/taiki-e/install-action) from 2.77.4 to 2.79.0.
- [Release notes](https://github.com/taiki-e/install-action/releases)
- [Changelog](https://github.com/taiki-e/install-action/blob/main/CHANGELOG.md)
- [Commits](ec28e28791...7be9fd86bd)

---
updated-dependencies:
- dependency-name: taiki-e/install-action
  dependency-version: 2.79.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-05-20 09:22:29 +00:00
tatakaisun 24e5c77d2b
docs: fix API documentation label in README (#4075) 2026-05-20 09:20:59 +01: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
12 changed files with 394 additions and 20 deletions

View File

@ -51,7 +51,7 @@ jobs:
toolchain: ${{ matrix.version.version }}
- name: Install just, cargo-hack, cargo-nextest, cargo-ci-cache-clean
uses: taiki-e/install-action@ec28e287910af896fd98e04056d31fa68607e7ad # v2.77.4
uses: taiki-e/install-action@d9be7d8cda89035c9c843f78bd44d4f72d8403d4 # v2.79.7
with:
tool: just,cargo-hack,cargo-nextest,cargo-ci-cache-clean
@ -87,7 +87,7 @@ jobs:
uses: actions-rust-lang/setup-rust-toolchain@46268bd060767258de96ed93c1251119784f2ab6 # v1.16.1
- name: Install just, cargo-hack
uses: taiki-e/install-action@ec28e287910af896fd98e04056d31fa68607e7ad # v2.77.4
uses: taiki-e/install-action@d9be7d8cda89035c9c843f78bd44d4f72d8403d4 # v2.79.7
with:
tool: just,cargo-hack

View File

@ -66,7 +66,7 @@ jobs:
toolchain: ${{ matrix.version.version }}
- name: Install just, cargo-hack, cargo-nextest, cargo-ci-cache-clean
uses: taiki-e/install-action@ec28e287910af896fd98e04056d31fa68607e7ad # v2.77.4
uses: taiki-e/install-action@d9be7d8cda89035c9c843f78bd44d4f72d8403d4 # v2.79.7
with:
tool: just,cargo-hack,cargo-nextest,cargo-ci-cache-clean
@ -89,7 +89,7 @@ jobs:
- name: deny check
if: matrix.version.name == 'stable' && matrix.target.os == 'ubuntu-latest'
uses: EmbarkStudios/cargo-deny-action@91bf2b620e09e18d6eb78b92e7861937469acedb # v2.0.17
uses: EmbarkStudios/cargo-deny-action@a531616d8ce3b9177443e48a1159bc945a099823 # v2.0.19
io-uring:
name: io-uring tests
@ -123,7 +123,7 @@ jobs:
toolchain: nightly
- name: Install just
uses: taiki-e/install-action@ec28e287910af896fd98e04056d31fa68607e7ad # v2.77.4
uses: taiki-e/install-action@d9be7d8cda89035c9c843f78bd44d4f72d8403d4 # v2.79.7
with:
tool: just

View File

@ -26,7 +26,7 @@ jobs:
components: llvm-tools
- name: Install just, cargo-llvm-cov, cargo-nextest
uses: taiki-e/install-action@ec28e287910af896fd98e04056d31fa68607e7ad # v2.77.4
uses: taiki-e/install-action@d9be7d8cda89035c9c843f78bd44d4f72d8403d4 # v2.79.7
with:
tool: just,cargo-llvm-cov,cargo-nextest
@ -34,7 +34,7 @@ jobs:
run: just test-coverage-codecov
- name: Upload coverage to Codecov
uses: codecov/codecov-action@57e3a136b779b570ffcdbf80b3bdc90e7fab3de2 # v6.0.0
uses: codecov/codecov-action@e79a6962e0d4c0c17b229090214935d2e33f8354 # v6.0.1
with:
files: codecov.json
fail_ci_if_error: true

View File

@ -24,7 +24,7 @@ jobs:
with:
persist-credentials: false
- uses: zizmorcore/zizmor-action@b1d7e1fb5de872772f31590499237e7cce841e8e # v0.5.3
- uses: zizmorcore/zizmor-action@5f14fd08f7cf1cb1609c1e344975f152c7ee938d # v0.5.6
with:
advanced-security: false
annotations: true
@ -103,7 +103,7 @@ jobs:
toolchain: ${{ vars.RUST_VERSION_EXTERNAL_TYPES }}
- name: Install just
uses: taiki-e/install-action@ec28e287910af896fd98e04056d31fa68607e7ad # v2.77.4
uses: taiki-e/install-action@d9be7d8cda89035c9c843f78bd44d4f72d8403d4 # v2.79.7
with:
tool: just

View File

@ -21,7 +21,7 @@ jobs:
toolchain: stable
- name: Install cargo-semver-checks
uses: taiki-e/install-action@ec28e287910af896fd98e04056d31fa68607e7ad # v2.77.4
uses: taiki-e/install-action@d9be7d8cda89035c9c843f78bd44d4f72d8403d4 # v2.79.7
with:
tool: cargo-semver-checks

16
Cargo.lock generated
View File

@ -1298,9 +1298,9 @@ checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6"
[[package]]
name = "filetime"
version = "0.2.28"
version = "0.2.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d5b2eef6fafbf69f877e55509ce5b11a760690ac9700a2921be067aa6afaef6"
checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759"
dependencies = [
"cfg-if",
"libc",
@ -2208,9 +2208,9 @@ checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
[[package]]
name = "openssl"
version = "0.10.79"
version = "0.10.80"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf0b434746ee2832f4f0baf10137e1cabb18cbe6912c69e2e33263c45250f542"
checksum = "a45fa2aa886c42762255da344f0a0d313e254066c46aad76f300c3d3da62d967"
dependencies = [
"bitflags 2.11.1",
"cfg-if",
@ -2239,9 +2239,9 @@ checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
[[package]]
name = "openssl-sys"
version = "0.9.115"
version = "0.9.116"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "158fe5b292746440aa6e7a7e690e55aeb72d41505e2804c23c6973ad0e9c9781"
checksum = "f28a22dc7140cda5f096e5e7724a6962ca81a7f8bfd2979f9b18c11af56318c4"
dependencies = [
"cc",
"libc",
@ -2861,9 +2861,9 @@ dependencies = [
[[package]]
name = "serde_json"
version = "1.0.149"
version = "1.0.150"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9"
dependencies = [
"itoa",
"memchr",

View File

@ -5,6 +5,7 @@
- Add support for passing multiple root directories to `Files::new`. [#3402]
- Add `Files::try_compressed()` to support serving pre-compressed static files [#2615]
- Fix handling of `bytes=0-`
- Fix panic in `Files` when `use_hidden_files()` is enabled and request paths contain `.` segments. [#4082]
- Fix `NamedFile` panic when serving files with pre-UNIX epoch modification times. [#2748]
- Fix invalid `Content-Encoding: identity` header in `NamedFile` range responses. [#3191]
- Update `v_htmlescape` dependency to `0.17`.
@ -13,6 +14,7 @@
[#2615]: https://github.com/actix/actix-web/pull/2615
[#2748]: https://github.com/actix/actix-web/issues/2748
[#3191]: https://github.com/actix/actix-web/issues/3191
[#4082]: https://github.com/actix/actix-web/issues/4082
## 0.6.10

View File

@ -1094,6 +1094,21 @@ mod tests {
assert_eq!(bytes, web::Bytes::from_static(b"default content"));
}
#[actix_rt::test]
async fn test_hidden_files_reject_cur_dir_segment() {
let service = Files::new("/", Vec::<PathBuf>::new())
.use_hidden_files()
.default_handler(Files::new("/", ".").use_hidden_files())
.new_service(())
.await
.unwrap();
let req = TestRequest::with_uri("/./Cargo.toml").to_srv_request();
let resp = test::call_service(&service, req).await;
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[actix_rt::test]
async fn test_serve_index_nested() {
let service = Files::new(".", ".")

View File

@ -78,7 +78,9 @@ impl PathBufWrap {
}
for segment in path.split('/') {
if segment == ".." {
if segment == "." {
return Err(UriSegmentError::BadStart('.'));
} else if segment == ".." {
segment_count -= 1;
buf.pop();
} else if !hidden_files && segment.starts_with('.') {
@ -180,6 +182,11 @@ mod tests {
PathBufWrap::parse_path("/test/.tt", true).unwrap().0,
PathBuf::from_iter(vec!["test", ".tt"])
);
assert_eq!(
PathBufWrap::parse_path("/test/./file.txt", true).map(|t| t.0),
Err(UriSegmentError::BadStart('.'))
);
}
#[test]

View File

@ -54,7 +54,7 @@ Please use them in a production environment at your own risk.
- [Website & User Guide](https://actix.rs)
- [Examples Repository](https://github.com/actix/examples)
- [API Documentation](https://docs.rs/actix-web)
- [API Documentation (mainranch)](https://actix.rs/actix-web/actix_web)
- [API Documentation (main branch)](https://actix.rs/actix-web/actix_web)
## Example

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);
}
}