retry-policies-0.5.1/.cargo_vcs_info.json0000644000000001360000000000100140110ustar { "git": { "sha1": "a2592b85e8a5aaa73b7322a29ebd5b939dd9d14b" }, "path_in_vcs": "" }retry-policies-0.5.1/.github/CODEOWNERS000064400000000000000000000000261046102023000155320ustar 00000000000000* @TrueLayer/rust-oss retry-policies-0.5.1/.github/ISSUE_TEMPLATE/bug_report.md000064400000000000000000000010311046102023000210110ustar 00000000000000--- name: Bug report about: Create a report to help us improve title: '' labels: bug assignees: '' --- ## Bug description ## To Reproduce ## Expected behavior ## Environment - OS: [e.g. Windows] - Rust version [e.g. 1.51.0] ## Additional context retry-policies-0.5.1/.github/ISSUE_TEMPLATE/config.yml000064400000000000000000000000331046102023000203100ustar 00000000000000blank_issues_enabled: true retry-policies-0.5.1/.github/ISSUE_TEMPLATE/feature_request.md000064400000000000000000000007441046102023000220560ustar 00000000000000--- name: Feature request about: Suggest an idea for this project title: '' labels: enhancement assignees: '' --- ## Motivations ## Solution ## Alternatives ## Additional context retry-policies-0.5.1/.github/PULL_REQUEST_TEMPLATE.md000064400000000000000000000007331046102023000177450ustar 00000000000000 retry-policies-0.5.1/.github/workflows/audit.yml000064400000000000000000000006201046102023000200250ustar 00000000000000name: Security audit on: schedule: # Runs at 00:00 UTC everyday - cron: '0 0 * * *' push: paths: - '**/Cargo.toml' - '**/Cargo.lock' pull_request: jobs: audit: runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v2 - uses: actions-rs/audit-check@v1 with: token: ${{ secrets.GITHUB_TOKEN }} retry-policies-0.5.1/.github/workflows/ci.yml000064400000000000000000000045061046102023000173210ustar 00000000000000on: push: branches: [main] pull_request: name: CI # Continuous Integration jobs: test: name: Test Suite runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v2 - name: Install Rust uses: actions-rs/toolchain@v1 with: toolchain: stable profile: minimal override: true - uses: actions-rs/cargo@v1 with: command: test args: --workspace --all-targets --all-features rustfmt: name: Rustfmt runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v2 - name: Install Rust uses: actions-rs/toolchain@v1 with: toolchain: stable profile: minimal override: true components: rustfmt - name: Check formatting uses: actions-rs/cargo@v1 with: command: fmt args: --all -- --check clippy: name: Clippy runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v2 - name: Install Rust uses: actions-rs/toolchain@v1 with: toolchain: stable profile: minimal override: true components: clippy - name: Clippy check uses: actions-rs/cargo@v1 with: command: clippy args: --all-targets --all-features --workspace -- -D warnings docs: name: Docs runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v2 - name: Install Rust uses: actions-rs/toolchain@v1 with: toolchain: stable profile: minimal override: true - name: Check documentation env: RUSTDOCFLAGS: -D warnings uses: actions-rs/cargo@v1 with: command: doc args: --no-deps --document-private-items --all-features --workspace publish-check: name: Publish dry run runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: toolchain: stable profile: minimal override: true - uses: actions-rs/cargo@v1 with: command: publish args: --dry-run retry-policies-0.5.1/.github/workflows/release-plz.yml000064400000000000000000000011221046102023000211400ustar 00000000000000name: Release-plz permissions: pull-requests: write contents: write on: push: branches: - main jobs: release-plz: name: Release-plz runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v4 with: fetch-depth: 0 - name: Install Rust toolchain uses: dtolnay/rust-toolchain@stable - name: Run release-plz uses: MarcoIeni/release-plz-action@v0.5 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} retry-policies-0.5.1/.gitignore000064400000000000000000000000231046102023000145640ustar 00000000000000/target Cargo.lock retry-policies-0.5.1/CHANGELOG.md000064400000000000000000000047301046102023000144160ustar 00000000000000# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] ## [0.5.1](https://github.com/TrueLayer/retry-policies/compare/v0.5.0...v0.5.1) - 2025-05-14 ### Changed - Improved bounded jitter to use 50% of `min_retry_interval` instead of 100%. ## [0.5.0](https://github.com/TrueLayer/retry-policies/compare/v0.4.0...v0.5.0) - 2025-05-14 ### Changed - [Breaking] Renamed `build_with_total_retry_duration_and_max_retries` to `build_with_total_retry_duration_and_limit_retries`. ### Added - Added `build_with_total_retry_duration_and_max_retries`. ## [0.4.0](https://github.com/TrueLayer/retry-policies/compare/v0.3.0...v0.4.0) - 2024-05-10 ### Changed - [Breaking] Replace `chrono` with standard library types - Replace `chrono::DateTime` with `std::time::SystemTime` ### Removed - Remove unused `anyhow` dependency - Remove `fake` dependency ## [0.3.0] - 2024-03-04 - [Breaking] Implement `RetryPolicy` for `ExponentialBackoffTimed`, which requires a modification to the `should_retry` method of `RetryPolicy` in order to pass the time at which the task (original request) was started. ## [0.2.1] - 2023-10-09 ### Added - Total duration algorithm can now be configured to also consider max retries, calculated applying no jitter (1.0) - We enforce whatever comes first, total duration or max retries - Exponential base is now configurable ## [0.2.0] - 2023-07-21 ### Changed - [Breaking] Change backoff and jitter algorithms - Change the backoff algorithm to a more conventional exponential backoff. - Replace the decorrelated jitter algorithm with an option of either none, full, or bounded. Defaults to full jitter. - [Breaking] Remove `ExponentialBackoffBuilder::backoff_exponent()` - The number of attempts is now used as the exponent. - [Breaking] Require a task start time when using a total retry duration - `ExponentialBackoffBuilder::build_with_total_retry_duration()` now returns `ExponentialBackoffTimed` which does not implement `RetryPolicy`. - [Breaking] Mark `ExponentialBackoff` as `non_exhaustive` - Can no longer be constructed directly. ## [0.1.2] - 2022-10-28 ### Added - `Debug` derived for `RetryDecision` ## [0.1.1] - 2021-10-18 ### Security - remove time v0.1 dependency ## [0.1.0] - 2021-08-11 ### Added - `ExponentialBackoff` policy. retry-policies-0.5.1/CODE_OF_CONDUCT.md000064400000000000000000000002121046102023000153730ustar 00000000000000# Code of Conduct This project adheres to the Rust Code of Conduct, which [can be found online](https://www.rust-lang.org/conduct.html). retry-policies-0.5.1/CONTRIBUTING.md000064400000000000000000000031111046102023000150260ustar 00000000000000# Contribution guidelines First off, thank you for considering contributing to retry-policies. If your contribution is not straightforward, please first discuss the change you wish to make by creating a new issue before making the change. ## Reporting issues Before reporting an issue on the [issue tracker](https://github.com/TrueLayer/retry-policies/issues), please check that it has not already been reported by searching for some related keywords. ## Pull requests Try to do one pull request per change. ### Updating the changelog Update the changes you have made in [CHANGELOG](https://github.com/TrueLayer/retry-policies/blob/master/CHANGELOG.md) file under the **Unreleased** section. Add the changes of your pull request to one of the following subsections, depending on the types of changes defined by [Keep a changelog](https://keepachangelog.com/en/1.0.0/): - `Added` for new features. - `Changed` for changes in existing functionality. - `Deprecated` for soon-to-be removed features. - `Removed` for now removed features. - `Fixed` for any bug fixes. - `Security` in case of vulnerabilities. If the required subsection does not exist yet under **Unreleased**, create it! ## Developing ### Set up This is no different than other Rust projects. ```shell git clone https://github.com/TrueLayer/retry-policies cd rust-retry-policies cargo test ``` ### Useful Commands - Run Clippy: ```shell cargo clippy ``` - Check to see if there are code formatting issues ```shell cargo fmt --all -- --check ``` - Format the code in the project ```shell cargo fmt --all ``` retry-policies-0.5.1/Cargo.lock0000644000000076310000000000100117730ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 4 [[package]] name = "bitflags" version = "2.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b8e56985ec62d17e9c1001dc89c88ecd7dc08e47eba5ec7c29c7b5eeecde967" [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "getrandom" version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4" dependencies = [ "cfg-if", "libc", "r-efi", "wasi", ] [[package]] name = "libc" version = "0.2.172" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d750af042f7ef4f724306de029d18836c26c1765a54a6a3f094cbd23a7267ffa" [[package]] name = "ppv-lite86" version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" dependencies = [ "zerocopy", ] [[package]] name = "proc-macro2" version = "1.0.95" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.40" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" dependencies = [ "proc-macro2", ] [[package]] name = "r-efi" version = "5.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "74765f6d916ee2faa39bc8e68e4f3ed8949b48cccdac59983d287a7cb71ce9c5" [[package]] name = "rand" version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9fbfd9d094a40bf3ae768db9361049ace4c0e04a4fd6b359518bd7b73a73dd97" dependencies = [ "rand_chacha", "rand_core", ] [[package]] name = "rand_chacha" version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" dependencies = [ "ppv-lite86", "rand_core", ] [[package]] name = "rand_core" version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38" dependencies = [ "getrandom", ] [[package]] name = "retry-policies" version = "0.5.1" dependencies = [ "rand", ] [[package]] name = "syn" version = "2.0.101" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ce2b7fc941b3a24138a0a7cf8e858bfc6a992e7978a068a5c760deb0ed43caf" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "unicode-ident" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512" [[package]] name = "wasi" version = "0.14.2+wasi-0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9683f9a5a998d873c0d21fcbe3c083009670149a8fab228644b8bd36b2c48cb3" dependencies = [ "wit-bindgen-rt", ] [[package]] name = "wit-bindgen-rt" version = "0.39.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6f42320e61fe2cfd34354ecb597f86f413484a798ba44a8ca1165c58d42da6c1" dependencies = [ "bitflags", ] [[package]] name = "zerocopy" version = "0.8.25" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a1702d9583232ddb9174e01bb7c15a2ab8fb1bc6f227aa1233858c351a3ba0cb" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" version = "0.8.25" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28a6e20d751156648aa063f3800b706ee209a32c0b4d9f24be3d980b01be55ef" dependencies = [ "proc-macro2", "quote", "syn", ] retry-policies-0.5.1/Cargo.toml0000644000000020560000000000100120120ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "retry-policies" version = "0.5.1" authors = ["Luca Palmieri "] build = false autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "A collection of plug-and-play retry policies for Rust projects." readme = "README.md" keywords = [ "retry", "policy", "backoff", ] categories = ["network-programming"] license = "MIT OR Apache-2.0" repository = "https://github.com/TrueLayer/retry-policies" [lib] name = "retry_policies" path = "src/lib.rs" [dependencies.rand] version = "0.9.1" retry-policies-0.5.1/Cargo.toml.orig000064400000000000000000000006221046102023000154700ustar 00000000000000[package] name = "retry-policies" version = "0.5.1" authors = ["Luca Palmieri "] edition = "2018" description = "A collection of plug-and-play retry policies for Rust projects." repository = "https://github.com/TrueLayer/retry-policies" license = "MIT OR Apache-2.0" keywords = ["retry", "policy", "backoff"] categories = ["network-programming"] [dependencies] rand = "0.9.1" retry-policies-0.5.1/LICENSE-APACHE000064400000000000000000000227731046102023000145400ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS retry-policies-0.5.1/LICENSE-MIT000064400000000000000000000020521046102023000142340ustar 00000000000000MIT License Copyright (c) 2021 TrueLayer Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. retry-policies-0.5.1/README.md000064400000000000000000000025051046102023000140620ustar 00000000000000# retry-policies A collection of plug-and-play retry policies for Rust projects. [![Crates.io](https://img.shields.io/crates/v/retry-policies.svg)](https://crates.io/crates/retry-policies) [![Docs.rs](https://docs.rs/retry-policies/badge.svg)](https://docs.rs/retry-policies) [![CI](https://github.com/TrueLayer/retry-policies/workflows/CI/badge.svg)](https://github.com/TrueLayer/retry-policies/actions) [![Coverage Status](https://coveralls.io/repos/github/TrueLayer/rust-retry-policies/badge.svg?branch=main&t=d56f4Y)](https://coveralls.io/github/TrueLayer/rust-retry-policies?branch=main) Currently available algorithms: - [`ExponentialBackoff`](https://docs.rs/retry-policies/latest/retry_policies/policies/struct.ExponentialBackoff.html), with configurable jitter. ## How to install Add `retry-policies` to your dependencies ```toml [dependencies] # ... retry-policies = "0.4.0" ``` ## License Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. retry-policies-0.5.1/src/lib.rs000064400000000000000000000002231046102023000145010ustar 00000000000000//! A collection of plug-and-play retry policies. pub mod policies; mod retry_policy; pub use retry_policy::{Jitter, RetryDecision, RetryPolicy}; retry-policies-0.5.1/src/policies/exponential_backoff.rs000064400000000000000000000465631046102023000215640ustar 00000000000000use crate::{Jitter, RetryDecision, RetryPolicy}; use std::{ cmp::{self, min}, time::{Duration, SystemTime}, }; /// Exponential backoff with optional jitter. #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[non_exhaustive] pub struct ExponentialBackoff { /// Maximum number of allowed retries attempts. pub max_n_retries: Option, /// Minimum waiting time between two retry attempts (it can end up being lower due to jitter). pub min_retry_interval: Duration, /// Maximum waiting time between two retry attempts. pub max_retry_interval: Duration, /// How we apply jitter to the calculated backoff intervals. pub jitter: Jitter, /// Base of the exponential pub base: u32, } /// Exponential backoff with a maximum retry duration. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct ExponentialBackoffTimed { /// Maximum duration the retries can continue for, after which retries will stop. max_total_retry_duration: Duration, backoff: ExponentialBackoff, } /// Builds an exponential backoff policy. /// /// # Example /// /// ```rust /// use retry_policies::{RetryDecision, RetryPolicy, Jitter}; /// use retry_policies::policies::ExponentialBackoff; /// use std::time::Duration; /// /// let backoff = ExponentialBackoff::builder() /// .retry_bounds(Duration::from_secs(1), Duration::from_secs(60)) /// .jitter(Jitter::Bounded) /// .base(2) /// .build_with_total_retry_duration(Duration::from_secs(24 * 60 * 60)); /// ``` pub struct ExponentialBackoffBuilder { min_retry_interval: Duration, max_retry_interval: Duration, jitter: Jitter, base: u32, } impl ExponentialBackoff { /// Returns a builder. /// /// # Example /// ``` /// use retry_policies::policies::ExponentialBackoff; /// use std::time::Duration; /// /// let backoff = ExponentialBackoff::builder() /// .build_with_max_retries(5); /// /// assert_eq!(backoff.min_retry_interval, Duration::from_secs(1)); /// assert_eq!(backoff.max_retry_interval, Duration::from_secs(30 * 60)); /// assert_eq!(backoff.max_n_retries, Some(5)); /// assert_eq!(backoff.base, 2); /// ``` pub fn builder() -> ExponentialBackoffBuilder { <_>::default() } fn too_many_attempts(&self, n_past_retries: u32) -> bool { self.max_n_retries .is_some_and(|max_n| max_n <= n_past_retries) } } impl RetryPolicy for ExponentialBackoff { fn should_retry(&self, _request_start_time: SystemTime, n_past_retries: u32) -> RetryDecision { if self.too_many_attempts(n_past_retries) { RetryDecision::DoNotRetry } else { let unjittered_wait_for = min( self.max_retry_interval, self.min_retry_interval * calculate_exponential(self.base, n_past_retries), ); let jittered_wait_for = self.jitter.apply( unjittered_wait_for, self.min_retry_interval, &mut rand::rng(), ); let execute_after = SystemTime::now() + clip(jittered_wait_for, self.max_retry_interval); RetryDecision::Retry { execute_after } } } } /// Clip to the maximum allowed retry interval. fn clip(duration: Duration, max_duration: Duration) -> Duration { cmp::min(duration, max_duration) } /// Calculate exponential using base and number of past retries fn calculate_exponential(base: u32, n_past_retries: u32) -> u32 { base.checked_pow(n_past_retries).unwrap_or(u32::MAX) } impl ExponentialBackoffTimed { /// Maximum number of allowed retries attempts. pub fn max_retries(&self) -> Option { self.backoff.max_n_retries } fn trying_for_too_long(&self, started_at: SystemTime) -> bool { self.max_total_retry_duration <= Self::elapsed(started_at) } fn elapsed(started_at: SystemTime) -> Duration { SystemTime::now() .duration_since(started_at) // If `started_at` is in the future then return a zero duration. .unwrap_or_default() } } impl Default for ExponentialBackoffBuilder { fn default() -> Self { Self { min_retry_interval: Duration::from_secs(1), max_retry_interval: Duration::from_secs(30 * 60), jitter: Jitter::Full, base: 2, } } } impl RetryPolicy for ExponentialBackoffTimed { fn should_retry(&self, request_start_time: SystemTime, n_past_retries: u32) -> RetryDecision { if self.trying_for_too_long(request_start_time) { return RetryDecision::DoNotRetry; } self.backoff .should_retry(request_start_time, n_past_retries) } } impl ExponentialBackoffBuilder { /// Add min & max retry interval bounds. _Default [1s, 30m]_. /// /// See [`ExponentialBackoff::min_retry_interval`], [`ExponentialBackoff::max_retry_interval`]. /// /// Panics if `min_retry_interval` > `max_retry_interval`. pub fn retry_bounds( mut self, min_retry_interval: Duration, max_retry_interval: Duration, ) -> Self { assert!( min_retry_interval <= max_retry_interval, "The maximum interval between retries should be greater or equal than the minimum retry interval." ); self.min_retry_interval = min_retry_interval; self.max_retry_interval = max_retry_interval; self } /// Set what type of jitter to apply. pub fn jitter(mut self, jitter: Jitter) -> Self { self.jitter = jitter; self } /// Set what base to use for the exponential. pub fn base(mut self, base: u32) -> Self { self.base = base; self } /// Builds an [`ExponentialBackoff`] with the given maximum retries. /// /// See [`ExponentialBackoff::max_n_retries`]. pub fn build_with_max_retries(self, n: u32) -> ExponentialBackoff { ExponentialBackoff { min_retry_interval: self.min_retry_interval, max_retry_interval: self.max_retry_interval, max_n_retries: Some(n), jitter: self.jitter, base: self.base, } } /// Builds an [`ExponentialBackoff`] with the given maximum total duration for which retries will /// continue to be performed. /// /// # Example /// /// ```rust /// use retry_policies::{RetryDecision, RetryPolicy}; /// use retry_policies::policies::ExponentialBackoff; /// use std::time::{Duration, SystemTime}; /// /// let backoff = ExponentialBackoff::builder() /// .build_with_total_retry_duration(Duration::from_secs(24 * 60 * 60)); /// /// let started_at = SystemTime::now() /// .checked_sub(Duration::from_secs(25 * 60 * 60)) /// .unwrap(); /// /// let should_retry = backoff.should_retry(started_at, 0); /// assert!(matches!(RetryDecision::DoNotRetry, should_retry)); /// ``` pub fn build_with_total_retry_duration( self, total_duration: Duration, ) -> ExponentialBackoffTimed { ExponentialBackoffTimed { max_total_retry_duration: total_duration, backoff: ExponentialBackoff { min_retry_interval: self.min_retry_interval, max_retry_interval: self.max_retry_interval, max_n_retries: None, jitter: self.jitter, base: self.base, }, } } /// Builds an [`ExponentialBackoffTimed`] with the given maximum total duration and limits the /// number of retries to a calculated maximum. /// /// This calculated maximum is based on how many attempts would be made without jitter applied. /// /// For example if we set total duration 24 hours, with retry bounds [1s, 24h] and 2 as base of /// the exponential, we would calculate 17 max retries, as 1s * pow(2, 16) = 65536s = ~18 hours /// and 18th attempt would be way after the 24 hours total duration. /// /// If the 17th retry ends up being scheduled after 10 hours due to jitter, /// [`ExponentialBackoff::should_retry`] will return false anyway: no retry will be allowed /// after total duration. /// /// If one of the 17 allowed retries for some reason (e.g. previous attempts taking a long time) /// ends up being scheduled after total duration, [`ExponentialBackoff::should_retry`] will /// return false. /// /// Basically we will enforce whatever comes first, max retries or total duration. /// /// # Example /// /// ```rust /// use retry_policies::{RetryDecision, RetryPolicy}; /// use retry_policies::policies::ExponentialBackoff; /// use std::time::{Duration, SystemTime}; /// /// let exponential_backoff_timed = ExponentialBackoff::builder() /// .retry_bounds(Duration::from_secs(1), Duration::from_secs(6 * 60 * 60)) /// .build_with_total_retry_duration_and_limit_retries(Duration::from_secs(24 * 60 * 60)); /// /// assert_eq!(exponential_backoff_timed.max_retries(), Some(17)); /// /// let started_at = SystemTime::now() /// .checked_sub(Duration::from_secs(25 * 60 * 60)) /// .unwrap(); /// /// let should_retry = exponential_backoff_timed.should_retry(started_at, 0); /// assert!(matches!(RetryDecision::DoNotRetry, should_retry)); /// /// let started_at = SystemTime::now() /// .checked_sub(Duration::from_secs(1 * 60 * 60)) /// .unwrap(); /// /// let should_retry = exponential_backoff_timed.should_retry(started_at, 18); /// assert!(matches!(RetryDecision::DoNotRetry, should_retry)); /// /// ``` pub fn build_with_total_retry_duration_and_limit_retries( self, total_duration: Duration, ) -> ExponentialBackoffTimed { let mut max_n_retries = None; let delays = (0u32..).map(|n| { min( self.max_retry_interval, self.min_retry_interval * calculate_exponential(self.base, n), ) }); let mut total = Duration::from_secs(0); for (n, delay) in delays.enumerate() { total += delay; if total >= total_duration { max_n_retries = Some(n as _); break; } } ExponentialBackoffTimed { max_total_retry_duration: total_duration, backoff: ExponentialBackoff { min_retry_interval: self.min_retry_interval, max_retry_interval: self.max_retry_interval, max_n_retries, jitter: self.jitter, base: self.base, }, } } /// Builds an [`ExponentialBackoffTimed`] with the given maximum total duration and maximum retries. pub fn build_with_total_retry_duration_and_max_retries( self, total_duration: Duration, max_n_retries: u32, ) -> ExponentialBackoffTimed { ExponentialBackoffTimed { max_total_retry_duration: total_duration, backoff: ExponentialBackoff { min_retry_interval: self.min_retry_interval, max_retry_interval: self.max_retry_interval, max_n_retries: Some(max_n_retries), jitter: self.jitter, base: self.base, }, } } } #[cfg(test)] mod tests { use std::convert::TryFrom as _; use rand::distr::{Distribution, Uniform}; use super::*; fn get_retry_policy() -> ExponentialBackoff { ExponentialBackoff { max_n_retries: Some(6), min_retry_interval: Duration::from_secs(1), max_retry_interval: Duration::from_secs(5 * 60), jitter: Jitter::Full, base: 2, } } #[test] fn if_n_past_retries_is_below_maximum_it_decides_to_retry() { // Arrange let policy = get_retry_policy(); let n_past_retries = Uniform::try_from(0..policy.max_n_retries.unwrap()) .unwrap() .sample(&mut rand::rng()); assert!(n_past_retries < policy.max_n_retries.unwrap()); // Act let decision = policy.should_retry(SystemTime::now(), n_past_retries); // Assert matches!(decision, RetryDecision::Retry { .. }); } #[test] fn if_n_past_retries_is_above_maximum_it_decides_to_mark_as_failed() { // Arrange let policy = get_retry_policy(); let n_past_retries = Uniform::try_from(policy.max_n_retries.unwrap()..=u32::MAX) .unwrap() .sample(&mut rand::rng()); assert!(n_past_retries >= policy.max_n_retries.unwrap()); // Act let decision = policy.should_retry(SystemTime::now(), n_past_retries); // Assert matches!(decision, RetryDecision::DoNotRetry); } #[test] fn maximum_retry_interval_is_never_exceeded() { // Arrange let policy = get_retry_policy(); let max_interval = policy.max_retry_interval; // Act let decision = policy.should_retry(SystemTime::now(), policy.max_n_retries.unwrap() - 1); // Assert match decision { RetryDecision::Retry { execute_after } => { assert!(execute_after.duration_since(SystemTime::now()).unwrap() <= max_interval) } RetryDecision::DoNotRetry => panic!("Expected Retry decision."), } } #[test] fn overflow_backoff_exponent_does_not_cause_a_panic() { let policy = ExponentialBackoff { max_n_retries: Some(u32::MAX), ..get_retry_policy() }; let max_interval = policy.max_retry_interval; let n_failed_attempts = u32::MAX - 1; // Act let decision = policy.should_retry(SystemTime::now(), n_failed_attempts); // Assert match decision { RetryDecision::Retry { execute_after } => { assert!(execute_after.duration_since(SystemTime::now()).unwrap() <= max_interval) } RetryDecision::DoNotRetry => panic!("Expected Retry decision."), } } #[test] #[should_panic] fn builder_invalid_retry_bounds() { // bounds are the wrong way round or invalid ExponentialBackoff::builder().retry_bounds(Duration::from_secs(3), Duration::from_secs(2)); } #[test] fn does_not_retry_after_total_retry_duration() { let backoff = ExponentialBackoff::builder() .build_with_total_retry_duration(Duration::from_secs(24 * 60 * 60)); { let started_at = SystemTime::now() .checked_sub(Duration::from_secs(23 * 60 * 60)) .unwrap(); let decision = backoff.should_retry(started_at, 0); match decision { RetryDecision::Retry { .. } => {} _ => panic!("should retry"), } } { let started_at = SystemTime::now() .checked_sub(Duration::from_secs(25 * 60 * 60)) .unwrap(); let decision = backoff.should_retry(started_at, 0); match decision { RetryDecision::DoNotRetry => {} _ => panic!("should not retry"), } } } #[test] fn does_not_retry_before_total_retry_duration_if_max_retries_exceeded() { let backoff = ExponentialBackoff::builder() // This configuration should allow 17 max retries inside a 24h total duration .retry_bounds(Duration::from_secs(1), Duration::from_secs(6 * 60 * 60)) .build_with_total_retry_duration_and_limit_retries(Duration::from_secs(24 * 60 * 60)); { let started_at = SystemTime::now() .checked_sub(Duration::from_secs(23 * 60 * 60)) .unwrap(); let decision = backoff.should_retry(started_at, 0); match decision { RetryDecision::Retry { .. } => {} _ => panic!("should retry"), } } { let started_at = SystemTime::now() .checked_sub(Duration::from_secs(23 * 60 * 60)) .unwrap(); // Zero based, so this is the 18th retry let decision = backoff.should_retry(started_at, 17); match decision { RetryDecision::DoNotRetry => {} _ => panic!("should not retry"), } } { let started_at = SystemTime::now() .checked_sub(Duration::from_secs(25 * 60 * 60)) .unwrap(); let decision = backoff.should_retry(started_at, 0); match decision { RetryDecision::DoNotRetry => {} _ => panic!("should not retry"), } } } #[test] fn different_exponential_base_produce_different_max_retries_for_the_same_duration() { let backoff_base_2 = ExponentialBackoff::builder() .retry_bounds(Duration::from_secs(1), Duration::from_secs(60 * 60)) .base(2) .build_with_total_retry_duration_and_limit_retries(Duration::from_secs(60 * 60)); let backoff_base_3 = ExponentialBackoff::builder() .retry_bounds(Duration::from_secs(1), Duration::from_secs(60 * 60)) .base(3) .build_with_total_retry_duration_and_limit_retries(Duration::from_secs(60 * 60)); let backoff_base_4 = ExponentialBackoff::builder() .retry_bounds(Duration::from_secs(1), Duration::from_secs(60 * 60)) .base(4) .build_with_total_retry_duration_and_limit_retries(Duration::from_secs(60 * 60)); assert_eq!(backoff_base_2.max_retries().unwrap(), 11); assert_eq!(backoff_base_3.max_retries().unwrap(), 8); assert_eq!(backoff_base_4.max_retries().unwrap(), 6); } #[test] fn total_retry_duration_and_max_retries() { // Create backoff policy with specific duration and retry limits let backoff = ExponentialBackoff::builder() .retry_bounds(Duration::from_secs(1), Duration::from_secs(30)) .build_with_total_retry_duration_and_max_retries(Duration::from_secs(120), 5); // Verify the max retries was set correctly assert_eq!(backoff.max_retries(), Some(5)); // Test retry within limits { let started_at = SystemTime::now() .checked_sub(Duration::from_secs(60)) .unwrap(); let decision = backoff.should_retry(started_at, 3); match decision { RetryDecision::Retry { .. } => {} _ => panic!("Should retry when within both retry count and duration limits"), } } // Test retry exceed max retries { let started_at = SystemTime::now() .checked_sub(Duration::from_secs(60)) .unwrap(); let decision = backoff.should_retry(started_at, 5); match decision { RetryDecision::DoNotRetry => {} _ => panic!("Should not retry when max retries exceeded"), } } // Test retry exceed duration { let started_at = SystemTime::now() .checked_sub(Duration::from_secs(150)) .unwrap(); let decision = backoff.should_retry(started_at, 3); match decision { RetryDecision::DoNotRetry => {} _ => panic!("Should not retry when time duration exceeded"), } } } } retry-policies-0.5.1/src/policies/mod.rs000064400000000000000000000002101046102023000163150ustar 00000000000000mod exponential_backoff; pub use exponential_backoff::{ ExponentialBackoff, ExponentialBackoffBuilder, ExponentialBackoffTimed, }; retry-policies-0.5.1/src/retry_policy.rs000064400000000000000000000072171046102023000164710ustar 00000000000000use std::time::{Duration, SystemTime}; use rand::{ distr::uniform::{UniformFloat, UniformSampler}, Rng, }; /// A policy for deciding whether and when to retry. pub trait RetryPolicy { /// Determine if a task should be retried according to a retry policy. fn should_retry(&self, request_start_time: SystemTime, n_past_retries: u32) -> RetryDecision; } /// Outcome of evaluating a retry policy for a failed task. #[derive(Debug)] pub enum RetryDecision { /// Retry after the specified timestamp. Retry { execute_after: SystemTime }, /// Give up. DoNotRetry, } /// How to apply jitter to the retry intervals. #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[non_exhaustive] pub enum Jitter { /// Don't apply any jitter. None, /// Jitter between 0 and the calculated backoff duration. Full, /// Jitter between 50% of `min_retry_interval` and the calculated backoff duration. Bounded, } impl Jitter { /// The lower bound for the calculated interval, as a fraction of the minimum /// interval. const BOUNDED_MIN_BOUND_FRACTION: f64 = 0.5; pub(crate) fn apply( &self, interval: Duration, min_interval: Duration, rng: &mut impl Rng, ) -> Duration { match self { Jitter::None => interval, Jitter::Full => { let jitter_factor = UniformFloat::::sample_single(0.0, 1.0, rng) .expect("Sample range should be valid"); interval.mul_f64(jitter_factor) } Jitter::Bounded => { let jitter_factor = UniformFloat::::sample_single(0.0, 1.0, rng) .expect("Sample range should be valid"); let jittered_wait_for = (interval - min_interval.mul_f64(Self::BOUNDED_MIN_BOUND_FRACTION)) .mul_f64(jitter_factor); jittered_wait_for + min_interval.mul_f64(Self::BOUNDED_MIN_BOUND_FRACTION) } } } } #[cfg(test)] mod tests { use rand::{rngs::StdRng, SeedableRng}; use super::*; use std::time::Duration; const SEED: u64 = 3097268606784207815; #[test] fn test_jitter_none() { let jitter = Jitter::None; let min_interval = Duration::from_secs(5); let interval = Duration::from_secs(10); assert_eq!( jitter.apply(interval, min_interval, &mut rand::rng()), interval, ); } #[test] fn test_jitter_full() { let jitter = Jitter::Full; let min_interval = Duration::from_secs(5); let interval = Duration::from_secs(10); let result = jitter.apply(interval, min_interval, &mut rand::rng()); assert!(result >= Duration::ZERO && result <= interval); } #[test] fn test_jitter_bounded() { let jitter = Jitter::Bounded; let min_interval = Duration::from_secs(5); let interval = Duration::from_secs(10); let result = jitter.apply(interval, min_interval, &mut rand::rng()); assert!( result >= min_interval.mul_f64(Jitter::BOUNDED_MIN_BOUND_FRACTION) && result <= interval ); } #[test] fn test_jitter_bounded_first_retry() { let jitter = Jitter::Bounded; let min_interval = Duration::from_secs(1); let interval = min_interval; let mut rng: StdRng = SeedableRng::seed_from_u64(SEED); let result = jitter.apply(interval, min_interval, &mut rng); assert!( result < interval, "should have jittered to below the min interval" ); assert_eq!(result, Duration::from_nanos(708_215_236)); } }