├── .github ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md └── workflows │ └── ci.yaml ├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── src ├── into_iter.rs └── lib.rs └── tests └── test.rs /.github/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of 9 | experience, 10 | education, socio-economic status, nationality, personal appearance, race, 11 | religion, or sexual identity and orientation. 12 | 13 | ## Our Standards 14 | 15 | Examples of behavior that contributes to creating a positive environment 16 | include: 17 | 18 | - Using welcoming and inclusive language 19 | - Being respectful of differing viewpoints and experiences 20 | - Gracefully accepting constructive criticism 21 | - Focusing on what is best for the community 22 | - Showing empathy towards other community members 23 | 24 | Examples of unacceptable behavior by participants include: 25 | 26 | - The use of sexualized language or imagery and unwelcome sexual attention or 27 | advances 28 | - Trolling, insulting/derogatory comments, and personal or political attacks 29 | - Public or private harassment 30 | - Publishing others' private information, such as a physical or electronic 31 | address, without explicit permission 32 | - Other conduct which could reasonably be considered inappropriate in a 33 | professional setting 34 | 35 | 36 | ## Our Responsibilities 37 | 38 | Project maintainers are responsible for clarifying the standards of acceptable 39 | behavior and are expected to take appropriate and fair corrective action in 40 | response to any instances of unacceptable behavior. 41 | 42 | Project maintainers have the right and responsibility to remove, edit, or 43 | reject comments, commits, code, wiki edits, issues, and other contributions 44 | that are not aligned to this Code of Conduct, or to ban temporarily or 45 | permanently any contributor for other behaviors that they deem inappropriate, 46 | threatening, offensive, or harmful. 47 | 48 | ## Scope 49 | 50 | This Code of Conduct applies both within project spaces and in public spaces 51 | when an individual is representing the project or its community. Examples of 52 | representing a project or community include using an official project e-mail 53 | address, posting via an official social media account, or acting as an appointed 54 | representative at an online or offline event. Representation of a project may be 55 | further defined and clarified by project maintainers. 56 | 57 | ## Enforcement 58 | 59 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 60 | reported by contacting the project team at yoshuawuyts@gmail.com, or through 61 | IRC. All complaints will be reviewed and investigated and will result in a 62 | response that is deemed necessary and appropriate to the circumstances. The 63 | project team is obligated to maintain confidentiality with regard to the 64 | reporter of an incident. 65 | Further details of specific enforcement policies may be posted separately. 66 | 67 | Project maintainers who do not follow or enforce the Code of Conduct in good 68 | faith may face temporary or permanent repercussions as determined by other 69 | members of the project's leadership. 70 | 71 | ## Attribution 72 | 73 | This Code of Conduct is adapted from the Contributor Covenant, version 1.4, 74 | available at 75 | https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 76 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | Contributions include code, documentation, answering user questions, running the 3 | project's infrastructure, and advocating for all types of users. 4 | 5 | The project welcomes all contributions from anyone willing to work in good faith 6 | with other contributors and the community. No contribution is too small and all 7 | contributions are valued. 8 | 9 | This guide explains the process for contributing to the project's GitHub 10 | Repository. 11 | 12 | - [Code of Conduct](#code-of-conduct) 13 | - [Bad Actors](#bad-actors) 14 | - [Developer Certificate of Origin](#developer-certificate-of-origin) 15 | 16 | ## Code of Conduct 17 | The project has a [Code of Conduct](./CODE_OF_CONDUCT.md) that *all* 18 | contributors are expected to follow. This code describes the *minimum* behavior 19 | expectations for all contributors. 20 | 21 | As a contributor, how you choose to act and interact towards your 22 | fellow contributors, as well as to the community, will reflect back not only 23 | on yourself but on the project as a whole. The Code of Conduct is designed and 24 | intended, above all else, to help establish a culture within the project that 25 | allows anyone and everyone who wants to contribute to feel safe doing so. 26 | 27 | Should any individual act in any way that is considered in violation of the 28 | [Code of Conduct](./CODE_OF_CONDUCT.md), corrective actions will be taken. It is 29 | possible, however, for any individual to *act* in such a manner that is not in 30 | violation of the strict letter of the Code of Conduct guidelines while still 31 | going completely against the spirit of what that Code is intended to accomplish. 32 | 33 | Open, diverse, and inclusive communities live and die on the basis of trust. 34 | Contributors can disagree with one another so long as they trust that those 35 | disagreements are in good faith and everyone is working towards a common 36 | goal. 37 | 38 | ## Bad Actors 39 | All contributors to tacitly agree to abide by both the letter and 40 | spirit of the [Code of Conduct](./CODE_OF_CONDUCT.md). Failure, or 41 | unwillingness, to do so will result in contributions being respectfully 42 | declined. 43 | 44 | A *bad actor* is someone who repeatedly violates the *spirit* of the Code of 45 | Conduct through consistent failure to self-regulate the way in which they 46 | interact with other contributors in the project. In doing so, bad actors 47 | alienate other contributors, discourage collaboration, and generally reflect 48 | poorly on the project as a whole. 49 | 50 | Being a bad actor may be intentional or unintentional. Typically, unintentional 51 | bad behavior can be easily corrected by being quick to apologize and correct 52 | course *even if you are not entirely convinced you need to*. Giving other 53 | contributors the benefit of the doubt and having a sincere willingness to admit 54 | that you *might* be wrong is critical for any successful open collaboration. 55 | 56 | Don't be a bad actor. 57 | -------------------------------------------------------------------------------- /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | pull_request: 5 | push: 6 | branches: 7 | - main 8 | 9 | env: 10 | RUSTFLAGS: -Dwarnings 11 | 12 | jobs: 13 | build_and_test: 14 | name: Build and test 15 | runs-on: ${{ matrix.os }} 16 | strategy: 17 | matrix: 18 | # os: [ubuntu-latest, windows-latest, macOS-latest] 19 | os: [ubuntu-latest] 20 | rust: [stable] 21 | 22 | steps: 23 | - uses: actions/checkout@master 24 | 25 | - name: Install ${{ matrix.rust }} 26 | uses: actions-rs/toolchain@v1 27 | with: 28 | toolchain: ${{ matrix.rust }} 29 | override: true 30 | 31 | - name: check 32 | uses: actions-rs/cargo@v1 33 | with: 34 | command: check 35 | args: --all --bins --examples 36 | 37 | - name: tests 38 | uses: actions-rs/cargo@v1 39 | with: 40 | command: test 41 | args: --all 42 | 43 | check_fmt_and_docs: 44 | name: Checking fmt and docs 45 | runs-on: ubuntu-latest 46 | steps: 47 | - uses: actions/checkout@master 48 | - uses: actions-rs/toolchain@v1 49 | with: 50 | toolchain: nightly 51 | components: rustfmt, clippy 52 | override: true 53 | 54 | - name: fmt 55 | run: cargo fmt --all -- --check 56 | 57 | - name: Docs 58 | run: cargo doc --no-deps 59 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | coverage/ 3 | tmp/ 4 | dist/ 5 | npm-debug.log* 6 | .DS_Store 7 | .nyc_output 8 | target/ 9 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 4 4 | 5 | [[package]] 6 | name = "exponential-backoff" 7 | version = "2.1.0" 8 | dependencies = [ 9 | "fastrand", 10 | ] 11 | 12 | [[package]] 13 | name = "fastrand" 14 | version = "2.0.1" 15 | source = "registry+https://github.com/rust-lang/crates.io-index" 16 | checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5" 17 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "exponential-backoff" 3 | version = "2.1.0" 4 | license = "MIT OR Apache-2.0" 5 | repository = "https://github.com/yoshuawuyts/exponential-backoff" 6 | documentation = "https://docs.rs/exponential-backoff" 7 | description = "An exponential backoff generator with jitter." 8 | keywords = ["backoff", "retry", "simple", "exponential", "async"] 9 | categories = ["algorithms", "date-and-time", ] 10 | authors = ["Yoshua Wuyts "] 11 | readme = "README.md" 12 | edition = "2021" 13 | 14 | [dependencies] 15 | fastrand = "2" 16 | 17 | [dev-dependencies] 18 | -------------------------------------------------------------------------------- /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 | 178 | Copyright 2018 Yoshua Wuyts 179 | 180 | Licensed under the Apache License, Version 2.0 (the "License"); 181 | you may not use this file except in compliance with the License. 182 | You may obtain a copy of the License at 183 | 184 | http://www.apache.org/licenses/LICENSE-2.0 185 | 186 | Unless required by applicable law or agreed to in writing, software 187 | distributed under the License is distributed on an "AS IS" BASIS, 188 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 189 | See the License for the specific language governing permissions and 190 | limitations under the License. 191 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2018 Yoshua Wuyts 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 | # exponential-backoff 2 | [![crates.io version][1]][2] 3 | [![downloads][5]][6] [![docs.rs docs][7]][8] 4 | 5 | An exponential backoff generator with jitter. Serves as a building block to 6 | implement custom retry functions. 7 | 8 | - [Documentation][8] 9 | - [Crates.io][2] 10 | 11 | ## Why? 12 | When an network requests times out, often the best way to solve it is to try 13 | again. But trying again straight away might at best cause some network overhead, 14 | and at worst a full fledged DDOS. So we have to be responsible about it. 15 | 16 | A good explanation of retry strategies can be found on the [Stripe 17 | blog](https://stripe.com/blog/idempotency). 18 | 19 | ## Usage 20 | Here we try and read a file from disk, and try again if it fails. A more 21 | realistic scenario would probably to perform an HTTP request, but the approach 22 | should be similar. 23 | 24 | ```rust 25 | use exponential_backoff::Backoff; 26 | use std::{fs, thread, time::Duration}; 27 | 28 | let attempts = 3; 29 | let min = Duration::from_millis(100); 30 | let max = Duration::from_secs(10); 31 | 32 | for duration in Backoff::new(attempts, min, max) { 33 | match fs::read_to_string("README.md") { 34 | Ok(string) => return Ok(string), 35 | Err(err) => match duration { 36 | Some(duration) => thread::sleep(duration), 37 | None => return Err(err), 38 | } 39 | } 40 | } 41 | ``` 42 | 43 | ## Installation 44 | ```sh 45 | $ cargo add exponential-backoff 46 | ``` 47 | 48 | ## See Also 49 | - [segment/backo](https://github.com/segmentio/backo) 50 | - [stripe/stripe-ruby](https://github.com/stripe/stripe-ruby/blob/1bb9ac48b916b1c60591795cdb7ba6d18495e82d/lib/stripe/stripe_client.rb#L78-L92) 51 | 52 | ## Further Reading 53 | - https://stripe.com/blog/idempotency 54 | - https://en.wikipedia.org/wiki/Exponential_backoff 55 | 56 | ## License 57 | [MIT](./LICENSE-MIT) OR [Apache-2.0](./LICENSE-APACHE) 58 | 59 | [1]: https://img.shields.io/crates/v/exponential-backoff.svg?style=flat-square 60 | [2]: https://crates.io/crates/exponential-backoff 61 | [3]: https://img.shields.io/travis/yoshuawuyts/exponential-backoff.svg?style=flat-square 62 | [4]: https://travis-ci.org/yoshuawuyts/exponential-backoff 63 | [5]: https://img.shields.io/crates/d/exponential-backoff.svg?style=flat-square 64 | [6]: https://crates.io/crates/exponential-backoff 65 | [7]: https://img.shields.io/badge/docs-latest-blue.svg?style=flat-square 66 | [8]: https://docs.rs/exponential-backoff 67 | -------------------------------------------------------------------------------- /src/into_iter.rs: -------------------------------------------------------------------------------- 1 | use super::Backoff; 2 | use fastrand::Rng; 3 | use std::{iter, time::Duration}; 4 | 5 | /// An exponential backoff iterator. 6 | #[derive(Debug, Clone)] 7 | pub struct IntoIter { 8 | inner: Backoff, 9 | rng: Rng, 10 | attempts: u32, 11 | } 12 | 13 | impl IntoIter { 14 | pub(crate) fn new(inner: Backoff) -> Self { 15 | Self { 16 | attempts: 0, 17 | rng: Rng::new(), 18 | inner, 19 | } 20 | } 21 | } 22 | 23 | impl iter::Iterator for IntoIter { 24 | type Item = Option; 25 | 26 | #[inline] 27 | fn next(&mut self) -> Option { 28 | // Check whether we've exceeded the number of attempts, 29 | // or whether we're on our last attempt. We don't want to sleep after 30 | // the last attempt. 31 | if self.attempts == self.inner.max_attempts { 32 | return None; 33 | } else if self.attempts == self.inner.max_attempts - 1 { 34 | self.attempts = self.attempts.saturating_add(1); 35 | return Some(None); 36 | } 37 | 38 | // Create exponential duration. 39 | let exponent = self.inner.factor.saturating_pow(self.attempts); 40 | let mut duration = self.inner.min.saturating_mul(exponent); 41 | 42 | // Increment the attempts counter. 43 | self.attempts = self.attempts.saturating_add(1); 44 | 45 | // Apply jitter. Uses multiples of 100 to prevent relying on floats. 46 | // 47 | // We put this in a conditional block because the `fastrand` crate 48 | // doesn't like `0..0` inputs, and dividing by zero is also not a good 49 | // idea. 50 | if self.inner.jitter != 0.0 { 51 | let jitter_factor = (self.inner.jitter * 100f32) as u32; 52 | let random = self.rng.u32(0..jitter_factor * 2); 53 | let mut duration = duration.saturating_mul(100); 54 | if random < jitter_factor { 55 | let jitter = duration.saturating_mul(random) / 100; 56 | duration = duration.saturating_sub(jitter); 57 | } else { 58 | let jitter = duration.saturating_mul(random / 2) / 100; 59 | duration = duration.saturating_add(jitter); 60 | }; 61 | duration /= 100; 62 | } 63 | 64 | // Make sure it doesn't exceed upper / lower bounds. 65 | duration = duration.clamp(self.inner.min, self.inner.max); 66 | 67 | Some(Some(duration)) 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! An exponential backoff generator with jitter. Serves as a building block to 2 | //! implement custom retry functions. 3 | //! 4 | //! # Why? 5 | //! When an network requests times out, often the best way to solve it is to try 6 | //! again. But trying again straight away might at best cause some network overhead, 7 | //! and at worst a full fledged DDOS. So we have to be responsible about it. 8 | //! 9 | //! A good explanation of retry strategies can be found on the [Stripe 10 | //! blog](https://stripe.com/blog/idempotency). 11 | //! 12 | //! # Usage 13 | //! Here we try and read a file from disk, and try again if it fails. A more 14 | //! realistic scenario would probably to perform an HTTP request, but the approach 15 | //! should be similar. 16 | //! 17 | //! ```rust 18 | //! # fn retry() -> std::io::Result<()> { 19 | //! use exponential_backoff::Backoff; 20 | //! use std::{fs, thread, time::Duration}; 21 | //! 22 | //! let attempts = 3; 23 | //! let min = Duration::from_millis(100); 24 | //! let max = Duration::from_secs(10); 25 | //! 26 | //! for duration in Backoff::new(attempts, min, max) { 27 | //! match fs::read_to_string("README.md") { 28 | //! Ok(s) => { 29 | //! println!("{}", s); 30 | //! break; 31 | //! } 32 | //! Err(err) => match duration { 33 | //! Some(duration) => thread::sleep(duration), 34 | //! None => return Err(err), 35 | //! } 36 | //! } 37 | //! } 38 | //! # Ok(()) } 39 | //! ``` 40 | 41 | mod into_iter; 42 | 43 | use std::time::Duration; 44 | 45 | pub use crate::into_iter::IntoIter; 46 | 47 | /// Exponential backoff type. 48 | #[derive(Debug, Clone)] 49 | pub struct Backoff { 50 | max_attempts: u32, 51 | min: Duration, 52 | max: Duration, 53 | jitter: f32, 54 | factor: u32, 55 | } 56 | impl Backoff { 57 | /// Create a new instance of `Backoff`. 58 | /// 59 | /// # Examples 60 | /// 61 | /// With an explicit max duration: 62 | /// 63 | /// ```rust 64 | /// use exponential_backoff::Backoff; 65 | /// use std::time::Duration; 66 | /// 67 | /// let backoff = Backoff::new(3, Duration::from_millis(100), Duration::from_secs(10)); 68 | /// assert_eq!(backoff.max_attempts(), 3); 69 | /// assert_eq!(backoff.min(), &Duration::from_millis(100)); 70 | /// assert_eq!(backoff.max(), &Duration::from_secs(10)); 71 | /// ``` 72 | /// 73 | /// With no max duration (sets it to 584,942,417,355 years): 74 | /// 75 | /// ```rust 76 | /// use exponential_backoff::Backoff; 77 | /// use std::time::Duration; 78 | /// 79 | /// let backoff = Backoff::new(5, Duration::from_millis(50), None); 80 | /// # assert_eq!(backoff.max_attempts(), 5); 81 | /// # assert_eq!(backoff.min(), &Duration::from_millis(50)); 82 | /// assert_eq!(backoff.max(), &Duration::MAX); 83 | /// ``` 84 | #[inline] 85 | pub fn new(max_attempts: u32, min: Duration, max: impl Into>) -> Self { 86 | Self { 87 | max_attempts, 88 | min, 89 | max: max.into().unwrap_or(Duration::MAX), 90 | jitter: 0.3, 91 | factor: 2, 92 | } 93 | } 94 | 95 | /// Get the min duration 96 | /// 97 | /// # Examples 98 | /// 99 | /// ```rust 100 | /// use exponential_backoff::Backoff; 101 | /// use std::time::Duration; 102 | /// 103 | /// let mut backoff = Backoff::default(); 104 | /// assert_eq!(backoff.min(), &Duration::from_millis(100)); 105 | /// ``` 106 | pub fn min(&self) -> &Duration { 107 | &self.min 108 | } 109 | 110 | /// Set the min duration. 111 | /// 112 | /// # Examples 113 | /// 114 | /// ```rust 115 | /// use exponential_backoff::Backoff; 116 | /// use std::time::Duration; 117 | /// 118 | /// let mut backoff = Backoff::default(); 119 | /// backoff.set_min(Duration::from_millis(50)); 120 | /// assert_eq!(backoff.min(), &Duration::from_millis(50)); 121 | /// ``` 122 | #[inline] 123 | pub fn set_min(&mut self, min: Duration) { 124 | self.min = min; 125 | } 126 | 127 | /// Get the max duration 128 | /// 129 | /// # Examples 130 | /// 131 | /// ```rust 132 | /// use exponential_backoff::Backoff; 133 | /// use std::time::Duration; 134 | /// 135 | /// let mut backoff = Backoff::default(); 136 | /// assert_eq!(backoff.max(), &Duration::from_secs(10)); 137 | /// ``` 138 | pub fn max(&self) -> &Duration { 139 | &self.max 140 | } 141 | 142 | /// Set the max duration. 143 | /// 144 | /// # Examples 145 | /// 146 | /// ```rust 147 | /// use exponential_backoff::Backoff; 148 | /// use std::time::Duration; 149 | /// 150 | /// let mut backoff = Backoff::default(); 151 | /// backoff.set_max(Duration::from_secs(30)); 152 | /// assert_eq!(backoff.max(), &Duration::from_secs(30)); 153 | /// ``` 154 | #[inline] 155 | pub fn set_max(&mut self, max: Duration) { 156 | self.max = max; 157 | } 158 | 159 | /// Get the maximum number of attempts 160 | /// 161 | /// # Examples 162 | /// 163 | /// ```rust 164 | /// use exponential_backoff::Backoff; 165 | /// 166 | /// let mut backoff = Backoff::default(); 167 | /// assert_eq!(backoff.max_attempts(), 3); 168 | /// ``` 169 | pub fn max_attempts(&self) -> u32 { 170 | self.max_attempts 171 | } 172 | 173 | /// Set the maximum number of attempts. 174 | /// 175 | /// # Examples 176 | /// 177 | /// ```rust 178 | /// use exponential_backoff::Backoff; 179 | /// 180 | /// let mut backoff = Backoff::default(); 181 | /// backoff.set_max_attempts(5); 182 | /// assert_eq!(backoff.max_attempts(), 5); 183 | /// ``` 184 | pub fn set_max_attempts(&mut self, max_attempts: u32) { 185 | self.max_attempts = max_attempts; 186 | } 187 | 188 | /// Get the jitter factor 189 | /// 190 | /// # Examples 191 | /// 192 | /// ```rust 193 | /// use exponential_backoff::Backoff; 194 | /// 195 | /// let mut backoff = Backoff::default(); 196 | /// assert_eq!(backoff.jitter(), 0.3); 197 | /// ``` 198 | pub fn jitter(&self) -> f32 { 199 | self.jitter 200 | } 201 | 202 | /// Set the amount of jitter per backoff. 203 | /// 204 | /// # Panics 205 | /// 206 | /// This method panics if a number smaller than `0` or larger than `1` is 207 | /// provided. 208 | /// 209 | /// # Examples 210 | /// 211 | /// ```rust 212 | /// use exponential_backoff::Backoff; 213 | /// 214 | /// let mut backoff = Backoff::default(); 215 | /// backoff.set_jitter(0.3); // default value 216 | /// backoff.set_jitter(0.0); // min value 217 | /// backoff.set_jitter(1.0); // max value 218 | /// ``` 219 | #[inline] 220 | pub fn set_jitter(&mut self, jitter: f32) { 221 | assert!( 222 | jitter >= 0f32 && jitter <= 1f32, 223 | ": jitter must be between 0 and 1." 224 | ); 225 | self.jitter = jitter; 226 | } 227 | 228 | /// Get the growth factor 229 | /// 230 | /// # Examples 231 | /// 232 | /// ```rust 233 | /// use exponential_backoff::Backoff; 234 | /// 235 | /// let mut backoff = Backoff::default(); 236 | /// assert_eq!(backoff.factor(), 2); 237 | /// ``` 238 | pub fn factor(&self) -> u32 { 239 | self.factor 240 | } 241 | 242 | /// Set the growth factor for each iteration of the backoff. 243 | /// 244 | /// # Examples 245 | /// 246 | /// ```rust 247 | /// use exponential_backoff::Backoff; 248 | /// 249 | /// let mut backoff = Backoff::default(); 250 | /// backoff.set_factor(3); 251 | /// assert_eq!(backoff.factor(), 3); 252 | /// ``` 253 | #[inline] 254 | pub fn set_factor(&mut self, factor: u32) { 255 | self.factor = factor; 256 | } 257 | 258 | /// Create an iterator. 259 | #[inline] 260 | pub fn iter(&self) -> IntoIter { 261 | IntoIter::new(self.clone()) 262 | } 263 | } 264 | 265 | /// Implements the `IntoIterator` trait for borrowed `Backoff` instances. 266 | /// 267 | /// # Examples 268 | /// 269 | /// ```rust 270 | /// use exponential_backoff::Backoff; 271 | /// use std::time::Duration; 272 | /// 273 | /// let backoff = Backoff::default(); 274 | /// let mut count = 0; 275 | /// 276 | /// for duration in &backoff { 277 | /// count += 1; 278 | /// if count > 1 { 279 | /// break; 280 | /// } 281 | /// } 282 | /// ``` 283 | impl<'b> IntoIterator for &'b Backoff { 284 | type Item = Option; 285 | type IntoIter = IntoIter; 286 | 287 | fn into_iter(self) -> Self::IntoIter { 288 | Self::IntoIter::new(self.clone()) 289 | } 290 | } 291 | 292 | /// Implements the `IntoIterator` trait for owned `Backoff` instances. 293 | /// 294 | /// # Examples 295 | /// 296 | /// ```rust 297 | /// use exponential_backoff::Backoff; 298 | /// use std::time::Duration; 299 | /// 300 | /// let backoff = Backoff::default(); 301 | /// let mut count = 0; 302 | /// 303 | /// for duration in backoff { 304 | /// count += 1; 305 | /// if count > 1 { 306 | /// break; 307 | /// } 308 | /// } 309 | /// ``` 310 | impl IntoIterator for Backoff { 311 | type Item = Option; 312 | type IntoIter = IntoIter; 313 | 314 | fn into_iter(self) -> Self::IntoIter { 315 | Self::IntoIter::new(self) 316 | } 317 | } 318 | 319 | /// Implements the `Default` trait for `Backoff`. 320 | /// 321 | /// # Examples 322 | /// 323 | /// ```rust 324 | /// use exponential_backoff::Backoff; 325 | /// use std::time::Duration; 326 | /// 327 | /// let backoff = Backoff::default(); 328 | /// assert_eq!(backoff.max_attempts(), 3); 329 | /// assert_eq!(backoff.min(), &Duration::from_millis(100)); 330 | /// assert_eq!(backoff.max(), &Duration::from_secs(10)); 331 | /// assert_eq!(backoff.jitter(), 0.3); 332 | /// assert_eq!(backoff.factor(), 2); 333 | /// ``` 334 | impl Default for Backoff { 335 | fn default() -> Self { 336 | Self { 337 | max_attempts: 3, 338 | min: Duration::from_millis(100), 339 | max: Duration::from_secs(10), 340 | jitter: 0.3, 341 | factor: 2, 342 | } 343 | } 344 | } 345 | -------------------------------------------------------------------------------- /tests/test.rs: -------------------------------------------------------------------------------- 1 | extern crate exponential_backoff; 2 | 3 | use exponential_backoff::Backoff; 4 | use std::{fs, thread, time::Duration}; 5 | 6 | #[test] 7 | fn it_doesnt_crash() -> std::io::Result<()> { 8 | let attempts = 8; 9 | let min = Duration::from_millis(10); 10 | let max = Duration::from_millis(20); 11 | 12 | for duration in &Backoff::new(attempts, min, max) { 13 | println!("duration {:?}", duration); 14 | match fs::read_to_string("README.md") { 15 | Ok(_string) => return Ok(()), 16 | Err(_) => { 17 | if let Some(duration) = duration { 18 | thread::sleep(duration); 19 | } 20 | } 21 | } 22 | } 23 | 24 | unreachable!(); 25 | } 26 | 27 | #[test] 28 | fn it_correctly_handles_max_attempts() { 29 | let attempts = 3; 30 | let min = Duration::from_millis(10); 31 | let max = Duration::from_millis(20); 32 | 33 | let mut counter = 0; 34 | let mut slept = 0; 35 | 36 | for duration in &Backoff::new(attempts, min, max) { 37 | counter += 1; 38 | if let Some(duration) = duration { 39 | thread::sleep(duration); 40 | slept += 1; 41 | } 42 | } 43 | assert_eq!(slept, attempts - 1); 44 | assert_eq!(counter, attempts); 45 | } 46 | 47 | #[test] 48 | fn it_completes_into_iter() { 49 | let attempts = 3; 50 | 51 | let min = Duration::from_millis(10); 52 | let max = Duration::from_millis(20); 53 | let mut counter = 0; 54 | let mut slept = 0; 55 | for duration in Backoff::new(attempts, min, max) { 56 | counter += 1; 57 | if let Some(duration) = duration { 58 | thread::sleep(duration); 59 | slept += 1; 60 | } 61 | } 62 | assert_eq!(slept, attempts - 1); 63 | assert_eq!(counter, attempts); 64 | } 65 | 66 | #[test] 67 | fn it_handles_max_backoff() { 68 | let attempts = u32::MAX; 69 | let min = Duration::MAX; 70 | let mut counter = 0u32; 71 | for _ in &Backoff::new(attempts, min, None) { 72 | counter += 1; 73 | if counter > 32 { 74 | break; 75 | } 76 | } 77 | } 78 | 79 | #[test] 80 | fn it_handles_zero_attempts() { 81 | let mut count = 0; 82 | let attempts = 0; 83 | for duration in &Backoff::new(attempts, Duration::from_millis(10), None) { 84 | assert!(duration.is_none()); 85 | count += 1; 86 | } 87 | assert_eq!(count, 0); 88 | } 89 | 90 | #[test] 91 | fn it_handles_no_jitter() { 92 | let mut backoff = Backoff::default(); 93 | backoff.set_jitter(0.0); 94 | 95 | // Exercise the iterator a number of times 96 | let mut durations = backoff.into_iter(); 97 | durations.next(); 98 | durations.next(); 99 | durations.next(); 100 | } 101 | 102 | #[test] 103 | fn it_has_the_right_min_value() { 104 | // Set up a backoff with predictable values 105 | let mut backoff = Backoff::new(4, Duration::from_secs(1), None); 106 | backoff.set_factor(2); 107 | backoff.set_jitter(0.0); // No jitter to make test deterministic 108 | 109 | let mut durations = backoff.into_iter(); 110 | assert_eq!( 111 | durations.next(), 112 | Some(Some(Duration::from_secs(1))), 113 | "First interval should equal the min value, not double it" 114 | ); 115 | assert_eq!( 116 | durations.next(), 117 | Some(Some(Duration::from_secs(2))), 118 | "Second interval should be min value * factor" 119 | ); 120 | assert_eq!( 121 | durations.next(), 122 | Some(Some(Duration::from_secs(4))), 123 | "Third interval should be min value * factor^2" 124 | ); 125 | } 126 | 127 | /// Tests that we uphold the invariant of ever-increasing sleep values. 128 | #[test] 129 | fn it_generates_ascending_sleep_values() { 130 | let mut backoff = Backoff::new(20, Duration::from_secs(1), None); 131 | backoff.set_factor(2); 132 | backoff.set_jitter(0.0); // No jitter to make test deterministic 133 | 134 | let mut max = Duration::from_millis(0); 135 | for duration in backoff { 136 | if let Some(duration) = duration { 137 | assert!(duration >= max); 138 | max = duration; 139 | } 140 | } 141 | } 142 | --------------------------------------------------------------------------------