├── .github ├── CODEOWNERS ├── ISSUE_TEMPLATE │ ├── bug_report.md │ ├── config.yml │ └── feature_request.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ ├── audit.yml │ ├── ci.yml │ └── release-plz.yml ├── .gitignore ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md └── src ├── lib.rs ├── policies ├── exponential_backoff.rs └── mod.rs └── retry_policy.rs /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @TrueLayer/rust-oss 2 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | ## Bug description 11 | 12 | 13 | 14 | ## To Reproduce 15 | 16 | 17 | 18 | ## Expected behavior 19 | 20 | 21 | 22 | ## Environment 23 | 24 | 25 | 26 | - OS: [e.g. Windows] 27 | - Rust version [e.g. 1.51.0] 28 | 29 | ## Additional context 30 | 31 | 32 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: true 2 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: enhancement 6 | assignees: '' 7 | 8 | --- 9 | 10 | ## Motivations 11 | 12 | 16 | 17 | ## Solution 18 | 19 | 20 | 21 | ## Alternatives 22 | 23 | 24 | 25 | ## Additional context 26 | 27 | 28 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 13 | -------------------------------------------------------------------------------- /.github/workflows/audit.yml: -------------------------------------------------------------------------------- 1 | name: Security audit 2 | 3 | on: 4 | schedule: 5 | # Runs at 00:00 UTC everyday 6 | - cron: '0 0 * * *' 7 | push: 8 | paths: 9 | - '**/Cargo.toml' 10 | - '**/Cargo.lock' 11 | pull_request: 12 | 13 | jobs: 14 | audit: 15 | runs-on: ubuntu-latest 16 | steps: 17 | - name: Checkout repository 18 | uses: actions/checkout@v2 19 | - uses: actions-rs/audit-check@v1 20 | with: 21 | token: ${{ secrets.GITHUB_TOKEN }} 22 | 23 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | branches: [main] 4 | pull_request: 5 | name: CI # Continuous Integration 6 | 7 | jobs: 8 | 9 | test: 10 | name: Test Suite 11 | runs-on: ubuntu-latest 12 | steps: 13 | - name: Checkout repository 14 | uses: actions/checkout@v2 15 | - name: Install Rust 16 | uses: actions-rs/toolchain@v1 17 | with: 18 | toolchain: stable 19 | profile: minimal 20 | override: true 21 | - uses: actions-rs/cargo@v1 22 | with: 23 | command: test 24 | args: --workspace --all-targets --all-features 25 | 26 | rustfmt: 27 | name: Rustfmt 28 | runs-on: ubuntu-latest 29 | steps: 30 | - name: Checkout repository 31 | uses: actions/checkout@v2 32 | - name: Install Rust 33 | uses: actions-rs/toolchain@v1 34 | with: 35 | toolchain: stable 36 | profile: minimal 37 | override: true 38 | components: rustfmt 39 | - name: Check formatting 40 | uses: actions-rs/cargo@v1 41 | with: 42 | command: fmt 43 | args: --all -- --check 44 | 45 | clippy: 46 | name: Clippy 47 | runs-on: ubuntu-latest 48 | steps: 49 | - name: Checkout repository 50 | uses: actions/checkout@v2 51 | - name: Install Rust 52 | uses: actions-rs/toolchain@v1 53 | with: 54 | toolchain: stable 55 | profile: minimal 56 | override: true 57 | components: clippy 58 | - name: Clippy check 59 | uses: actions-rs/cargo@v1 60 | with: 61 | command: clippy 62 | args: --all-targets --all-features --workspace -- -D warnings 63 | 64 | docs: 65 | name: Docs 66 | runs-on: ubuntu-latest 67 | steps: 68 | - name: Checkout repository 69 | uses: actions/checkout@v2 70 | - name: Install Rust 71 | uses: actions-rs/toolchain@v1 72 | with: 73 | toolchain: stable 74 | profile: minimal 75 | override: true 76 | - name: Check documentation 77 | env: 78 | RUSTDOCFLAGS: -D warnings 79 | uses: actions-rs/cargo@v1 80 | with: 81 | command: doc 82 | args: --no-deps --document-private-items --all-features --workspace 83 | 84 | publish-check: 85 | name: Publish dry run 86 | runs-on: ubuntu-latest 87 | steps: 88 | - name: Checkout repository 89 | uses: actions/checkout@v2 90 | - uses: actions-rs/toolchain@v1 91 | with: 92 | toolchain: stable 93 | profile: minimal 94 | override: true 95 | - uses: actions-rs/cargo@v1 96 | with: 97 | command: publish 98 | args: --dry-run 99 | 100 | -------------------------------------------------------------------------------- /.github/workflows/release-plz.yml: -------------------------------------------------------------------------------- 1 | name: Release-plz 2 | 3 | permissions: 4 | pull-requests: write 5 | contents: write 6 | 7 | on: 8 | push: 9 | branches: 10 | - main 11 | 12 | jobs: 13 | release-plz: 14 | name: Release-plz 15 | runs-on: ubuntu-latest 16 | steps: 17 | - name: Checkout repository 18 | uses: actions/checkout@v4 19 | with: 20 | fetch-depth: 0 21 | - name: Install Rust toolchain 22 | uses: dtolnay/rust-toolchain@stable 23 | - name: Run release-plz 24 | uses: MarcoIeni/release-plz-action@v0.5 25 | env: 26 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 27 | CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} 28 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), 6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 7 | 8 | ## [Unreleased] 9 | 10 | ## [0.5.1](https://github.com/TrueLayer/retry-policies/compare/v0.5.0...v0.5.1) - 2025-05-14 11 | 12 | ### Changed 13 | 14 | - Improved bounded jitter to use 50% of `min_retry_interval` instead of 100%. 15 | 16 | ## [0.5.0](https://github.com/TrueLayer/retry-policies/compare/v0.4.0...v0.5.0) - 2025-05-14 17 | 18 | ### Changed 19 | 20 | - [Breaking] Renamed `build_with_total_retry_duration_and_max_retries` to `build_with_total_retry_duration_and_limit_retries`. 21 | 22 | ### Added 23 | 24 | - Added `build_with_total_retry_duration_and_max_retries`. 25 | 26 | ## [0.4.0](https://github.com/TrueLayer/retry-policies/compare/v0.3.0...v0.4.0) - 2024-05-10 27 | 28 | ### Changed 29 | 30 | - [Breaking] Replace `chrono` with standard library types 31 | - Replace `chrono::DateTime` with `std::time::SystemTime` 32 | 33 | ### Removed 34 | 35 | - Remove unused `anyhow` dependency 36 | - Remove `fake` dependency 37 | 38 | ## [0.3.0] - 2024-03-04 39 | 40 | - [Breaking] Implement `RetryPolicy` for `ExponentialBackoffTimed`, which requires a modification to the `should_retry` method of 41 | `RetryPolicy` in order to pass the time at which the task (original request) was started. 42 | 43 | ## [0.2.1] - 2023-10-09 44 | 45 | ### Added 46 | 47 | - Total duration algorithm can now be configured to also consider max retries, calculated applying no jitter (1.0) 48 | - We enforce whatever comes first, total duration or max retries 49 | - Exponential base is now configurable 50 | 51 | ## [0.2.0] - 2023-07-21 52 | 53 | ### Changed 54 | 55 | - [Breaking] Change backoff and jitter algorithms 56 | - Change the backoff algorithm to a more conventional exponential backoff. 57 | - Replace the decorrelated jitter algorithm with an option of either none, full, or bounded. Defaults to full jitter. 58 | - [Breaking] Remove `ExponentialBackoffBuilder::backoff_exponent()` 59 | - The number of attempts is now used as the exponent. 60 | - [Breaking] Require a task start time when using a total retry duration 61 | - `ExponentialBackoffBuilder::build_with_total_retry_duration()` now returns `ExponentialBackoffTimed` which does not implement `RetryPolicy`. 62 | - [Breaking] Mark `ExponentialBackoff` as `non_exhaustive` 63 | - Can no longer be constructed directly. 64 | 65 | ## [0.1.2] - 2022-10-28 66 | 67 | ### Added 68 | 69 | - `Debug` derived for `RetryDecision` 70 | 71 | ## [0.1.1] - 2021-10-18 72 | 73 | ### Security 74 | 75 | - remove time v0.1 dependency 76 | 77 | ## [0.1.0] - 2021-08-11 78 | 79 | ### Added 80 | 81 | - `ExponentialBackoff` policy. 82 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct 2 | 3 | This project adheres to the Rust Code of Conduct, which [can be found online](https://www.rust-lang.org/conduct.html). 4 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribution guidelines 2 | 3 | First off, thank you for considering contributing to retry-policies. 4 | 5 | If your contribution is not straightforward, please first discuss the change you 6 | wish to make by creating a new issue before making the change. 7 | 8 | ## Reporting issues 9 | 10 | Before reporting an issue on the 11 | [issue tracker](https://github.com/TrueLayer/retry-policies/issues), 12 | please check that it has not already been reported by searching for some related 13 | keywords. 14 | 15 | ## Pull requests 16 | 17 | Try to do one pull request per change. 18 | 19 | ### Updating the changelog 20 | 21 | Update the changes you have made in 22 | [CHANGELOG](https://github.com/TrueLayer/retry-policies/blob/master/CHANGELOG.md) 23 | file under the **Unreleased** section. 24 | 25 | Add the changes of your pull request to one of the following subsections, 26 | depending on the types of changes defined by 27 | [Keep a changelog](https://keepachangelog.com/en/1.0.0/): 28 | 29 | - `Added` for new features. 30 | - `Changed` for changes in existing functionality. 31 | - `Deprecated` for soon-to-be removed features. 32 | - `Removed` for now removed features. 33 | - `Fixed` for any bug fixes. 34 | - `Security` in case of vulnerabilities. 35 | 36 | If the required subsection does not exist yet under **Unreleased**, create it! 37 | 38 | ## Developing 39 | 40 | ### Set up 41 | 42 | This is no different than other Rust projects. 43 | 44 | ```shell 45 | git clone https://github.com/TrueLayer/retry-policies 46 | cd rust-retry-policies 47 | cargo test 48 | ``` 49 | 50 | ### Useful Commands 51 | 52 | - Run Clippy: 53 | 54 | ```shell 55 | cargo clippy 56 | ``` 57 | 58 | - Check to see if there are code formatting issues 59 | 60 | ```shell 61 | cargo fmt --all -- --check 62 | ``` 63 | 64 | - Format the code in the project 65 | 66 | ```shell 67 | cargo fmt --all 68 | ``` 69 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "retry-policies" 3 | version = "0.5.1" 4 | authors = ["Luca Palmieri "] 5 | edition = "2018" 6 | description = "A collection of plug-and-play retry policies for Rust projects." 7 | repository = "https://github.com/TrueLayer/retry-policies" 8 | license = "MIT OR Apache-2.0" 9 | keywords = ["retry", "policy", "backoff"] 10 | categories = ["network-programming"] 11 | 12 | [dependencies] 13 | rand = "0.9.1" 14 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 TrueLayer 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # retry-policies 2 | 3 | A collection of plug-and-play retry policies for Rust projects. 4 | 5 | [![Crates.io](https://img.shields.io/crates/v/retry-policies.svg)](https://crates.io/crates/retry-policies) 6 | [![Docs.rs](https://docs.rs/retry-policies/badge.svg)](https://docs.rs/retry-policies) 7 | [![CI](https://github.com/TrueLayer/retry-policies/workflows/CI/badge.svg)](https://github.com/TrueLayer/retry-policies/actions) 8 | [![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) 9 | 10 | Currently available algorithms: 11 | 12 | - [`ExponentialBackoff`](https://docs.rs/retry-policies/latest/retry_policies/policies/struct.ExponentialBackoff.html), 13 | with configurable jitter. 14 | 15 | ## How to install 16 | 17 | Add `retry-policies` to your dependencies 18 | 19 | ```toml 20 | [dependencies] 21 | # ... 22 | retry-policies = "0.4.0" 23 | ``` 24 | 25 | ## License 26 | 27 | 28 | 29 | 30 | Licensed under either of Apache License, Version 31 | 2.0 or MIT license at your option. 32 | 33 | 34 |
35 | 36 | 37 | Unless you explicitly state otherwise, any contribution intentionally submitted 38 | for inclusion in the work by you, as defined in the Apache-2.0 license, shall be 39 | dual licensed as above, without any additional terms or conditions. 40 | 41 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! A collection of plug-and-play retry policies. 2 | pub mod policies; 3 | mod retry_policy; 4 | 5 | pub use retry_policy::{Jitter, RetryDecision, RetryPolicy}; 6 | -------------------------------------------------------------------------------- /src/policies/exponential_backoff.rs: -------------------------------------------------------------------------------- 1 | use crate::{Jitter, RetryDecision, RetryPolicy}; 2 | use std::{ 3 | cmp::{self, min}, 4 | time::{Duration, SystemTime}, 5 | }; 6 | 7 | /// Exponential backoff with optional jitter. 8 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] 9 | #[non_exhaustive] 10 | pub struct ExponentialBackoff { 11 | /// Maximum number of allowed retries attempts. 12 | pub max_n_retries: Option, 13 | /// Minimum waiting time between two retry attempts (it can end up being lower due to jitter). 14 | pub min_retry_interval: Duration, 15 | /// Maximum waiting time between two retry attempts. 16 | pub max_retry_interval: Duration, 17 | /// How we apply jitter to the calculated backoff intervals. 18 | pub jitter: Jitter, 19 | /// Base of the exponential 20 | pub base: u32, 21 | } 22 | 23 | /// Exponential backoff with a maximum retry duration. 24 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] 25 | pub struct ExponentialBackoffTimed { 26 | /// Maximum duration the retries can continue for, after which retries will stop. 27 | max_total_retry_duration: Duration, 28 | 29 | backoff: ExponentialBackoff, 30 | } 31 | 32 | /// Builds an exponential backoff policy. 33 | /// 34 | /// # Example 35 | /// 36 | /// ```rust 37 | /// use retry_policies::{RetryDecision, RetryPolicy, Jitter}; 38 | /// use retry_policies::policies::ExponentialBackoff; 39 | /// use std::time::Duration; 40 | /// 41 | /// let backoff = ExponentialBackoff::builder() 42 | /// .retry_bounds(Duration::from_secs(1), Duration::from_secs(60)) 43 | /// .jitter(Jitter::Bounded) 44 | /// .base(2) 45 | /// .build_with_total_retry_duration(Duration::from_secs(24 * 60 * 60)); 46 | /// ``` 47 | pub struct ExponentialBackoffBuilder { 48 | min_retry_interval: Duration, 49 | max_retry_interval: Duration, 50 | jitter: Jitter, 51 | base: u32, 52 | } 53 | 54 | impl ExponentialBackoff { 55 | /// Returns a builder. 56 | /// 57 | /// # Example 58 | /// ``` 59 | /// use retry_policies::policies::ExponentialBackoff; 60 | /// use std::time::Duration; 61 | /// 62 | /// let backoff = ExponentialBackoff::builder() 63 | /// .build_with_max_retries(5); 64 | /// 65 | /// assert_eq!(backoff.min_retry_interval, Duration::from_secs(1)); 66 | /// assert_eq!(backoff.max_retry_interval, Duration::from_secs(30 * 60)); 67 | /// assert_eq!(backoff.max_n_retries, Some(5)); 68 | /// assert_eq!(backoff.base, 2); 69 | /// ``` 70 | pub fn builder() -> ExponentialBackoffBuilder { 71 | <_>::default() 72 | } 73 | 74 | fn too_many_attempts(&self, n_past_retries: u32) -> bool { 75 | self.max_n_retries 76 | .is_some_and(|max_n| max_n <= n_past_retries) 77 | } 78 | } 79 | 80 | impl RetryPolicy for ExponentialBackoff { 81 | fn should_retry(&self, _request_start_time: SystemTime, n_past_retries: u32) -> RetryDecision { 82 | if self.too_many_attempts(n_past_retries) { 83 | RetryDecision::DoNotRetry 84 | } else { 85 | let unjittered_wait_for = min( 86 | self.max_retry_interval, 87 | self.min_retry_interval * calculate_exponential(self.base, n_past_retries), 88 | ); 89 | 90 | let jittered_wait_for = self.jitter.apply( 91 | unjittered_wait_for, 92 | self.min_retry_interval, 93 | &mut rand::rng(), 94 | ); 95 | 96 | let execute_after = 97 | SystemTime::now() + clip(jittered_wait_for, self.max_retry_interval); 98 | RetryDecision::Retry { execute_after } 99 | } 100 | } 101 | } 102 | 103 | /// Clip to the maximum allowed retry interval. 104 | fn clip(duration: Duration, max_duration: Duration) -> Duration { 105 | cmp::min(duration, max_duration) 106 | } 107 | 108 | /// Calculate exponential using base and number of past retries 109 | fn calculate_exponential(base: u32, n_past_retries: u32) -> u32 { 110 | base.checked_pow(n_past_retries).unwrap_or(u32::MAX) 111 | } 112 | 113 | impl ExponentialBackoffTimed { 114 | /// Maximum number of allowed retries attempts. 115 | pub fn max_retries(&self) -> Option { 116 | self.backoff.max_n_retries 117 | } 118 | 119 | fn trying_for_too_long(&self, started_at: SystemTime) -> bool { 120 | self.max_total_retry_duration <= Self::elapsed(started_at) 121 | } 122 | 123 | fn elapsed(started_at: SystemTime) -> Duration { 124 | SystemTime::now() 125 | .duration_since(started_at) 126 | // If `started_at` is in the future then return a zero duration. 127 | .unwrap_or_default() 128 | } 129 | } 130 | 131 | impl Default for ExponentialBackoffBuilder { 132 | fn default() -> Self { 133 | Self { 134 | min_retry_interval: Duration::from_secs(1), 135 | max_retry_interval: Duration::from_secs(30 * 60), 136 | jitter: Jitter::Full, 137 | base: 2, 138 | } 139 | } 140 | } 141 | 142 | impl RetryPolicy for ExponentialBackoffTimed { 143 | fn should_retry(&self, request_start_time: SystemTime, n_past_retries: u32) -> RetryDecision { 144 | if self.trying_for_too_long(request_start_time) { 145 | return RetryDecision::DoNotRetry; 146 | } 147 | self.backoff 148 | .should_retry(request_start_time, n_past_retries) 149 | } 150 | } 151 | 152 | impl ExponentialBackoffBuilder { 153 | /// Add min & max retry interval bounds. _Default [1s, 30m]_. 154 | /// 155 | /// See [`ExponentialBackoff::min_retry_interval`], [`ExponentialBackoff::max_retry_interval`]. 156 | /// 157 | /// Panics if `min_retry_interval` > `max_retry_interval`. 158 | pub fn retry_bounds( 159 | mut self, 160 | min_retry_interval: Duration, 161 | max_retry_interval: Duration, 162 | ) -> Self { 163 | assert!( 164 | min_retry_interval <= max_retry_interval, 165 | "The maximum interval between retries should be greater or equal than the minimum retry interval." 166 | ); 167 | self.min_retry_interval = min_retry_interval; 168 | self.max_retry_interval = max_retry_interval; 169 | self 170 | } 171 | 172 | /// Set what type of jitter to apply. 173 | pub fn jitter(mut self, jitter: Jitter) -> Self { 174 | self.jitter = jitter; 175 | self 176 | } 177 | 178 | /// Set what base to use for the exponential. 179 | pub fn base(mut self, base: u32) -> Self { 180 | self.base = base; 181 | self 182 | } 183 | 184 | /// Builds an [`ExponentialBackoff`] with the given maximum retries. 185 | /// 186 | /// See [`ExponentialBackoff::max_n_retries`]. 187 | pub fn build_with_max_retries(self, n: u32) -> ExponentialBackoff { 188 | ExponentialBackoff { 189 | min_retry_interval: self.min_retry_interval, 190 | max_retry_interval: self.max_retry_interval, 191 | max_n_retries: Some(n), 192 | jitter: self.jitter, 193 | base: self.base, 194 | } 195 | } 196 | 197 | /// Builds an [`ExponentialBackoff`] with the given maximum total duration for which retries will 198 | /// continue to be performed. 199 | /// 200 | /// # Example 201 | /// 202 | /// ```rust 203 | /// use retry_policies::{RetryDecision, RetryPolicy}; 204 | /// use retry_policies::policies::ExponentialBackoff; 205 | /// use std::time::{Duration, SystemTime}; 206 | /// 207 | /// let backoff = ExponentialBackoff::builder() 208 | /// .build_with_total_retry_duration(Duration::from_secs(24 * 60 * 60)); 209 | /// 210 | /// let started_at = SystemTime::now() 211 | /// .checked_sub(Duration::from_secs(25 * 60 * 60)) 212 | /// .unwrap(); 213 | /// 214 | /// let should_retry = backoff.should_retry(started_at, 0); 215 | /// assert!(matches!(RetryDecision::DoNotRetry, should_retry)); 216 | /// ``` 217 | pub fn build_with_total_retry_duration( 218 | self, 219 | total_duration: Duration, 220 | ) -> ExponentialBackoffTimed { 221 | ExponentialBackoffTimed { 222 | max_total_retry_duration: total_duration, 223 | backoff: ExponentialBackoff { 224 | min_retry_interval: self.min_retry_interval, 225 | max_retry_interval: self.max_retry_interval, 226 | max_n_retries: None, 227 | jitter: self.jitter, 228 | base: self.base, 229 | }, 230 | } 231 | } 232 | 233 | /// Builds an [`ExponentialBackoffTimed`] with the given maximum total duration and limits the 234 | /// number of retries to a calculated maximum. 235 | /// 236 | /// This calculated maximum is based on how many attempts would be made without jitter applied. 237 | /// 238 | /// For example if we set total duration 24 hours, with retry bounds [1s, 24h] and 2 as base of 239 | /// the exponential, we would calculate 17 max retries, as 1s * pow(2, 16) = 65536s = ~18 hours 240 | /// and 18th attempt would be way after the 24 hours total duration. 241 | /// 242 | /// If the 17th retry ends up being scheduled after 10 hours due to jitter, 243 | /// [`ExponentialBackoff::should_retry`] will return false anyway: no retry will be allowed 244 | /// after total duration. 245 | /// 246 | /// If one of the 17 allowed retries for some reason (e.g. previous attempts taking a long time) 247 | /// ends up being scheduled after total duration, [`ExponentialBackoff::should_retry`] will 248 | /// return false. 249 | /// 250 | /// Basically we will enforce whatever comes first, max retries or total duration. 251 | /// 252 | /// # Example 253 | /// 254 | /// ```rust 255 | /// use retry_policies::{RetryDecision, RetryPolicy}; 256 | /// use retry_policies::policies::ExponentialBackoff; 257 | /// use std::time::{Duration, SystemTime}; 258 | /// 259 | /// let exponential_backoff_timed = ExponentialBackoff::builder() 260 | /// .retry_bounds(Duration::from_secs(1), Duration::from_secs(6 * 60 * 60)) 261 | /// .build_with_total_retry_duration_and_limit_retries(Duration::from_secs(24 * 60 * 60)); 262 | /// 263 | /// assert_eq!(exponential_backoff_timed.max_retries(), Some(17)); 264 | /// 265 | /// let started_at = SystemTime::now() 266 | /// .checked_sub(Duration::from_secs(25 * 60 * 60)) 267 | /// .unwrap(); 268 | /// 269 | /// let should_retry = exponential_backoff_timed.should_retry(started_at, 0); 270 | /// assert!(matches!(RetryDecision::DoNotRetry, should_retry)); 271 | /// 272 | /// let started_at = SystemTime::now() 273 | /// .checked_sub(Duration::from_secs(1 * 60 * 60)) 274 | /// .unwrap(); 275 | /// 276 | /// let should_retry = exponential_backoff_timed.should_retry(started_at, 18); 277 | /// assert!(matches!(RetryDecision::DoNotRetry, should_retry)); 278 | /// 279 | /// ``` 280 | pub fn build_with_total_retry_duration_and_limit_retries( 281 | self, 282 | total_duration: Duration, 283 | ) -> ExponentialBackoffTimed { 284 | let mut max_n_retries = None; 285 | 286 | let delays = (0u32..).map(|n| { 287 | min( 288 | self.max_retry_interval, 289 | self.min_retry_interval * calculate_exponential(self.base, n), 290 | ) 291 | }); 292 | 293 | let mut total = Duration::from_secs(0); 294 | for (n, delay) in delays.enumerate() { 295 | total += delay; 296 | if total >= total_duration { 297 | max_n_retries = Some(n as _); 298 | break; 299 | } 300 | } 301 | 302 | ExponentialBackoffTimed { 303 | max_total_retry_duration: total_duration, 304 | backoff: ExponentialBackoff { 305 | min_retry_interval: self.min_retry_interval, 306 | max_retry_interval: self.max_retry_interval, 307 | max_n_retries, 308 | jitter: self.jitter, 309 | base: self.base, 310 | }, 311 | } 312 | } 313 | 314 | /// Builds an [`ExponentialBackoffTimed`] with the given maximum total duration and maximum retries. 315 | pub fn build_with_total_retry_duration_and_max_retries( 316 | self, 317 | total_duration: Duration, 318 | max_n_retries: u32, 319 | ) -> ExponentialBackoffTimed { 320 | ExponentialBackoffTimed { 321 | max_total_retry_duration: total_duration, 322 | backoff: ExponentialBackoff { 323 | min_retry_interval: self.min_retry_interval, 324 | max_retry_interval: self.max_retry_interval, 325 | max_n_retries: Some(max_n_retries), 326 | jitter: self.jitter, 327 | base: self.base, 328 | }, 329 | } 330 | } 331 | } 332 | #[cfg(test)] 333 | mod tests { 334 | use std::convert::TryFrom as _; 335 | 336 | use rand::distr::{Distribution, Uniform}; 337 | 338 | use super::*; 339 | 340 | fn get_retry_policy() -> ExponentialBackoff { 341 | ExponentialBackoff { 342 | max_n_retries: Some(6), 343 | min_retry_interval: Duration::from_secs(1), 344 | max_retry_interval: Duration::from_secs(5 * 60), 345 | jitter: Jitter::Full, 346 | base: 2, 347 | } 348 | } 349 | 350 | #[test] 351 | fn if_n_past_retries_is_below_maximum_it_decides_to_retry() { 352 | // Arrange 353 | let policy = get_retry_policy(); 354 | let n_past_retries = Uniform::try_from(0..policy.max_n_retries.unwrap()) 355 | .unwrap() 356 | .sample(&mut rand::rng()); 357 | assert!(n_past_retries < policy.max_n_retries.unwrap()); 358 | 359 | // Act 360 | let decision = policy.should_retry(SystemTime::now(), n_past_retries); 361 | 362 | // Assert 363 | matches!(decision, RetryDecision::Retry { .. }); 364 | } 365 | 366 | #[test] 367 | fn if_n_past_retries_is_above_maximum_it_decides_to_mark_as_failed() { 368 | // Arrange 369 | let policy = get_retry_policy(); 370 | let n_past_retries = Uniform::try_from(policy.max_n_retries.unwrap()..=u32::MAX) 371 | .unwrap() 372 | .sample(&mut rand::rng()); 373 | assert!(n_past_retries >= policy.max_n_retries.unwrap()); 374 | 375 | // Act 376 | let decision = policy.should_retry(SystemTime::now(), n_past_retries); 377 | 378 | // Assert 379 | matches!(decision, RetryDecision::DoNotRetry); 380 | } 381 | 382 | #[test] 383 | fn maximum_retry_interval_is_never_exceeded() { 384 | // Arrange 385 | let policy = get_retry_policy(); 386 | let max_interval = policy.max_retry_interval; 387 | 388 | // Act 389 | let decision = policy.should_retry(SystemTime::now(), policy.max_n_retries.unwrap() - 1); 390 | 391 | // Assert 392 | match decision { 393 | RetryDecision::Retry { execute_after } => { 394 | assert!(execute_after.duration_since(SystemTime::now()).unwrap() <= max_interval) 395 | } 396 | RetryDecision::DoNotRetry => panic!("Expected Retry decision."), 397 | } 398 | } 399 | 400 | #[test] 401 | fn overflow_backoff_exponent_does_not_cause_a_panic() { 402 | let policy = ExponentialBackoff { 403 | max_n_retries: Some(u32::MAX), 404 | ..get_retry_policy() 405 | }; 406 | let max_interval = policy.max_retry_interval; 407 | let n_failed_attempts = u32::MAX - 1; 408 | 409 | // Act 410 | let decision = policy.should_retry(SystemTime::now(), n_failed_attempts); 411 | 412 | // Assert 413 | match decision { 414 | RetryDecision::Retry { execute_after } => { 415 | assert!(execute_after.duration_since(SystemTime::now()).unwrap() <= max_interval) 416 | } 417 | RetryDecision::DoNotRetry => panic!("Expected Retry decision."), 418 | } 419 | } 420 | 421 | #[test] 422 | #[should_panic] 423 | fn builder_invalid_retry_bounds() { 424 | // bounds are the wrong way round or invalid 425 | ExponentialBackoff::builder().retry_bounds(Duration::from_secs(3), Duration::from_secs(2)); 426 | } 427 | 428 | #[test] 429 | fn does_not_retry_after_total_retry_duration() { 430 | let backoff = ExponentialBackoff::builder() 431 | .build_with_total_retry_duration(Duration::from_secs(24 * 60 * 60)); 432 | 433 | { 434 | let started_at = SystemTime::now() 435 | .checked_sub(Duration::from_secs(23 * 60 * 60)) 436 | .unwrap(); 437 | 438 | let decision = backoff.should_retry(started_at, 0); 439 | 440 | match decision { 441 | RetryDecision::Retry { .. } => {} 442 | _ => panic!("should retry"), 443 | } 444 | } 445 | { 446 | let started_at = SystemTime::now() 447 | .checked_sub(Duration::from_secs(25 * 60 * 60)) 448 | .unwrap(); 449 | 450 | let decision = backoff.should_retry(started_at, 0); 451 | 452 | match decision { 453 | RetryDecision::DoNotRetry => {} 454 | _ => panic!("should not retry"), 455 | } 456 | } 457 | } 458 | 459 | #[test] 460 | fn does_not_retry_before_total_retry_duration_if_max_retries_exceeded() { 461 | let backoff = ExponentialBackoff::builder() 462 | // This configuration should allow 17 max retries inside a 24h total duration 463 | .retry_bounds(Duration::from_secs(1), Duration::from_secs(6 * 60 * 60)) 464 | .build_with_total_retry_duration_and_limit_retries(Duration::from_secs(24 * 60 * 60)); 465 | 466 | { 467 | let started_at = SystemTime::now() 468 | .checked_sub(Duration::from_secs(23 * 60 * 60)) 469 | .unwrap(); 470 | 471 | let decision = backoff.should_retry(started_at, 0); 472 | 473 | match decision { 474 | RetryDecision::Retry { .. } => {} 475 | _ => panic!("should retry"), 476 | } 477 | } 478 | { 479 | let started_at = SystemTime::now() 480 | .checked_sub(Duration::from_secs(23 * 60 * 60)) 481 | .unwrap(); 482 | 483 | // Zero based, so this is the 18th retry 484 | let decision = backoff.should_retry(started_at, 17); 485 | 486 | match decision { 487 | RetryDecision::DoNotRetry => {} 488 | _ => panic!("should not retry"), 489 | } 490 | } 491 | { 492 | let started_at = SystemTime::now() 493 | .checked_sub(Duration::from_secs(25 * 60 * 60)) 494 | .unwrap(); 495 | 496 | let decision = backoff.should_retry(started_at, 0); 497 | 498 | match decision { 499 | RetryDecision::DoNotRetry => {} 500 | _ => panic!("should not retry"), 501 | } 502 | } 503 | } 504 | 505 | #[test] 506 | fn different_exponential_base_produce_different_max_retries_for_the_same_duration() { 507 | let backoff_base_2 = ExponentialBackoff::builder() 508 | .retry_bounds(Duration::from_secs(1), Duration::from_secs(60 * 60)) 509 | .base(2) 510 | .build_with_total_retry_duration_and_limit_retries(Duration::from_secs(60 * 60)); 511 | 512 | let backoff_base_3 = ExponentialBackoff::builder() 513 | .retry_bounds(Duration::from_secs(1), Duration::from_secs(60 * 60)) 514 | .base(3) 515 | .build_with_total_retry_duration_and_limit_retries(Duration::from_secs(60 * 60)); 516 | 517 | let backoff_base_4 = ExponentialBackoff::builder() 518 | .retry_bounds(Duration::from_secs(1), Duration::from_secs(60 * 60)) 519 | .base(4) 520 | .build_with_total_retry_duration_and_limit_retries(Duration::from_secs(60 * 60)); 521 | 522 | assert_eq!(backoff_base_2.max_retries().unwrap(), 11); 523 | assert_eq!(backoff_base_3.max_retries().unwrap(), 8); 524 | assert_eq!(backoff_base_4.max_retries().unwrap(), 6); 525 | } 526 | 527 | #[test] 528 | fn total_retry_duration_and_max_retries() { 529 | // Create backoff policy with specific duration and retry limits 530 | let backoff = ExponentialBackoff::builder() 531 | .retry_bounds(Duration::from_secs(1), Duration::from_secs(30)) 532 | .build_with_total_retry_duration_and_max_retries(Duration::from_secs(120), 5); 533 | 534 | // Verify the max retries was set correctly 535 | assert_eq!(backoff.max_retries(), Some(5)); 536 | 537 | // Test retry within limits 538 | { 539 | let started_at = SystemTime::now() 540 | .checked_sub(Duration::from_secs(60)) 541 | .unwrap(); 542 | 543 | let decision = backoff.should_retry(started_at, 3); 544 | 545 | match decision { 546 | RetryDecision::Retry { .. } => {} 547 | _ => panic!("Should retry when within both retry count and duration limits"), 548 | } 549 | } 550 | 551 | // Test retry exceed max retries 552 | { 553 | let started_at = SystemTime::now() 554 | .checked_sub(Duration::from_secs(60)) 555 | .unwrap(); 556 | 557 | let decision = backoff.should_retry(started_at, 5); 558 | 559 | match decision { 560 | RetryDecision::DoNotRetry => {} 561 | _ => panic!("Should not retry when max retries exceeded"), 562 | } 563 | } 564 | 565 | // Test retry exceed duration 566 | { 567 | let started_at = SystemTime::now() 568 | .checked_sub(Duration::from_secs(150)) 569 | .unwrap(); 570 | 571 | let decision = backoff.should_retry(started_at, 3); 572 | 573 | match decision { 574 | RetryDecision::DoNotRetry => {} 575 | _ => panic!("Should not retry when time duration exceeded"), 576 | } 577 | } 578 | } 579 | } 580 | -------------------------------------------------------------------------------- /src/policies/mod.rs: -------------------------------------------------------------------------------- 1 | mod exponential_backoff; 2 | 3 | pub use exponential_backoff::{ 4 | ExponentialBackoff, ExponentialBackoffBuilder, ExponentialBackoffTimed, 5 | }; 6 | -------------------------------------------------------------------------------- /src/retry_policy.rs: -------------------------------------------------------------------------------- 1 | use std::time::{Duration, SystemTime}; 2 | 3 | use rand::{ 4 | distr::uniform::{UniformFloat, UniformSampler}, 5 | Rng, 6 | }; 7 | 8 | /// A policy for deciding whether and when to retry. 9 | pub trait RetryPolicy { 10 | /// Determine if a task should be retried according to a retry policy. 11 | fn should_retry(&self, request_start_time: SystemTime, n_past_retries: u32) -> RetryDecision; 12 | } 13 | 14 | /// Outcome of evaluating a retry policy for a failed task. 15 | #[derive(Debug)] 16 | pub enum RetryDecision { 17 | /// Retry after the specified timestamp. 18 | Retry { execute_after: SystemTime }, 19 | /// Give up. 20 | DoNotRetry, 21 | } 22 | 23 | /// How to apply jitter to the retry intervals. 24 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] 25 | #[non_exhaustive] 26 | pub enum Jitter { 27 | /// Don't apply any jitter. 28 | None, 29 | /// Jitter between 0 and the calculated backoff duration. 30 | Full, 31 | /// Jitter between 50% of `min_retry_interval` and the calculated backoff duration. 32 | Bounded, 33 | } 34 | 35 | impl Jitter { 36 | /// The lower bound for the calculated interval, as a fraction of the minimum 37 | /// interval. 38 | const BOUNDED_MIN_BOUND_FRACTION: f64 = 0.5; 39 | 40 | pub(crate) fn apply( 41 | &self, 42 | interval: Duration, 43 | min_interval: Duration, 44 | rng: &mut impl Rng, 45 | ) -> Duration { 46 | match self { 47 | Jitter::None => interval, 48 | Jitter::Full => { 49 | let jitter_factor = UniformFloat::::sample_single(0.0, 1.0, rng) 50 | .expect("Sample range should be valid"); 51 | 52 | interval.mul_f64(jitter_factor) 53 | } 54 | Jitter::Bounded => { 55 | let jitter_factor = UniformFloat::::sample_single(0.0, 1.0, rng) 56 | .expect("Sample range should be valid"); 57 | 58 | let jittered_wait_for = (interval 59 | - min_interval.mul_f64(Self::BOUNDED_MIN_BOUND_FRACTION)) 60 | .mul_f64(jitter_factor); 61 | 62 | jittered_wait_for + min_interval.mul_f64(Self::BOUNDED_MIN_BOUND_FRACTION) 63 | } 64 | } 65 | } 66 | } 67 | 68 | #[cfg(test)] 69 | mod tests { 70 | use rand::{rngs::StdRng, SeedableRng}; 71 | 72 | use super::*; 73 | use std::time::Duration; 74 | 75 | const SEED: u64 = 3097268606784207815; 76 | 77 | #[test] 78 | fn test_jitter_none() { 79 | let jitter = Jitter::None; 80 | let min_interval = Duration::from_secs(5); 81 | let interval = Duration::from_secs(10); 82 | assert_eq!( 83 | jitter.apply(interval, min_interval, &mut rand::rng()), 84 | interval, 85 | ); 86 | } 87 | 88 | #[test] 89 | fn test_jitter_full() { 90 | let jitter = Jitter::Full; 91 | let min_interval = Duration::from_secs(5); 92 | let interval = Duration::from_secs(10); 93 | let result = jitter.apply(interval, min_interval, &mut rand::rng()); 94 | assert!(result >= Duration::ZERO && result <= interval); 95 | } 96 | 97 | #[test] 98 | fn test_jitter_bounded() { 99 | let jitter = Jitter::Bounded; 100 | let min_interval = Duration::from_secs(5); 101 | let interval = Duration::from_secs(10); 102 | let result = jitter.apply(interval, min_interval, &mut rand::rng()); 103 | assert!( 104 | result >= min_interval.mul_f64(Jitter::BOUNDED_MIN_BOUND_FRACTION) 105 | && result <= interval 106 | ); 107 | } 108 | 109 | #[test] 110 | fn test_jitter_bounded_first_retry() { 111 | let jitter = Jitter::Bounded; 112 | let min_interval = Duration::from_secs(1); 113 | let interval = min_interval; 114 | let mut rng: StdRng = SeedableRng::seed_from_u64(SEED); 115 | let result = jitter.apply(interval, min_interval, &mut rng); 116 | assert!( 117 | result < interval, 118 | "should have jittered to below the min interval" 119 | ); 120 | assert_eq!(result, Duration::from_nanos(708_215_236)); 121 | } 122 | } 123 | --------------------------------------------------------------------------------