backon-0.4.4/.cargo_vcs_info.json0000644000000001360000000000100122760ustar { "git": { "sha1": "7e906602a17c37bbafbd20416b65bbd74266f497" }, "path_in_vcs": "" }backon-0.4.4/.github/FUNDING.yml000064400000000000000000000000211046102023000142340ustar 00000000000000github: [Xuanwo] backon-0.4.4/.github/actions/check/action.yml000064400000000000000000000012101046102023000171350ustar 00000000000000name: 'Check' description: 'Check will do all essential checks' inputs: github_token: description: "Github Token" required: true runs: using: "composite" steps: - name: Format uses: actions-rs/cargo@v1 with: command: fmt args: --all -- --check - name: Install cargo-audit uses: actions-rs/cargo@v1 with: command: install args: cargo-audit - name: Audit dependencies uses: actions-rs/cargo@v1 with: command: audit - name: Clippy uses: actions-rs/cargo@v1 with: command: clippy args: --all-targets -- -D warnings backon-0.4.4/.github/dependabot.yml000064400000000000000000000004361046102023000152610ustar 00000000000000version: 2 updates: # Maintain dependencies for GitHub Actions - package-ecosystem: "github-actions" directory: "/" schedule: interval: "daily" # Maintain dependencies for rust - package-ecosystem: "cargo" directory: "/" schedule: interval: "daily" backon-0.4.4/.github/workflows/ci.yml000064400000000000000000000021131046102023000155760ustar 00000000000000name: CI on: [push, pull_request] concurrency: group: ${{ github.workflow }}-${{ github.ref }}-${{ github.event_name }} cancel-in-progress: true jobs: check: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: ./.github/actions/check with: github_token: ${{ secrets.GITHUB_TOKEN }} build: runs-on: ${{ matrix.os }} strategy: matrix: os: - ubuntu-latest - macos-11 - windows-latest steps: - uses: actions/checkout@v4 - uses: Swatinem/rust-cache@v2 - name: Build uses: actions-rs/cargo@v1 with: command: build unit: runs-on: ${{ matrix.os }} strategy: matrix: os: - ubuntu-latest - macos-11 - windows-latest steps: - uses: actions/checkout@v4 - uses: Swatinem/rust-cache@v2 - name: Test uses: actions-rs/cargo@v1 with: command: test args: -- --nocapture env: RUST_LOG: DEBUG RUST_BACKTRACE: full backon-0.4.4/.gitignore000064400000000000000000000000241046102023000130520ustar 00000000000000/target /Cargo.lock backon-0.4.4/.taplo.toml000064400000000000000000000026201046102023000131600ustar 00000000000000include = ["Cargo.toml", "**/*.toml"] [formatting] # Align consecutive entries vertically. align_entries = false # Append trailing commas for multi-line arrays. array_trailing_comma = true # Expand arrays to multiple lines that exceed the maximum column width. array_auto_expand = true # Collapse arrays that don't exceed the maximum column width and don't contain comments. array_auto_collapse = true # Omit white space padding from single-line arrays compact_arrays = true # Omit white space padding from the start and end of inline tables. compact_inline_tables = false # Maximum column width in characters, affects array expansion and collapse, this doesn't take whitespace into account. # Note that this is not set in stone, and works on a best-effort basis. column_width = 80 # Indent based on tables and arrays of tables and their subtables, subtables out of order are not indented. indent_tables = false # The substring that is used for indentation, should be tabs or spaces (but technically can be anything). indent_string = ' ' # Add trailing newline at the end of the file if not present. trailing_newline = true # Alphabetically reorder keys that are not separated by empty lines. reorder_keys = true # Maximum amount of allowed consecutive blank lines. This does not affect the whitespace at the end of the document, as it is always stripped. allowed_blank_lines = 2 # Use CRLF for line endings. crlf = false backon-0.4.4/CONTRIBUTING.md000064400000000000000000000006461046102023000133250ustar 00000000000000# Contributing ## Get Started This is a Rust project, so [rustup](https://rustup.rs/) is the best place to start. This is a pure rust project, so only `cargo` is needed. - `cargo check` to analyze the current package and report errors. - `cargo build` to compile the current package. - `cargo clippy` to catch common mistakes and improve code. - `cargo test` to run unit tests. - `cargo bench` to run benchmark tests. backon-0.4.4/Cargo.lock0000644000000765540000000000100102720ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "anyhow" version = "1.0.64" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9a8f622bcf6ff3df478e9deba3e03e4e04b300f8e6a139e192c05fa3490afc7" [[package]] name = "autocfg" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "backon" version = "0.4.4" dependencies = [ "anyhow", "fastrand 2.0.1", "futures-core", "pin-project", "reqwest", "tokio", ] [[package]] name = "base64" version = "0.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9475866fec1451be56a3c2400fd081ff546538961565ccb5b7142cbd22bc7a51" [[package]] name = "bitflags" version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bumpalo" version = "3.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1ad822118d20d2c234f427000d5acc36eabe1e29a348c89b63dd60b13f28e5d" [[package]] name = "bytes" version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec8a7b6a70fde80372154c65702f00a0f56f3e1c36abbc6c440484be248856db" [[package]] name = "cc" version = "1.0.73" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2fff2a6927b3bb87f9595d67196a70493f627687a71d87a0d692242c33f58c11" [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "core-foundation" version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "194a7a9e6de53fa55116934067c844d9d749312f75c6f6d0980e8c252f8c2146" dependencies = [ "core-foundation-sys", "libc", ] [[package]] name = "core-foundation-sys" version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5827cebf4670468b8772dd191856768aedcb1b0278a04f989f7766351917b9dc" [[package]] name = "encoding_rs" version = "0.8.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9852635589dc9f9ea1b6fe9f05b50ef208c85c834a562f0c6abb1c475736ec2b" dependencies = [ "cfg-if", ] [[package]] name = "equivalent" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" [[package]] name = "fastrand" version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e51093e27b0797c359783294ca4f0a911c270184cb10f85783b118614a1501be" dependencies = [ "instant", ] [[package]] name = "fastrand" version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5" [[package]] name = "fnv" version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" [[package]] name = "foreign-types" version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" dependencies = [ "foreign-types-shared", ] [[package]] name = "foreign-types-shared" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" [[package]] name = "form_urlencoded" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5fc25a87fa4fd2094bffb06925852034d90a17f0d1e05197d4956d3555752191" dependencies = [ "matches", "percent-encoding", ] [[package]] name = "futures-channel" version = "0.3.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "30bdd20c28fadd505d0fd6712cdfcb0d4b5648baf45faef7f852afb2399bb050" dependencies = [ "futures-core", ] [[package]] name = "futures-core" version = "0.3.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec90ff4d0fe1f57d600049061dc6bb68ed03c7d2fbd697274c41805dcb3f8608" [[package]] name = "futures-sink" version = "0.3.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "21b20ba5a92e727ba30e72834706623d94ac93a725410b6a6b6fbc1b07f7ba56" [[package]] name = "futures-task" version = "0.3.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6508c467c73851293f390476d4491cf4d227dbabcd4170f3bb6044959b294f1" [[package]] name = "futures-util" version = "0.3.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "44fb6cb1be61cc1d2e43b262516aafcf63b241cffdb1d3fa115f91d9c7b09c90" dependencies = [ "futures-core", "futures-task", "pin-project-lite", "pin-utils", ] [[package]] name = "h2" version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "816ec7294445779408f36fe57bc5b7fc1cf59664059096c65f905c1c61f58069" dependencies = [ "bytes", "fnv", "futures-core", "futures-sink", "futures-util", "http", "indexmap", "slab", "tokio", "tokio-util", "tracing", ] [[package]] name = "hashbrown" version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "290f1a1d9242c78d09ce40a5e87e7554ee637af1351968159f4952f028f75604" [[package]] name = "http" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "21b9ddb458710bc376481b842f5da65cdf31522de232c1ca8146abce2a358258" dependencies = [ "bytes", "fnv", "itoa", ] [[package]] name = "http-body" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1cac85db508abc24a2e48553ba12a996e87244a0395ce011e62b37158745d643" dependencies = [ "bytes", "http", ] [[package]] name = "http-body-util" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0475f8b2ac86659c21b64320d5d653f9efe42acd2a4e560073ec61a155a34f1d" dependencies = [ "bytes", "futures-core", "http", "http-body", "pin-project-lite", ] [[package]] name = "httparse" version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d897f394bad6a705d5f4104762e116a75639e470d80901eed05a860a95cb1904" [[package]] name = "hyper" version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "186548d73ac615b32a73aafe38fb4f56c0d340e110e5a200bcadbaf2e199263a" dependencies = [ "bytes", "futures-channel", "futures-util", "h2", "http", "http-body", "httparse", "itoa", "pin-project-lite", "smallvec", "tokio", "want", ] [[package]] name = "hyper-tls" version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" dependencies = [ "bytes", "http-body-util", "hyper", "hyper-util", "native-tls", "tokio", "tokio-native-tls", "tower-service", ] [[package]] name = "hyper-util" version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca38ef113da30126bbff9cd1705f9273e15d45498615d138b0c20279ac7a76aa" dependencies = [ "bytes", "futures-channel", "futures-util", "http", "http-body", "hyper", "pin-project-lite", "socket2 0.5.6", "tokio", "tower", "tower-service", "tracing", ] [[package]] name = "idna" version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "418a0a6fab821475f634efe3ccc45c013f742efe03d853e8d3355d5cb850ecf8" dependencies = [ "matches", "unicode-bidi", "unicode-normalization", ] [[package]] name = "indexmap" version = "2.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "168fb715dda47215e360912c096649d23d58bf392ac62f73919e831745e40f26" dependencies = [ "equivalent", "hashbrown", ] [[package]] name = "instant" version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" dependencies = [ "cfg-if", ] [[package]] name = "ipnet" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "879d54834c8c76457ef4293a689b2a8c59b076067ad77b15efafbb05f92a592b" [[package]] name = "itoa" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6c8af84674fe1f223a982c933a0ee1086ac4d4052aa0fb8060c12c6ad838e754" [[package]] name = "js-sys" version = "0.3.59" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "258451ab10b34f8af53416d1fdab72c22e805f0c92a1136d59470ec0b11138b2" dependencies = [ "wasm-bindgen", ] [[package]] name = "lazy_static" version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" [[package]] name = "libc" version = "0.2.153" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd" [[package]] name = "log" version = "0.4.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" dependencies = [ "cfg-if", ] [[package]] name = "matches" version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a3e378b66a060d48947b590737b30a1be76706c8dd7b8ba0f2fe3989c68a853f" [[package]] name = "memchr" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" [[package]] name = "mime" version = "0.3.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a60c7ce501c71e03a9c9c0d35b861413ae925bd979cc7a4e30d060069aaac8d" [[package]] name = "mio" version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57ee1c23c7c63b0c9250c339ffdc69255f110b298b901b9f6c82547b7b87caaf" dependencies = [ "libc", "log", "wasi", "windows-sys 0.36.1", ] [[package]] name = "native-tls" version = "0.2.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd7e2f3618557f980e0b17e8856252eee3c97fa12c54dff0ca290fb6266ca4a9" dependencies = [ "lazy_static", "libc", "log", "openssl", "openssl-probe", "openssl-sys", "schannel", "security-framework", "security-framework-sys", "tempfile", ] [[package]] name = "once_cell" version = "1.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2f7254b99e31cad77da24b08ebf628882739a608578bb1bcdfc1f9c21260d7c0" [[package]] name = "openssl" version = "0.10.41" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "618febf65336490dfcf20b73f885f5651a0c89c64c2d4a8c3662585a70bf5bd0" dependencies = [ "bitflags", "cfg-if", "foreign-types", "libc", "once_cell", "openssl-macros", "openssl-sys", ] [[package]] name = "openssl-macros" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b501e44f11665960c7e7fcf062c7d96a14ade4aa98116c004b2e37b5be7d736c" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "openssl-probe" version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" [[package]] name = "openssl-sys" version = "0.9.75" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5f9bd0c2710541a3cda73d6f9ac4f1b240de4ae261065d309dbe73d9dceb42f" dependencies = [ "autocfg", "cc", "libc", "pkg-config", "vcpkg", ] [[package]] name = "percent-encoding" version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d4fd5641d01c8f18a23da7b6fe29298ff4b55afcccdf78973b24cf3175fee32e" [[package]] name = "pin-project" version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ad29a609b6bcd67fee905812e544992d216af9d755757c05ed2d0e15a74c6ecc" dependencies = [ "pin-project-internal", ] [[package]] name = "pin-project-internal" version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "069bdb1e05adc7a8990dce9cc75370895fbe4e3d58b9b73bf1aee56359344a55" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "pin-project-lite" version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116" [[package]] name = "pin-utils" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" [[package]] name = "pkg-config" version = "0.3.25" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1df8c4ec4b0627e53bdf214615ad287367e482558cf84b109250b37464dc03ae" [[package]] name = "proc-macro2" version = "1.0.79" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e835ff2298f5721608eb1a980ecaee1aef2c132bf95ecc026a11b7bf3c01c02e" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.35" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef" dependencies = [ "proc-macro2", ] [[package]] name = "redox_syscall" version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" dependencies = [ "bitflags", ] [[package]] name = "remove_dir_all" version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7" dependencies = [ "winapi", ] [[package]] name = "reqwest" version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e6cc1e89e689536eb5aeede61520e874df5a4707df811cd5da4aa5fbb2aae19" dependencies = [ "base64", "bytes", "encoding_rs", "futures-core", "futures-util", "h2", "http", "http-body", "http-body-util", "hyper", "hyper-tls", "hyper-util", "ipnet", "js-sys", "log", "mime", "native-tls", "once_cell", "percent-encoding", "pin-project-lite", "rustls-pemfile", "serde", "serde_json", "serde_urlencoded", "sync_wrapper", "system-configuration", "tokio", "tokio-native-tls", "tower-service", "url", "wasm-bindgen", "wasm-bindgen-futures", "web-sys", "winreg", ] [[package]] name = "rustls-pemfile" version = "2.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29993a25686778eb88d4189742cd713c9bce943bc54251a33509dc63cbacf73d" dependencies = [ "base64", "rustls-pki-types", ] [[package]] name = "rustls-pki-types" version = "1.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ecd36cc4259e3e4514335c4a138c6b43171a8d61d8f5c9348f9fc7529416f247" [[package]] name = "ryu" version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4501abdff3ae82a1c1b477a17252eb69cee9e66eb915c1abaa4f44d873df9f09" [[package]] name = "schannel" version = "0.1.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "88d6731146462ea25d9244b2ed5fd1d716d25c52e4d54aa4fb0f3c4e9854dbe2" dependencies = [ "lazy_static", "windows-sys 0.36.1", ] [[package]] name = "security-framework" version = "2.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2bc1bb97804af6631813c55739f771071e0f2ed33ee20b68c86ec505d906356c" dependencies = [ "bitflags", "core-foundation", "core-foundation-sys", "libc", "security-framework-sys", ] [[package]] name = "security-framework-sys" version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0160a13a177a45bfb43ce71c01580998474f556ad854dcbca936dd2841a5c556" dependencies = [ "core-foundation-sys", "libc", ] [[package]] name = "serde" version = "1.0.144" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0f747710de3dcd43b88c9168773254e809d8ddbdf9653b84e2554ab219f17860" [[package]] name = "serde_json" version = "1.0.85" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e55a28e3aaef9d5ce0506d0a14dbba8054ddc7e499ef522dd8b26859ec9d4a44" dependencies = [ "itoa", "ryu", "serde", ] [[package]] name = "serde_urlencoded" version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" dependencies = [ "form_urlencoded", "itoa", "ryu", "serde", ] [[package]] name = "slab" version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4614a76b2a8be0058caa9dbbaf66d988527d86d003c11a94fbd335d7661edcef" dependencies = [ "autocfg", ] [[package]] name = "smallvec" version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" [[package]] name = "socket2" version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "02e2d2db9033d13a1567121ddd7a095ee144db4e1ca1b1bda3419bc0da294ebd" dependencies = [ "libc", "winapi", ] [[package]] name = "socket2" version = "0.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "05ffd9c0a93b7543e062e759284fcf5f5e3b098501104bfbdde4d404db792871" dependencies = [ "libc", "windows-sys 0.52.0", ] [[package]] name = "syn" version = "1.0.99" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "58dbef6ec655055e20b86b15a8cc6d439cca19b667537ac6a1369572d151ab13" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "sync_wrapper" version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2047c6ded9c721764247e62cd3b03c09ffc529b2ba5b10ec482ae507a4a70160" [[package]] name = "system-configuration" version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba3a3adc5c275d719af8cb4272ea1c4a6d668a777f37e115f6d11ddbc1c8e0e7" dependencies = [ "bitflags", "core-foundation", "system-configuration-sys", ] [[package]] name = "system-configuration-sys" version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a75fb188eb626b924683e3b95e3a48e63551fcfb51949de2f06a9d91dbee93c9" dependencies = [ "core-foundation-sys", "libc", ] [[package]] name = "tempfile" version = "3.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5cdb1ef4eaeeaddc8fbd371e5017057064af0911902ef36b39801f67cc6d79e4" dependencies = [ "cfg-if", "fastrand 1.9.0", "libc", "redox_syscall", "remove_dir_all", "winapi", ] [[package]] name = "tinyvec" version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50" dependencies = [ "tinyvec_macros", ] [[package]] name = "tinyvec_macros" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c" [[package]] name = "tokio" version = "1.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "89797afd69d206ccd11fb0ea560a44bbb87731d020670e79416d442919257d42" dependencies = [ "autocfg", "bytes", "libc", "memchr", "mio", "once_cell", "pin-project-lite", "socket2 0.4.7", "tokio-macros", "winapi", ] [[package]] name = "tokio-macros" version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9724f9a975fb987ef7a3cd9be0350edcbe130698af5b8f7a631e23d42d052484" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "tokio-native-tls" version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f7d995660bd2b7f8c1568414c1126076c13fbb725c40112dc0120b78eb9b717b" dependencies = [ "native-tls", "tokio", ] [[package]] name = "tokio-util" version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cc463cd8deddc3770d20f9852143d50bf6094e640b485cb2e189a2099085ff45" dependencies = [ "bytes", "futures-core", "futures-sink", "pin-project-lite", "tokio", "tracing", ] [[package]] name = "tower" version = "0.4.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8fa9be0de6cf49e536ce1851f987bd21a43b771b09473c3549a6c853db37c1c" dependencies = [ "futures-core", "futures-util", "pin-project", "pin-project-lite", "tokio", "tower-layer", "tower-service", "tracing", ] [[package]] name = "tower-layer" version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c20c8dbed6283a09604c3e69b4b7eeb54e298b8a600d4d5ecb5ad39de609f1d0" [[package]] name = "tower-service" version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52" [[package]] name = "tracing" version = "0.1.36" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2fce9567bd60a67d08a16488756721ba392f24f29006402881e43b19aac64307" dependencies = [ "cfg-if", "log", "pin-project-lite", "tracing-core", ] [[package]] name = "tracing-core" version = "0.1.29" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5aeea4303076558a00714b823f9ad67d58a3bbda1df83d8827d21193156e22f7" dependencies = [ "once_cell", ] [[package]] name = "try-lock" version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "59547bce71d9c38b83d9c0e92b6066c4253371f15005def0c30d9657f50c7642" [[package]] name = "unicode-bidi" version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "099b7128301d285f79ddd55b9a83d5e6b9e97c92e0ea0daebee7263e932de992" [[package]] name = "unicode-ident" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c4f5b37a154999a8f3f98cc23a628d850e154479cd94decf3414696e12e31aaf" [[package]] name = "unicode-normalization" version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "854cbdc4f7bc6ae19c820d44abdc3277ac3e1b2b93db20a636825d9322fb60e6" dependencies = [ "tinyvec", ] [[package]] name = "url" version = "2.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a507c383b2d33b5fc35d1861e77e6b383d158b2da5e14fe51b83dfedf6fd578c" dependencies = [ "form_urlencoded", "idna", "matches", "percent-encoding", ] [[package]] name = "vcpkg" version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" [[package]] name = "want" version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ce8a968cb1cd110d136ff8b819a556d6fb6d919363c61534f6860c7eb172ba0" dependencies = [ "log", "try-lock", ] [[package]] name = "wasi" version = "0.11.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasm-bindgen" version = "0.2.82" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc7652e3f6c4706c8d9cd54832c4a4ccb9b5336e2c3bd154d5cccfbf1c1f5f7d" dependencies = [ "cfg-if", "wasm-bindgen-macro", ] [[package]] name = "wasm-bindgen-backend" version = "0.2.82" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "662cd44805586bd52971b9586b1df85cdbbd9112e4ef4d8f41559c334dc6ac3f" dependencies = [ "bumpalo", "log", "once_cell", "proc-macro2", "quote", "syn", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-futures" version = "0.4.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fa76fb221a1f8acddf5b54ace85912606980ad661ac7a503b4570ffd3a624dad" dependencies = [ "cfg-if", "js-sys", "wasm-bindgen", "web-sys", ] [[package]] name = "wasm-bindgen-macro" version = "0.2.82" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b260f13d3012071dfb1512849c033b1925038373aea48ced3012c09df952c602" dependencies = [ "quote", "wasm-bindgen-macro-support", ] [[package]] name = "wasm-bindgen-macro-support" version = "0.2.82" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5be8e654bdd9b79216c2929ab90721aa82faf65c48cdf08bdc4e7f51357b80da" dependencies = [ "proc-macro2", "quote", "syn", "wasm-bindgen-backend", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" version = "0.2.82" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6598dd0bd3c7d51095ff6531a5b23e02acdc81804e30d8f07afb77b7215a140a" [[package]] name = "web-sys" version = "0.3.59" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed055ab27f941423197eb86b2035720b1a3ce40504df082cac2ecc6ed73335a1" dependencies = [ "js-sys", "wasm-bindgen", ] [[package]] name = "winapi" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" dependencies = [ "winapi-i686-pc-windows-gnu", "winapi-x86_64-pc-windows-gnu", ] [[package]] name = "winapi-i686-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "windows-sys" version = "0.36.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea04155a16a59f9eab786fe12a4a450e75cdb175f9e0d80da1e17db09f55b8d2" dependencies = [ "windows_aarch64_msvc 0.36.1", "windows_i686_gnu 0.36.1", "windows_i686_msvc 0.36.1", "windows_x86_64_gnu 0.36.1", "windows_x86_64_msvc 0.36.1", ] [[package]] name = "windows-sys" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" dependencies = [ "windows-targets 0.48.5", ] [[package]] name = "windows-sys" version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ "windows-targets 0.52.4", ] [[package]] name = "windows-targets" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" dependencies = [ "windows_aarch64_gnullvm 0.48.5", "windows_aarch64_msvc 0.48.5", "windows_i686_gnu 0.48.5", "windows_i686_msvc 0.48.5", "windows_x86_64_gnu 0.48.5", "windows_x86_64_gnullvm 0.48.5", "windows_x86_64_msvc 0.48.5", ] [[package]] name = "windows-targets" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7dd37b7e5ab9018759f893a1952c9420d060016fc19a472b4bb20d1bdd694d1b" dependencies = [ "windows_aarch64_gnullvm 0.52.4", "windows_aarch64_msvc 0.52.4", "windows_i686_gnu 0.52.4", "windows_i686_msvc 0.52.4", "windows_x86_64_gnu 0.52.4", "windows_x86_64_gnullvm 0.52.4", "windows_x86_64_msvc 0.52.4", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" [[package]] name = "windows_aarch64_gnullvm" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bcf46cf4c365c6f2d1cc93ce535f2c8b244591df96ceee75d8e83deb70a9cac9" [[package]] name = "windows_aarch64_msvc" version = "0.36.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9bb8c3fd39ade2d67e9874ac4f3db21f0d710bee00fe7cab16949ec184eeaa47" [[package]] name = "windows_aarch64_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" [[package]] name = "windows_aarch64_msvc" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da9f259dd3bcf6990b55bffd094c4f7235817ba4ceebde8e6d11cd0c5633b675" [[package]] name = "windows_i686_gnu" version = "0.36.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "180e6ccf01daf4c426b846dfc66db1fc518f074baa793aa7d9b9aaeffad6a3b6" [[package]] name = "windows_i686_gnu" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" [[package]] name = "windows_i686_gnu" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b474d8268f99e0995f25b9f095bc7434632601028cf86590aea5c8a5cb7801d3" [[package]] name = "windows_i686_msvc" version = "0.36.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2e7917148b2812d1eeafaeb22a97e4813dfa60a3f8f78ebe204bcc88f12f024" [[package]] name = "windows_i686_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" [[package]] name = "windows_i686_msvc" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1515e9a29e5bed743cb4415a9ecf5dfca648ce85ee42e15873c3cd8610ff8e02" [[package]] name = "windows_x86_64_gnu" version = "0.36.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4dcd171b8776c41b97521e5da127a2d86ad280114807d0b2ab1e462bc764d9e1" [[package]] name = "windows_x86_64_gnu" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" [[package]] name = "windows_x86_64_gnu" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5eee091590e89cc02ad514ffe3ead9eb6b660aedca2183455434b93546371a03" [[package]] name = "windows_x86_64_gnullvm" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" [[package]] name = "windows_x86_64_gnullvm" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ca79f2451b49fa9e2af39f0747fe999fcda4f5e241b2898624dca97a1f2177" [[package]] name = "windows_x86_64_msvc" version = "0.36.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c811ca4a8c853ef420abd8592ba53ddbbac90410fab6903b3e79972a631f7680" [[package]] name = "windows_x86_64_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" [[package]] name = "windows_x86_64_msvc" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32b752e52a2da0ddfbdbcc6fceadfeede4c939ed16d13e648833a61dfb611ed8" [[package]] name = "winreg" version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a277a57398d4bfa075df44f501a17cfdf8542d224f0d36095a2adc7aee4ef0a5" dependencies = [ "cfg-if", "windows-sys 0.48.0", ] backon-0.4.4/Cargo.toml0000644000000021520000000000100102740ustar # 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 = "2021" name = "backon" version = "0.4.4" authors = ["Xuanwo "] description = "Retry with backoff without effort." documentation = "https://docs.rs/backon" readme = "README.md" license = "Apache-2.0" repository = "https://github.com/Xuanwo/backon" [dependencies.fastrand] version = "2.0.0" [dependencies.futures-core] version = "0.3.26" [dependencies.pin-project] version = "1" [dependencies.tokio] version = "1" features = ["time"] [dev-dependencies.anyhow] version = "1" [dev-dependencies.reqwest] version = "0.12" [dev-dependencies.tokio] version = "1" features = [ "time", "rt", "macros", "sync", ] backon-0.4.4/Cargo.toml.orig000064400000000000000000000007751046102023000137660ustar 00000000000000[package] authors = ["Xuanwo "] description = "Retry with backoff without effort." documentation = "https://docs.rs/backon" edition = "2021" license = "Apache-2.0" name = "backon" repository = "https://github.com/Xuanwo/backon" version = "0.4.4" [dependencies] fastrand = "2.0.0" futures-core = "0.3.26" pin-project = "1" tokio = { version = "1", features = ["time"] } [dev-dependencies] anyhow = "1" reqwest = "0.12" tokio = { version = "1", features = ["time", "rt", "macros", "sync"] } backon-0.4.4/LICENSE000064400000000000000000000261161046102023000121010ustar 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 APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2021 Datafuse Labs Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.backon-0.4.4/README.md000064400000000000000000000037751046102023000123610ustar 00000000000000# backon   [![Build Status]][actions] [![Latest Version]][crates.io] [![](https://img.shields.io/discord/1111711408875393035?logo=discord&label=discord)](https://discord.gg/8ARnvtJePD) [Build Status]: https://img.shields.io/github/actions/workflow/status/Xuanwo/backon/ci.yml?branch=main [actions]: https://github.com/Xuanwo/backon/actions?query=branch%3Amain [Latest Version]: https://img.shields.io/crates/v/backon.svg [crates.io]: https://crates.io/crates/backon Retry with backoff without effort. --- The opposite backoff implementation of the popular [backoff](https://docs.rs/backoff). - Newer: developed by Rust edition 2021 and latest stable. - Cleaner: Iterator based abstraction, easy to use, customization friendly. - Easier: Trait based implementations, works like a native function provided by closures. ## Quick Start Retry a blocking function. ```rust use anyhow::Result; use backon::BlockingRetryable; use backon::ExponentialBuilder; fn fetch() -> Result { Ok("hello, world!".to_string()) } fn main() -> Result<()> { let content = fetch.retry(&ExponentialBuilder::default()).call()?; println!("fetch succeeded: {}", content); Ok(()) } ``` Retry an async function. ```rust use anyhow::Result; use backon::ExponentialBuilder; use backon::Retryable; async fn fetch() -> Result { Ok(reqwest::get("https://www.rust-lang.org").await?.text().await?) } #[tokio::main] async fn main() -> Result<()> { let content = fetch.retry(&ExponentialBuilder::default()).await?; println!("fetch succeeded: {}", content); Ok(()) } ``` ## Contributing Check out the [CONTRIBUTING.md](./CONTRIBUTING.md) guide for more details on getting started with contributing to this project. ## Getting help Submit [issues](https://github.com/Xuanwo/backon/issues/new/choose) for bug report or asking questions in [discussion](https://github.com/Xuanwo/backon/discussions/new?category=q-a). #### License Licensed under Apache License, Version 2.0. backon-0.4.4/examples/async.rs000064400000000000000000000011031046102023000143620ustar 00000000000000use anyhow::Result; use backon::ExponentialBuilder; use backon::Retryable; async fn fetch() -> Result { let response = reqwest::get("https://httpbingo.org/unstable?failure_rate=0.7").await?; if !response.status().is_success() { println!("{}", response.status()); anyhow::bail!("some kind of error"); } let text = response.text().await?; Ok(text) } #[tokio::main(flavor = "current_thread")] async fn main() -> Result<()> { let _ = fetch.retry(&ExponentialBuilder::default()).await?; println!("fetch succeeded"); Ok(()) } backon-0.4.4/examples/blocking.rs000064400000000000000000000004671046102023000150510ustar 00000000000000use anyhow::Result; use backon::BlockingRetryable; use backon::ExponentialBuilder; fn fetch() -> Result { Ok("hello, world!".to_string()) } fn main() -> Result<()> { let content = fetch.retry(&ExponentialBuilder::default()).call()?; println!("fetch succeeded: {}", content); Ok(()) } backon-0.4.4/examples/closure.rs000064400000000000000000000005011046102023000147220ustar 00000000000000use anyhow::Result; use backon::BlockingRetryable; use backon::ExponentialBuilder; fn main() -> Result<()> { let var = 42; // `f` can use input variables let f = || Ok::(var); let result = f.retry(&ExponentialBuilder::default()).call()?; println!("var = {result}"); Ok(()) } backon-0.4.4/rust-toolchain.toml000064400000000000000000000001021046102023000147270ustar 00000000000000[toolchain] channel = "stable" components = ["rustfmt", "clippy"] backon-0.4.4/rustfmt.toml000064400000000000000000000002211046102023000134620ustar 00000000000000edition = "2021" reorder_imports = true # format_code_in_doc_comments = true # imports_granularity = "Item" # group_imports = "StdExternalCrate" backon-0.4.4/src/backoff.rs000064400000000000000000000013451046102023000136210ustar 00000000000000use std::fmt::Debug; use std::time::Duration; /// BackoffBuilder is used to build a new backoff. pub trait BackoffBuilder: Clone + Debug + Send + Sync + Unpin { /// The associated backoff that returned by this builder. type Backoff: Backoff; /// Builder a new backoff via builder. fn build(&self) -> Self::Backoff; } /// Backoff is an [`Iterator`] that returns [`Duration`]. /// /// - `Some(Duration)` means caller need to `sleep(Duration)` and retry the same request /// - `None` means we have reaching the limits, caller needs to return current error instead. pub trait Backoff: Iterator + Send + Sync + Unpin {} impl Backoff for T where T: Iterator + Debug + Send + Sync + Unpin {} backon-0.4.4/src/blocking_retry.rs000064400000000000000000000176041046102023000152500ustar 00000000000000use std::thread; use std::time::Duration; use crate::backoff::BackoffBuilder; use crate::Backoff; /// BlockingRetryable will add retry support for functions. /// /// For example: /// /// - Functions without extra args: /// /// ```ignore /// fn fetch() -> Result { /// Ok("hello, world!".to_string()) /// } /// ``` /// /// - Closures /// /// ```ignore /// || { /// Ok("hello, world!".to_string()) /// } /// ``` /// /// # Example /// /// ```no_run /// use anyhow::Result; /// use backon::BlockingRetryable; /// use backon::ExponentialBuilder; /// /// fn fetch() -> Result { /// Ok("hello, world!".to_string()) /// } /// /// fn main() -> Result<()> { /// let content = fetch.retry(&ExponentialBuilder::default()).call()?; /// println!("fetch succeeded: {}", content); /// /// Ok(()) /// } /// ``` pub trait BlockingRetryable Result> { /// Generate a new retry fn retry(self, builder: &B) -> BlockingRetry; } impl BlockingRetryable for F where B: BackoffBuilder, F: FnMut() -> Result, { fn retry(self, builder: &B) -> BlockingRetry { BlockingRetry::new(self, builder.build()) } } /// Retry struct generated by [`Retryable`]. pub struct BlockingRetry< B: Backoff, T, E, F: FnMut() -> Result, RF = fn(&E) -> bool, NF = fn(&E, Duration), > { backoff: B, retryable: RF, notify: NF, f: F, } impl BlockingRetry where B: Backoff, F: FnMut() -> Result, { /// Create a new retry. fn new(f: F, backoff: B) -> Self { BlockingRetry { backoff, retryable: |_: &E| true, notify: |_: &E, _: Duration| {}, f, } } } impl BlockingRetry where B: Backoff, F: FnMut() -> Result, RF: FnMut(&E) -> bool, NF: FnMut(&E, Duration), { /// Set the conditions for retrying. /// /// If not specified, we treat all errors as retryable. /// /// # Examples /// /// ```no_run /// use anyhow::Result; /// use backon::BlockingRetryable; /// use backon::ExponentialBuilder; /// /// fn fetch() -> Result { /// Ok("hello, world!".to_string()) /// } /// /// fn main() -> Result<()> { /// let retry = fetch /// .retry(&ExponentialBuilder::default()) /// .when(|e| e.to_string() == "EOF"); /// let content = retry.call()?; /// println!("fetch succeeded: {}", content); /// /// Ok(()) /// } /// ``` pub fn when bool>(self, retryable: RN) -> BlockingRetry { BlockingRetry { backoff: self.backoff, retryable, notify: self.notify, f: self.f, } } /// Set to notify for everything retrying. /// /// If not specified, this is a no-op. /// /// # Examples /// /// ```no_run /// use std::time::Duration; /// /// use anyhow::Result; /// use backon::BlockingRetryable; /// use backon::ExponentialBuilder; /// /// fn fetch() -> Result { /// Ok("hello, world!".to_string()) /// } /// /// fn main() -> Result<()> { /// let retry = fetch.retry(&ExponentialBuilder::default()).notify( /// |err: &anyhow::Error, dur: Duration| { /// println!("retrying error {:?} with sleeping {:?}", err, dur); /// }, /// ); /// let content = retry.call()?; /// println!("fetch succeeded: {}", content); /// /// Ok(()) /// } /// ``` pub fn notify(self, notify: NN) -> BlockingRetry { BlockingRetry { backoff: self.backoff, retryable: self.retryable, notify, f: self.f, } } /// Call the retried function. /// /// TODO: implment [`std::ops::FnOnce`] after it stable. pub fn call(mut self) -> Result { loop { let result = (self.f)(); match result { Ok(v) => return Ok(v), Err(err) => { if !(self.retryable)(&err) { return Err(err); } match self.backoff.next() { None => return Err(err), Some(dur) => { (self.notify)(&err, dur); thread::sleep(dur); } } } } } } } #[cfg(test)] mod tests { use std::sync::Mutex; use std::time::Duration; use super::*; use crate::ExponentialBuilder; fn always_error() -> anyhow::Result<()> { Err(anyhow::anyhow!("test_query meets error")) } #[test] fn test_retry() -> anyhow::Result<()> { let result = always_error .retry(&ExponentialBuilder::default().with_min_delay(Duration::from_millis(1))) .call(); assert!(result.is_err()); assert_eq!("test_query meets error", result.unwrap_err().to_string()); Ok(()) } #[test] fn test_retry_with_not_retryable_error() -> anyhow::Result<()> { let error_times = Mutex::new(0); let f = || { let mut x = error_times.lock().unwrap(); *x += 1; Err::<(), anyhow::Error>(anyhow::anyhow!("not retryable")) }; let backoff = ExponentialBuilder::default().with_min_delay(Duration::from_millis(1)); let result = f .retry(&backoff) // Only retry If error message is `retryable` .when(|e| e.to_string() == "retryable") .call(); assert!(result.is_err()); assert_eq!("not retryable", result.unwrap_err().to_string()); // `f` always returns error "not retryable", so it should be executed // only once. assert_eq!(*error_times.lock().unwrap(), 1); Ok(()) } #[test] fn test_retry_with_retryable_error() -> anyhow::Result<()> { let error_times = Mutex::new(0); let f = || { println!("I have been called!"); let mut x = error_times.lock().unwrap(); *x += 1; Err::<(), anyhow::Error>(anyhow::anyhow!("retryable")) }; let backoff = ExponentialBuilder::default().with_min_delay(Duration::from_millis(1)); let result = f .retry(&backoff) // Only retry If error message is `retryable` .when(|e| e.to_string() == "retryable") .call(); assert!(result.is_err()); assert_eq!("retryable", result.unwrap_err().to_string()); // `f` always returns error "retryable", so it should be executed // 4 times (retry 3 times). assert_eq!(*error_times.lock().unwrap(), 4); Ok(()) } #[test] fn test_fn_mut_when_and_notify() -> anyhow::Result<()> { let mut calls_retryable: Vec<()> = vec![]; let mut calls_notify: Vec<()> = vec![]; let f = || Err::<(), anyhow::Error>(anyhow::anyhow!("retryable")); let backoff = ExponentialBuilder::default().with_min_delay(Duration::from_millis(1)); let result = f .retry(&backoff) .when(|_| { calls_retryable.push(()); true }) .notify(|_, _| { calls_notify.push(()); }) .call(); assert!(result.is_err()); assert_eq!("retryable", result.unwrap_err().to_string()); // `f` always returns error "retryable", so it should be executed // 4 times (retry 3 times). assert_eq!(calls_retryable.len(), 4); assert_eq!(calls_notify.len(), 3); Ok(()) } } backon-0.4.4/src/blocking_retry_with_context.rs000064400000000000000000000114061046102023000200410ustar 00000000000000use std::thread; use std::time::Duration; use crate::backoff::BackoffBuilder; use crate::Backoff; /// BlockingRetryableWithContext will add retry support for functions. pub trait BlockingRetryableWithContext< B: BackoffBuilder, T, E, Ctx, F: FnMut(Ctx) -> (Ctx, Result), > { /// Generate a new retry fn retry(self, builder: &B) -> BlockingRetry; } impl BlockingRetryableWithContext for F where B: BackoffBuilder, F: FnMut(Ctx) -> (Ctx, Result), { fn retry(self, builder: &B) -> BlockingRetry { BlockingRetry::new(self, builder.build()) } } /// Retry struct generated by [`Retryable`]. pub struct BlockingRetry< B: Backoff, T, E, Ctx, F: FnMut(Ctx) -> (Ctx, Result), RF = fn(&E) -> bool, NF = fn(&E, Duration), > { backoff: B, retryable: RF, notify: NF, f: F, ctx: Option, } impl BlockingRetry where B: Backoff, F: FnMut(Ctx) -> (Ctx, Result), { /// Create a new retry. fn new(f: F, backoff: B) -> Self { BlockingRetry { backoff, retryable: |_: &E| true, notify: |_: &E, _: Duration| {}, f, ctx: None, } } } impl BlockingRetry where B: Backoff, F: FnMut(Ctx) -> (Ctx, Result), RF: FnMut(&E) -> bool, NF: FnMut(&E, Duration), { /// Set the context for retrying. pub fn context(self, context: Ctx) -> BlockingRetry { BlockingRetry { backoff: self.backoff, retryable: self.retryable, notify: self.notify, f: self.f, ctx: Some(context), } } /// Set the conditions for retrying. /// /// If not specified, we treat all errors as retryable. pub fn when bool>( self, retryable: RN, ) -> BlockingRetry { BlockingRetry { backoff: self.backoff, retryable, notify: self.notify, f: self.f, ctx: self.ctx, } } /// Set to notify for everything retrying. /// /// If not specified, this is a no-op. pub fn notify( self, notify: NN, ) -> BlockingRetry { BlockingRetry { backoff: self.backoff, retryable: self.retryable, notify, f: self.f, ctx: self.ctx, } } /// Call the retried function. /// /// TODO: implment [`std::ops::FnOnce`] after it stable. pub fn call(mut self) -> (Ctx, Result) { let mut ctx = self.ctx.take().expect("context must be valid"); loop { let (xctx, result) = (self.f)(ctx); // return ctx ownership back ctx = xctx; match result { Ok(v) => return (ctx, Ok(v)), Err(err) => { if !(self.retryable)(&err) { return (ctx, Err(err)); } match self.backoff.next() { None => return (ctx, Err(err)), Some(dur) => { (self.notify)(&err, dur); thread::sleep(dur); } } } } } } } #[cfg(test)] mod tests { use std::time::Duration; use anyhow::anyhow; use std::sync::Mutex; use super::*; use crate::exponential::ExponentialBuilder; use anyhow::Result; struct Test; impl Test { fn hello(&mut self) -> Result { Err(anyhow!("not retryable")) } } #[test] fn test_retry_with_not_retryable_error() -> Result<()> { let error_times = Mutex::new(0); let test = Test; let backoff = ExponentialBuilder::default().with_min_delay(Duration::from_millis(1)); let (_, result) = { |mut v: Test| { let mut x = error_times.lock().unwrap(); *x += 1; let res = v.hello(); (v, res) } } .retry(&backoff) .context(test) // Only retry If error message is `retryable` .when(|e| e.to_string() == "retryable") .call(); assert!(result.is_err()); assert_eq!("not retryable", result.unwrap_err().to_string()); // `f` always returns error "not retryable", so it should be executed // only once. assert_eq!(*error_times.lock().unwrap(), 1); Ok(()) } } backon-0.4.4/src/constant.rs000064400000000000000000000100561046102023000140560ustar 00000000000000use std::time::Duration; use crate::backoff::BackoffBuilder; /// ConstantBuilder is used to build [`ConstantBackoff`] /// /// # Default /// /// - delay: 1s /// - max times: 3 /// /// # Examples /// /// ```no_run /// use anyhow::Result; /// use backon::ConstantBuilder; /// use backon::Retryable; /// /// async fn fetch() -> Result { /// Ok(reqwest::get("https://www.rust-lang.org") /// .await? /// .text() /// .await?) /// } /// /// #[tokio::main(flavor = "current_thread")] /// async fn main() -> Result<()> { /// let content = fetch.retry(&ConstantBuilder::default()).await?; /// println!("fetch succeeded: {}", content); /// /// Ok(()) /// } /// ``` #[derive(Debug, Clone)] pub struct ConstantBuilder { delay: Duration, max_times: Option, jitter: bool, } impl Default for ConstantBuilder { fn default() -> Self { Self { delay: Duration::from_secs(1), max_times: Some(3), jitter: false, } } } impl ConstantBuilder { /// Set delay of current backoff. pub fn with_delay(mut self, delay: Duration) -> Self { self.delay = delay; self } /// Set max times of current backoff. pub fn with_max_times(mut self, max_times: usize) -> Self { self.max_times = Some(max_times); self } /// Set jitter on pub fn with_jitter(mut self) -> Self { self.jitter = true; self } } impl BackoffBuilder for ConstantBuilder { type Backoff = ConstantBackoff; fn build(&self) -> Self::Backoff { ConstantBackoff { delay: self.delay, max_times: self.max_times, attempts: 0, jitter: self.jitter, } } } /// ConstantBackoff provides backoff with constant delay and limited times. #[derive(Debug)] pub struct ConstantBackoff { delay: Duration, max_times: Option, attempts: usize, jitter: bool, } impl Default for ConstantBackoff { fn default() -> Self { Self { delay: Duration::from_secs(1), max_times: Some(3), attempts: 0, jitter: false, } } } impl Iterator for ConstantBackoff { type Item = Duration; fn next(&mut self) -> Option { let delay = || match self.jitter { true => self.delay + self.delay.mul_f32(fastrand::f32()), false => self.delay, }; match self.max_times { None => Some(delay()), Some(max_times) => { if self.attempts >= max_times { None } else { self.attempts += 1; Some(delay()) } } } } } #[cfg(test)] mod tests { use std::time::Duration; use crate::backoff::BackoffBuilder; use crate::constant::ConstantBuilder; #[test] fn test_constant_default() { let mut exp = ConstantBuilder::default().build(); assert_eq!(Some(Duration::from_secs(1)), exp.next()); assert_eq!(Some(Duration::from_secs(1)), exp.next()); assert_eq!(Some(Duration::from_secs(1)), exp.next()); assert_eq!(None, exp.next()); } #[test] fn test_constant_with_delay() { let mut exp = ConstantBuilder::default() .with_delay(Duration::from_secs(2)) .build(); assert_eq!(Some(Duration::from_secs(2)), exp.next()); assert_eq!(Some(Duration::from_secs(2)), exp.next()); assert_eq!(Some(Duration::from_secs(2)), exp.next()); assert_eq!(None, exp.next()); } #[test] fn test_constant_with_times() { let mut exp = ConstantBuilder::default().with_max_times(1).build(); assert_eq!(Some(Duration::from_secs(1)), exp.next()); assert_eq!(None, exp.next()); } #[test] fn test_constant_with_jitter() { let mut it = ConstantBuilder::default().with_jitter().build(); let dur = it.next().unwrap(); fastrand::seed(7); assert!(dur > Duration::from_secs(1)); } } backon-0.4.4/src/exponential.rs000064400000000000000000000217701046102023000145600ustar 00000000000000use std::time::Duration; use crate::backoff::BackoffBuilder; /// ExponentialBuilder is used to build a [`ExponentialBackoff`] /// /// # Default /// /// - jitter: false /// - factor: 2 /// - min_delay: 1s /// - max_delay: 60s /// - max_times: 3 /// /// # Examples /// /// ```no_run /// use anyhow::Result; /// use backon::ExponentialBuilder; /// use backon::Retryable; /// /// async fn fetch() -> Result { /// Ok(reqwest::get("https://www.rust-lang.org") /// .await? /// .text() /// .await?) /// } /// /// #[tokio::main(flavor = "current_thread")] /// async fn main() -> Result<()> { /// let content = fetch.retry(&ExponentialBuilder::default()).await?; /// println!("fetch succeeded: {}", content); /// /// Ok(()) /// } /// ``` #[derive(Debug, Clone)] pub struct ExponentialBuilder { jitter: bool, factor: f32, min_delay: Duration, max_delay: Option, max_times: Option, } impl Default for ExponentialBuilder { fn default() -> Self { Self { jitter: false, factor: 2.0, min_delay: Duration::from_secs(1), max_delay: Some(Duration::from_secs(60)), max_times: Some(3), } } } impl ExponentialBuilder { /// Set jitter of current backoff. /// /// If jitter is enabled, ExponentialBackoff will add a random jitter in `[0, min_delay) /// to current delay. pub fn with_jitter(mut self) -> Self { self.jitter = true; self } /// Set factor of current backoff. /// /// # Panics /// /// This function will panic if input factor smaller than `1.0`. pub fn with_factor(mut self, factor: f32) -> Self { debug_assert!(factor >= 1.0, "invalid factor that lower than 1"); self.factor = factor; self } /// Set min_delay of current backoff. pub fn with_min_delay(mut self, min_delay: Duration) -> Self { self.min_delay = min_delay; self } /// Set max_delay of current backoff. /// /// Delay will not increasing if current delay is larger than max_delay. pub fn with_max_delay(mut self, max_delay: Duration) -> Self { self.max_delay = Some(max_delay); self } /// Set max_times of current backoff. /// /// Backoff will return `None` if max times is reaching. pub fn with_max_times(mut self, max_times: usize) -> Self { self.max_times = Some(max_times); self } } impl BackoffBuilder for ExponentialBuilder { type Backoff = ExponentialBackoff; fn build(&self) -> Self::Backoff { ExponentialBackoff { jitter: self.jitter, factor: self.factor, min_delay: self.min_delay, max_delay: self.max_delay, max_times: self.max_times, current_delay: None, attempts: 0, } } } /// Exponential backoff implementation. #[derive(Debug)] pub struct ExponentialBackoff { jitter: bool, factor: f32, min_delay: Duration, max_delay: Option, max_times: Option, current_delay: Option, attempts: usize, } impl Iterator for ExponentialBackoff { type Item = Duration; fn next(&mut self) -> Option { if self.attempts >= self.max_times.unwrap_or(usize::MAX) { return None; } self.attempts += 1; let mut tmp_cur = match self.current_delay { None => { // If current_delay is None, it's must be the first time to retry. self.current_delay = Some(self.min_delay); self.min_delay } Some(mut cur) => { // If current delay larger than max delay, we should stop increment anymore. if let Some(max_delay) = self.max_delay { if cur < max_delay { cur = saturating_mul(cur, self.factor); } if cur > max_delay { cur = max_delay; } } else { cur = saturating_mul(cur, self.factor); } self.current_delay = Some(cur); cur } }; // If jitter is enabled, add random jitter based on min delay. if self.jitter { tmp_cur = tmp_cur.saturating_add(self.min_delay.mul_f32(fastrand::f32())); } Some(tmp_cur) } } pub(crate) fn saturating_mul(d: Duration, rhs: f32) -> Duration { match Duration::try_from_secs_f32(rhs * d.as_secs_f32()) { Ok(v) => v, Err(_) => Duration::MAX, } } #[cfg(test)] mod tests { use std::time::Duration; use crate::backoff::BackoffBuilder; use crate::exponential::ExponentialBuilder; #[test] fn test_exponential_default() { let mut exp = ExponentialBuilder::default().build(); assert_eq!(Some(Duration::from_secs(1)), exp.next()); assert_eq!(Some(Duration::from_secs(2)), exp.next()); assert_eq!(Some(Duration::from_secs(4)), exp.next()); assert_eq!(None, exp.next()); } #[test] fn test_exponential_factor() { let mut exp = ExponentialBuilder::default().with_factor(1.5).build(); assert_eq!(Some(Duration::from_secs_f32(1.0)), exp.next()); assert_eq!(Some(Duration::from_secs_f32(1.5)), exp.next()); assert_eq!(Some(Duration::from_secs_f32(2.25)), exp.next()); assert_eq!(None, exp.next()); } #[test] fn test_exponential_jitter() { let mut exp = ExponentialBuilder::default().with_jitter().build(); let v = exp.next().expect("value must valid"); assert!(v >= Duration::from_secs(1), "current: {v:?}"); assert!(v < Duration::from_secs(2), "current: {v:?}"); let v = exp.next().expect("value must valid"); assert!(v >= Duration::from_secs(2), "current: {v:?}"); assert!(v < Duration::from_secs(4), "current: {v:?}"); let v = exp.next().expect("value must valid"); assert!(v >= Duration::from_secs(4), "current: {v:?}"); assert!(v < Duration::from_secs(8), "current: {v:?}"); assert_eq!(None, exp.next()); } #[test] fn test_exponential_min_delay() { let mut exp = ExponentialBuilder::default() .with_min_delay(Duration::from_millis(500)) .build(); assert_eq!(Some(Duration::from_millis(500)), exp.next()); assert_eq!(Some(Duration::from_secs(1)), exp.next()); assert_eq!(Some(Duration::from_secs(2)), exp.next()); assert_eq!(None, exp.next()); } #[test] fn test_exponential_max_delay_with_default() { let mut exp = ExponentialBuilder::default() .with_max_delay(Duration::from_secs(2)) .build(); assert_eq!(Some(Duration::from_secs(1)), exp.next()); assert_eq!(Some(Duration::from_secs(2)), exp.next()); assert_eq!(Some(Duration::from_secs(2)), exp.next()); assert_eq!(None, exp.next()); } #[test] fn test_exponential_max_delay_without_default_1() { let mut exp = ExponentialBuilder { jitter: false, factor: 10_000_000_000_f32, min_delay: Duration::from_secs(1), max_delay: None, max_times: None, } .build(); assert_eq!(Some(Duration::from_secs(1)), exp.next()); assert_eq!(Some(Duration::from_secs(10_000_000_000)), exp.next()); assert_eq!(Some(Duration::MAX), exp.next()); assert_eq!(Some(Duration::MAX), exp.next()); } #[test] fn test_exponential_max_delay_without_default_2() { let mut exp = ExponentialBuilder { jitter: true, factor: 10_000_000_000_f32, min_delay: Duration::from_secs(10_000_000_000), max_delay: None, max_times: Some(2), } .build(); let v = exp.next().expect("value must valid"); assert!(v >= Duration::from_secs(10_000_000_000), "current: {v:?}"); assert!(v < Duration::from_secs(20_000_000_000), "current: {v:?}"); assert_eq!(Some(Duration::MAX), exp.next()); assert_eq!(None, exp.next()); } #[test] fn test_exponential_max_delay_without_default_3() { let mut exp = ExponentialBuilder { jitter: false, factor: 10_000_000_000_f32, min_delay: Duration::from_secs(10_000_000_000), max_delay: Some(Duration::from_secs(60_000_000_000)), max_times: Some(3), } .build(); assert_eq!(Some(Duration::from_secs(10_000_000_000)), exp.next()); assert_eq!(Some(Duration::from_secs(60_000_000_000)), exp.next()); assert_eq!(Some(Duration::from_secs(60_000_000_000)), exp.next()); assert_eq!(None, exp.next()); } #[test] fn test_exponential_max_times() { let mut exp = ExponentialBuilder::default().with_max_times(1).build(); assert_eq!(Some(Duration::from_secs(1)), exp.next()); assert_eq!(None, exp.next()); } } backon-0.4.4/src/fibonacci.rs000064400000000000000000000154041046102023000141440ustar 00000000000000use std::time::Duration; use crate::backoff::BackoffBuilder; /// FibonacciBuilder is used to build a [`FibonacciBackoff`] /// /// # Default /// /// - jitter: false /// - min_delay: 1s /// - max_delay: 60s /// - max_times: 3 /// /// # Examples /// /// ```no_run /// use anyhow::Result; /// use backon::FibonacciBuilder; /// use backon::Retryable; /// /// async fn fetch() -> Result { /// Ok(reqwest::get("https://www.rust-lang.org") /// .await? /// .text() /// .await?) /// } /// /// #[tokio::main(flavor = "current_thread")] /// async fn main() -> Result<()> { /// let content = fetch.retry(&FibonacciBuilder::default()).await?; /// println!("fetch succeeded: {}", content); /// /// Ok(()) /// } /// ``` #[derive(Debug, Clone)] pub struct FibonacciBuilder { jitter: bool, min_delay: Duration, max_delay: Option, max_times: Option, } impl Default for FibonacciBuilder { fn default() -> Self { Self { jitter: false, min_delay: Duration::from_secs(1), max_delay: Some(Duration::from_secs(60)), max_times: Some(3), } } } impl FibonacciBuilder { /// Set jitter of current backoff. /// /// If jitter is enabled, FibonacciBackoff will add a random jitter in `[0, min_delay) /// to current delay. pub fn with_jitter(mut self) -> Self { self.jitter = true; self } /// Set min_delay of current backoff. pub fn with_min_delay(mut self, min_delay: Duration) -> Self { self.min_delay = min_delay; self } /// Set max_delay of current backoff. /// /// Delay will not increasing if current delay is larger than max_delay. pub fn with_max_delay(mut self, max_delay: Duration) -> Self { self.max_delay = Some(max_delay); self } /// Set max_times of current backoff. /// /// Backoff will return `None` if max times is reaching. pub fn with_max_times(mut self, max_times: usize) -> Self { self.max_times = Some(max_times); self } } impl BackoffBuilder for FibonacciBuilder { type Backoff = FibonacciBackoff; fn build(&self) -> Self::Backoff { FibonacciBackoff { jitter: self.jitter, min_delay: self.min_delay, max_delay: self.max_delay, max_times: self.max_times, previous_delay: None, current_delay: None, attempts: 0, } } } /// Fibonacci backoff implementation. #[derive(Debug)] pub struct FibonacciBackoff { jitter: bool, min_delay: Duration, max_delay: Option, max_times: Option, previous_delay: Option, current_delay: Option, attempts: usize, } impl Iterator for FibonacciBackoff { type Item = Duration; fn next(&mut self) -> Option { if self.attempts >= self.max_times.unwrap_or(usize::MAX) { return None; } self.attempts += 1; match self.current_delay { None => { // If current_delay is None, it's must be the first time to retry. let mut next = self.min_delay; self.current_delay = Some(next); // If jitter is enabled, add random jitter based on min delay. if self.jitter { next += self.min_delay.mul_f32(fastrand::f32()); } Some(next) } Some(cur) => { let mut next = cur; // If current delay larger than max delay, we should stop increment anymore. if next < self.max_delay.unwrap_or(Duration::MAX) { if let Some(prev) = self.previous_delay { next += prev; self.current_delay = Some(next); } self.previous_delay = Some(cur); } // If jitter is enabled, add random jitter based on min delay. if self.jitter { next += self.min_delay.mul_f32(fastrand::f32()); } Some(next) } } } } #[cfg(test)] mod tests { use std::time::Duration; use crate::backoff::BackoffBuilder; use crate::fibonacci::FibonacciBuilder; #[test] fn test_fibonacci_default() { let mut fib = FibonacciBuilder::default().build(); assert_eq!(Some(Duration::from_secs(1)), fib.next()); assert_eq!(Some(Duration::from_secs(1)), fib.next()); assert_eq!(Some(Duration::from_secs(2)), fib.next()); assert_eq!(None, fib.next()); } #[test] fn test_fibonacci_jitter() { let mut fib = FibonacciBuilder::default().with_jitter().build(); let v = fib.next().expect("value must valid"); assert!(v >= Duration::from_secs(1), "current: {v:?}"); assert!(v < Duration::from_secs(2), "current: {v:?}"); let v = fib.next().expect("value must valid"); assert!(v >= Duration::from_secs(1), "current: {v:?}"); assert!(v < Duration::from_secs(2), "current: {v:?}"); let v = fib.next().expect("value must valid"); assert!(v >= Duration::from_secs(2), "current: {v:?}"); assert!(v < Duration::from_secs(3), "current: {v:?}"); assert_eq!(None, fib.next()); } #[test] fn test_fibonacci_min_delay() { let mut fib = FibonacciBuilder::default() .with_min_delay(Duration::from_millis(500)) .build(); assert_eq!(Some(Duration::from_millis(500)), fib.next()); assert_eq!(Some(Duration::from_millis(500)), fib.next()); assert_eq!(Some(Duration::from_secs(1)), fib.next()); assert_eq!(None, fib.next()); } #[test] fn test_fibonacci_max_delay() { let mut fib = FibonacciBuilder::default() .with_max_times(4) .with_max_delay(Duration::from_secs(2)) .build(); assert_eq!(Some(Duration::from_secs(1)), fib.next()); assert_eq!(Some(Duration::from_secs(1)), fib.next()); assert_eq!(Some(Duration::from_secs(2)), fib.next()); assert_eq!(Some(Duration::from_secs(2)), fib.next()); assert_eq!(None, fib.next()); } #[test] fn test_fibonacci_max_times() { let mut fib = FibonacciBuilder::default().with_max_times(6).build(); assert_eq!(Some(Duration::from_secs(1)), fib.next()); assert_eq!(Some(Duration::from_secs(1)), fib.next()); assert_eq!(Some(Duration::from_secs(2)), fib.next()); assert_eq!(Some(Duration::from_secs(3)), fib.next()); assert_eq!(Some(Duration::from_secs(5)), fib.next()); assert_eq!(Some(Duration::from_secs(8)), fib.next()); assert_eq!(None, fib.next()); } } backon-0.4.4/src/lib.rs000064400000000000000000000121621046102023000127730ustar 00000000000000//! backon intends to provide an opposite backoff implementation of the popular [backoff](https://docs.rs/backoff). //! //! - Newer: developed by Rust edition 2021 and latest stable. //! - Cleaner: Iterator based abstraction, easy to use, customization friendly. //! - Easier: Trait based implementations, works like a native function provided by closures. //! //! # Backoff //! //! Any types that implements `Iterator` can be used as backoff. //! //! backon also provides backoff implementations with reasonable defaults: //! //! - [`ConstantBackoff`]: backoff with constant delay and limited times. //! - [`ExponentialBackoff`]: backoff with exponential delay, also provides jitter supports. //! - [`FibonacciBackoff`]: backoff with fibonacci delay, also provides jitter supports. //! //! Internally, `tokio::time::sleep()` will be used to sleep between retries, therefore //! it will respect [pausing/auto-advancing](https://docs.rs/tokio/latest/tokio/time/fn.pause.html) //! tokio's Runtime semantics, if enabled. //! //! # Examples //! //! Retry with default settings. //! //! ```no_run //! use anyhow::Result; //! use backon::ExponentialBuilder; //! use backon::Retryable; //! //! async fn fetch() -> Result { //! Ok(reqwest::get("https://www.rust-lang.org") //! .await? //! .text() //! .await?) //! } //! //! #[tokio::main(flavor = "current_thread")] //! async fn main() -> Result<()> { //! let content = fetch.retry(&ExponentialBuilder::default()).await?; //! //! println!("fetch succeeded: {}", content); //! Ok(()) //! } //! ``` //! //! Retry with specify retryable error. //! //! ```no_run //! use anyhow::Result; //! use backon::ExponentialBuilder; //! use backon::Retryable; //! //! async fn fetch() -> Result { //! Ok(reqwest::get("https://www.rust-lang.org") //! .await? //! .text() //! .await?) //! } //! //! #[tokio::main(flavor = "current_thread")] //! async fn main() -> Result<()> { //! let content = fetch //! .retry(&ExponentialBuilder::default()) //! .when(|e| e.to_string() == "retryable") //! .await?; //! //! println!("fetch succeeded: {}", content); //! Ok(()) //! } //! ``` //! //! Retry functions with args. //! //! ```no_run //! use anyhow::Result; //! use backon::ExponentialBuilder; //! use backon::Retryable; //! //! async fn fetch(url: &str) -> Result { //! Ok(reqwest::get(url).await?.text().await?) //! } //! //! #[tokio::main(flavor = "current_thread")] //! async fn main() -> Result<()> { //! let content = (|| async { fetch("https://www.rust-lang.org").await }) //! .retry(&ExponentialBuilder::default()) //! .when(|e| e.to_string() == "retryable") //! .await?; //! //! println!("fetch succeeded: {}", content); //! Ok(()) //! } //! ``` //! //! Retry functions with receiver `&self`. //! //! ```no_run //! use anyhow::Result; //! use backon::ExponentialBuilder; //! use backon::Retryable; //! //! struct Test; //! //! impl Test { //! async fn fetch(&self, url: &str) -> Result { //! Ok(reqwest::get(url).await?.text().await?) //! } //! } //! //! #[tokio::main(flavor = "current_thread")] //! async fn main() -> Result<()> { //! let test = Test; //! let content = (|| async { test.fetch("https://www.rust-lang.org").await }) //! .retry(&ExponentialBuilder::default()) //! .when(|e| e.to_string() == "retryable") //! .await?; //! //! println!("fetch succeeded: {}", content); //! Ok(()) //! } //! ``` //! //! Retry functions with receiver `&mut self`. //! //! ```no_run //! use anyhow::Result; //! use backon::ExponentialBuilder; //! use backon::RetryableWithContext; //! //! struct Test; //! //! impl Test { //! async fn fetch(&mut self, url: &str) -> Result { //! Ok(reqwest::get(url).await?.text().await?) //! } //! } //! //! #[tokio::main(flavor = "current_thread")] //! async fn main() -> Result<()> { //! let test = Test; //! //! let (_, result) = (|mut v: Test| async { //! let res = v.fetch("https://www.rust-lang.org").await; //! // Return input context back. //! (v, res) //! }) //! .retry(&ExponentialBuilder::default()) //! // Passing context in. //! .context(test) //! .when(|e| e.to_string() == "retryable") //! .await; //! //! println!("fetch succeeded: {}", result.unwrap()); //! Ok(()) //! } //! ``` #![deny(missing_docs)] #![deny(unused_qualifications)] mod backoff; pub use backoff::Backoff; pub use backoff::BackoffBuilder; mod constant; pub use constant::ConstantBackoff; pub use constant::ConstantBuilder; mod exponential; pub use exponential::ExponentialBackoff; pub use exponential::ExponentialBuilder; mod fibonacci; pub use fibonacci::FibonacciBackoff; pub use fibonacci::FibonacciBuilder; mod retry; pub use retry::Retry; pub use retry::Retryable; mod retry_with_context; pub use retry_with_context::RetryableWithContext; mod blocking_retry; pub use blocking_retry::BlockingRetry; pub use blocking_retry::BlockingRetryable; mod blocking_retry_with_context; pub use blocking_retry_with_context::BlockingRetryableWithContext; backon-0.4.4/src/retry.rs000064400000000000000000000252401046102023000133730ustar 00000000000000use std::future::Future; use std::pin::Pin; use std::task::Context; use std::task::Poll; use std::time::Duration; use futures_core::ready; use pin_project::pin_project; use crate::backoff::BackoffBuilder; use crate::Backoff; /// Retryable will add retry support for functions that produces a futures with results. /// /// That means all types that implement `FnMut() -> impl Future>` /// will be able to use `retry`. /// /// For example: /// /// - Functions without extra args: /// /// ```ignore /// async fn fetch() -> Result { /// Ok(reqwest::get("https://www.rust-lang.org").await?.text().await?) /// } /// ``` /// /// - Closures /// /// ```ignore /// || async { /// let x = reqwest::get("https://www.rust-lang.org") /// .await? /// .text() /// .await?; /// /// Err(anyhow::anyhow!(x)) /// } /// ``` /// /// # Example /// /// ```no_run /// use anyhow::Result; /// use backon::ExponentialBuilder; /// use backon::Retryable; /// /// async fn fetch() -> Result { /// Ok(reqwest::get("https://www.rust-lang.org") /// .await? /// .text() /// .await?) /// } /// /// #[tokio::main(flavor = "current_thread")] /// async fn main() -> Result<()> { /// let content = fetch.retry(&ExponentialBuilder::default()).await?; /// println!("fetch succeeded: {}", content); /// /// Ok(()) /// } /// ``` pub trait Retryable< B: BackoffBuilder, T, E, Fut: Future>, FutureFn: FnMut() -> Fut, > { /// Generate a new retry fn retry(self, builder: &B) -> Retry; } impl Retryable for FutureFn where B: BackoffBuilder, Fut: Future>, FutureFn: FnMut() -> Fut, { fn retry(self, builder: &B) -> Retry { Retry::new(self, builder.build()) } } /// Retry struct generated by [`Retryable`]. #[pin_project] pub struct Retry< B: Backoff, T, E, Fut: Future>, FutureFn: FnMut() -> Fut, RF = fn(&E) -> bool, NF = fn(&E, Duration), > { backoff: B, retryable: RF, notify: NF, future_fn: FutureFn, #[pin] state: State, } impl Retry where B: Backoff, Fut: Future>, FutureFn: FnMut() -> Fut, { /// Create a new retry. fn new(future_fn: FutureFn, backoff: B) -> Self { Retry { backoff, retryable: |_: &E| true, notify: |_: &E, _: Duration| {}, future_fn, state: State::Idle, } } } impl Retry where B: Backoff, Fut: Future>, FutureFn: FnMut() -> Fut, RF: FnMut(&E) -> bool, NF: FnMut(&E, Duration), { /// Set the conditions for retrying. /// /// If not specified, we treat all errors as retryable. /// /// # Examples /// /// ```no_run /// use anyhow::Result; /// use backon::ExponentialBuilder; /// use backon::Retryable; /// /// async fn fetch() -> Result { /// Ok(reqwest::get("https://www.rust-lang.org") /// .await? /// .text() /// .await?) /// } /// /// #[tokio::main(flavor = "current_thread")] /// async fn main() -> Result<()> { /// let content = fetch /// .retry(&ExponentialBuilder::default()) /// .when(|e| e.to_string() == "EOF") /// .await?; /// println!("fetch succeeded: {}", content); /// /// Ok(()) /// } /// ``` pub fn when bool>( self, retryable: RN, ) -> Retry { Retry { backoff: self.backoff, retryable, notify: self.notify, future_fn: self.future_fn, state: self.state, } } /// Set to notify for everything retrying. /// /// If not specified, this is a no-op. /// /// # Examples /// /// ```no_run /// use std::time::Duration; /// /// use anyhow::Result; /// use backon::ExponentialBuilder; /// use backon::Retryable; /// /// async fn fetch() -> Result { /// Ok(reqwest::get("https://www.rust-lang.org") /// .await? /// .text() /// .await?) /// } /// /// #[tokio::main(flavor = "current_thread")] /// async fn main() -> Result<()> { /// let content = fetch /// .retry(&ExponentialBuilder::default()) /// .notify(|err: &anyhow::Error, dur: Duration| { /// println!("retrying error {:?} with sleeping {:?}", err, dur); /// }) /// .await?; /// println!("fetch succeeded: {}", content); /// /// Ok(()) /// } /// ``` pub fn notify( self, notify: NN, ) -> Retry { Retry { backoff: self.backoff, retryable: self.retryable, notify, future_fn: self.future_fn, state: self.state, } } } /// State maintains internal state of retry. /// /// # Notes /// /// `tokio::time::Sleep` is a very struct that occupy 640B, so we wrap it /// into a `Pin>` to avoid this enum too large. #[derive(Default)] #[pin_project(project = StateProject)] enum State>> { #[default] Idle, Polling(#[pin] Fut), // TODO: we need to support other sleeper Sleeping(#[pin] Pin>), } impl Future for Retry where B: Backoff, Fut: Future>, FutureFn: FnMut() -> Fut, RF: FnMut(&E) -> bool, NF: FnMut(&E, Duration), { type Output = Result; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let mut this = self.project(); loop { let state = this.state.as_mut().project(); match state { StateProject::Idle => { let fut = (this.future_fn)(); this.state.set(State::Polling(fut)); continue; } StateProject::Polling(fut) => match ready!(fut.poll(cx)) { Ok(v) => return Poll::Ready(Ok(v)), Err(err) => { // If input error is not retryable, return error directly. if !(this.retryable)(&err) { return Poll::Ready(Err(err)); } match this.backoff.next() { None => return Poll::Ready(Err(err)), Some(dur) => { (this.notify)(&err, dur); this.state .set(State::Sleeping(Box::pin(tokio::time::sleep(dur)))); continue; } } } }, StateProject::Sleeping(sl) => { ready!(sl.poll(cx)); this.state.set(State::Idle); continue; } } } } } #[cfg(test)] mod tests { use std::time::Duration; use tokio::sync::Mutex; use super::*; use crate::exponential::ExponentialBuilder; async fn always_error() -> anyhow::Result<()> { Err(anyhow::anyhow!("test_query meets error")) } #[tokio::test] async fn test_retry() -> anyhow::Result<()> { let result = always_error .retry(&ExponentialBuilder::default().with_min_delay(Duration::from_millis(1))) .await; assert!(result.is_err()); assert_eq!("test_query meets error", result.unwrap_err().to_string()); Ok(()) } #[tokio::test] async fn test_retry_with_not_retryable_error() -> anyhow::Result<()> { let error_times = Mutex::new(0); let f = || async { let mut x = error_times.lock().await; *x += 1; Err::<(), anyhow::Error>(anyhow::anyhow!("not retryable")) }; let backoff = ExponentialBuilder::default().with_min_delay(Duration::from_millis(1)); let result = f .retry(&backoff) // Only retry If error message is `retryable` .when(|e| e.to_string() == "retryable") .await; assert!(result.is_err()); assert_eq!("not retryable", result.unwrap_err().to_string()); // `f` always returns error "not retryable", so it should be executed // only once. assert_eq!(*error_times.lock().await, 1); Ok(()) } #[tokio::test] async fn test_retry_with_retryable_error() -> anyhow::Result<()> { let error_times = Mutex::new(0); let f = || async { let mut x = error_times.lock().await; *x += 1; Err::<(), anyhow::Error>(anyhow::anyhow!("retryable")) }; let backoff = ExponentialBuilder::default().with_min_delay(Duration::from_millis(1)); let result = f .retry(&backoff) // Only retry If error message is `retryable` .when(|e| e.to_string() == "retryable") .await; assert!(result.is_err()); assert_eq!("retryable", result.unwrap_err().to_string()); // `f` always returns error "retryable", so it should be executed // 4 times (retry 3 times). assert_eq!(*error_times.lock().await, 4); Ok(()) } #[tokio::test] async fn test_fn_mut_when_and_notify() -> anyhow::Result<()> { let mut calls_retryable: Vec<()> = vec![]; let mut calls_notify: Vec<()> = vec![]; let f = || async { Err::<(), anyhow::Error>(anyhow::anyhow!("retryable")) }; let backoff = ExponentialBuilder::default().with_min_delay(Duration::from_millis(1)); let result = f .retry(&backoff) .when(|_| { calls_retryable.push(()); true }) .notify(|_, _| { calls_notify.push(()); }) .await; assert!(result.is_err()); assert_eq!("retryable", result.unwrap_err().to_string()); // `f` always returns error "retryable", so it should be executed // 4 times (retry 3 times). assert_eq!(calls_retryable.len(), 4); assert_eq!(calls_notify.len(), 3); Ok(()) } } backon-0.4.4/src/retry_with_context.rs000064400000000000000000000252321046102023000161730ustar 00000000000000use std::future::Future; use std::pin::{pin, Pin}; use std::task::Context; use std::task::Poll; use std::time::Duration; use futures_core::ready; use pin_project::pin_project; use crate::backoff::BackoffBuilder; use crate::Backoff; /// RetryableWithContext will add retry support for functions that produces a futures with results /// and context. /// /// That means all types that implement `FnMut(Ctx) -> impl Future)>` /// will be able to use `retry`. /// /// This will allow users to pass a context to the function and return it back while retry finish. /// /// # Example /// /// Without context, we could meet errors like the following: /// /// ```shell /// error: captured variable cannot escape `FnMut` closure body /// --> src/retry.rs:404:27 /// | /// 400 | let mut test = Test; /// | -------- variable defined here /// ... /// 404 | let result = { || async { test.hello().await } } /// | - ^^^^^^^^----^^^^^^^^^^^^^^^^ /// | | | | /// | | | variable captured here /// | | returns an `async` block that contains a reference to a captured variable, which then escapes the closure body /// | inferred to be a `FnMut` closure /// | /// = note: `FnMut` closures only have access to their captured variables while they are executing... /// = note: ...therefore, they cannot allow references to captured variables to escape /// ``` /// /// But with context support, we can implement in this way: /// /// ```no_run /// use anyhow::anyhow; /// use anyhow::Result; /// use backon::ExponentialBuilder; /// use backon::RetryableWithContext; /// /// struct Test; /// /// impl Test { /// async fn hello(&mut self) -> Result { /// Err(anyhow!("not retryable")) /// } /// } /// /// #[tokio::main(flavor = "current_thread")] /// async fn main() -> Result<()> { /// let mut test = Test; /// /// // (Test, Result) /// let (_, result) = { /// |mut v: Test| async { /// let res = v.hello().await; /// (v, res) /// } /// } /// .retry(&ExponentialBuilder::default()) /// .context(test) /// .await; /// /// Ok(()) /// } /// ``` pub trait RetryableWithContext< B: BackoffBuilder, T, E, Ctx, Fut: Future)>, FutureFn: FnMut(Ctx) -> Fut, > { /// Generate a new retry fn retry(self, builder: &B) -> Retry; } impl RetryableWithContext for FutureFn where B: BackoffBuilder, Fut: Future)>, FutureFn: FnMut(Ctx) -> Fut, { fn retry(self, builder: &B) -> Retry { Retry::new(self, builder.build()) } } /// Retry struct generated by [`Retryable`]. #[pin_project] pub struct Retry< B: Backoff, T, E, Ctx, Fut: Future)>, FutureFn: FnMut(Ctx) -> Fut, RF = fn(&E) -> bool, NF = fn(&E, Duration), > { backoff: B, retryable: RF, notify: NF, future_fn: FutureFn, #[pin] state: State, } impl Retry where B: Backoff, Fut: Future)>, FutureFn: FnMut(Ctx) -> Fut, { /// Create a new retry. /// /// # Notes /// /// `context` must be set by `context` method before calling `await`. fn new(future_fn: FutureFn, backoff: B) -> Self { Retry { backoff, retryable: |_: &E| true, notify: |_: &E, _: Duration| {}, future_fn, state: State::Idle(None), } } } impl Retry where B: Backoff, Fut: Future)>, FutureFn: FnMut(Ctx) -> Fut, RF: FnMut(&E) -> bool, NF: FnMut(&E, Duration), { /// Set the context for retrying. pub fn context(self, context: Ctx) -> Retry { Retry { backoff: self.backoff, retryable: self.retryable, notify: self.notify, future_fn: self.future_fn, state: State::Idle(Some(context)), } } /// Set the conditions for retrying. /// /// If not specified, we treat all errors as retryable. /// /// # Examples /// /// ```no_run /// use anyhow::Result; /// use backon::ExponentialBuilder; /// use backon::Retryable; /// /// async fn fetch() -> Result { /// Ok(reqwest::get("https://www.rust-lang.org") /// .await? /// .text() /// .await?) /// } /// /// #[tokio::main(flavor = "current_thread")] /// async fn main() -> Result<()> { /// let content = fetch /// .retry(&ExponentialBuilder::default()) /// .when(|e| e.to_string() == "EOF") /// .await?; /// println!("fetch succeeded: {}", content); /// /// Ok(()) /// } /// ``` pub fn when bool>( self, retryable: RN, ) -> Retry { Retry { backoff: self.backoff, retryable, notify: self.notify, future_fn: self.future_fn, state: self.state, } } /// Set to notify for everything retrying. /// /// If not specified, this is a no-op. /// /// # Examples /// /// ```no_run /// use std::time::Duration; /// /// use anyhow::Result; /// use backon::ExponentialBuilder; /// use backon::Retryable; /// /// async fn fetch() -> Result { /// Ok(reqwest::get("https://www.rust-lang.org") /// .await? /// .text() /// .await?) /// } /// /// #[tokio::main(flavor = "current_thread")] /// async fn main() -> Result<()> { /// let content = fetch /// .retry(&ExponentialBuilder::default()) /// .notify(|err: &anyhow::Error, dur: Duration| { /// println!("retrying error {:?} with sleeping {:?}", err, dur); /// }) /// .await?; /// println!("fetch succeeded: {}", content); /// /// Ok(()) /// } /// ``` pub fn notify( self, notify: NN, ) -> Retry { Retry { backoff: self.backoff, retryable: self.retryable, notify, future_fn: self.future_fn, state: self.state, } } } /// State maintains internal state of retry. /// /// # Notes /// /// `tokio::time::Sleep` is a very struct that occupy 640B, so we wrap it /// into a `Pin>` to avoid this enum too large. #[pin_project(project = StateProject)] enum State)>> { Idle(Option), Polling(#[pin] Fut), // TODO: we need to support other sleeper Sleeping((Option, Pin>)), } impl Future for Retry where B: Backoff, Fut: Future)>, FutureFn: FnMut(Ctx) -> Fut, RF: FnMut(&E) -> bool, NF: FnMut(&E, Duration), { type Output = (Ctx, Result); fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let mut this = self.project(); loop { let state = this.state.as_mut().project(); match state { StateProject::Idle(ctx) => { let ctx = ctx.take().expect("context must be valid"); let fut = (this.future_fn)(ctx); this.state.set(State::Polling(fut)); continue; } StateProject::Polling(fut) => { let (ctx, res) = ready!(fut.poll(cx)); match res { Ok(v) => return Poll::Ready((ctx, Ok(v))), Err(err) => { // If input error is not retryable, return error directly. if !(this.retryable)(&err) { return Poll::Ready((ctx, Err(err))); } match this.backoff.next() { None => return Poll::Ready((ctx, Err(err))), Some(dur) => { (this.notify)(&err, dur); this.state.set(State::Sleeping(( Some(ctx), Box::pin(tokio::time::sleep(dur)), ))); continue; } } } } } StateProject::Sleeping((ctx, sl)) => { ready!(pin!(sl).poll(cx)); let ctx = ctx.take().expect("context must be valid"); this.state.set(State::Idle(Some(ctx))); continue; } } } } } #[cfg(test)] mod tests { use std::time::Duration; use anyhow::anyhow; use tokio::sync::Mutex; use super::*; use crate::exponential::ExponentialBuilder; use anyhow::Result; struct Test; impl Test { async fn hello(&mut self) -> Result { Err(anyhow!("not retryable")) } } #[tokio::test] async fn test_retry_with_not_retryable_error() -> Result<()> { let error_times = Mutex::new(0); let test = Test; let backoff = ExponentialBuilder::default().with_min_delay(Duration::from_millis(1)); let (_, result) = { |mut v: Test| async { let mut x = error_times.lock().await; *x += 1; let res = v.hello().await; (v, res) } } .retry(&backoff) .context(test) // Only retry If error message is `retryable` .when(|e| e.to_string() == "retryable") .await; assert!(result.is_err()); assert_eq!("not retryable", result.unwrap_err().to_string()); // `f` always returns error "not retryable", so it should be executed // only once. assert_eq!(*error_times.lock().await, 1); Ok(()) } }