├── .github ├── FUNDING.yml └── workflows │ └── CI.yml ├── .gitignore ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── SECURITY.md ├── deny.toml ├── examples ├── hyper.rs ├── hyper_panic.rs ├── hyper_with_overwrite_fn.rs ├── hyper_with_shutdown_delay.rs ├── tokio_tcp.rs ├── tokio_tcp_with_overwrite_fn.rs └── waitgroup.rs ├── justfile ├── rust-toolchain.toml └── src ├── guard.rs ├── lib.rs ├── shutdown.rs ├── sync ├── default.rs ├── loom.rs └── mod.rs └── trigger.rs /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: plabayo 4 | -------------------------------------------------------------------------------- /.github/workflows/CI.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | env: 4 | CARGO_TERM_COLOR: always 5 | RUST_TOOLCHAIN: stable 6 | RUST_TOOLCHAIN_NIGHTLY: nightly 7 | RUST_TOOLCHAIN_MSRV: 1.75.0 8 | RUST_TOOLCHAIN_BETA: beta 9 | 10 | on: 11 | push: 12 | branches: 13 | - main 14 | pull_request: {} 15 | 16 | jobs: 17 | check-msrv: 18 | runs-on: ubuntu-latest 19 | steps: 20 | - uses: actions/checkout@v4 21 | - uses: dtolnay/rust-toolchain@stable 22 | with: 23 | toolchain: ${{env.RUST_TOOLCHAIN_MSRV}} 24 | components: clippy, rustfmt 25 | - uses: Swatinem/rust-cache@v2 26 | - name: check 27 | run: | 28 | cargo check --workspace --all-targets --all-features 29 | - name: clippy 30 | run: | 31 | cargo clippy --workspace --all-targets --all-features 32 | - name: rustfmt 33 | run: | 34 | cargo fmt --all --check 35 | 36 | check: 37 | runs-on: ubuntu-latest 38 | steps: 39 | - uses: actions/checkout@v4 40 | - uses: dtolnay/rust-toolchain@stable 41 | with: 42 | toolchain: ${{env.RUST_TOOLCHAIN}} 43 | components: clippy, rustfmt 44 | - uses: Swatinem/rust-cache@v2 45 | - name: check 46 | run: | 47 | cargo check --workspace --all-targets --all-features 48 | - name: clippy 49 | run: | 50 | cargo clippy --workspace --all-targets --all-features 51 | - name: rustfmt 52 | run: | 53 | cargo fmt --all --check 54 | 55 | check-all-features: 56 | runs-on: ubuntu-latest 57 | steps: 58 | - uses: actions/checkout@v4 59 | - uses: dtolnay/rust-toolchain@stable 60 | with: 61 | toolchain: ${{env.RUST_TOOLCHAIN}} 62 | components: clippy, rustfmt 63 | - uses: Swatinem/rust-cache@v2 64 | - name: check 65 | run: | 66 | cargo check --workspace --all-targets --all-features 67 | - name: clippy 68 | run: | 69 | cargo clippy --workspace --all-targets --all-features 70 | - name: rustfmt 71 | run: | 72 | cargo fmt --all --check 73 | 74 | test-msrv: 75 | needs: [check, check-msrv, check-all-features] 76 | runs-on: ubuntu-latest 77 | steps: 78 | - uses: actions/checkout@v4 79 | - uses: dtolnay/rust-toolchain@stable 80 | with: 81 | toolchain: ${{env.RUST_TOOLCHAIN_MSRV}} 82 | - uses: Swatinem/rust-cache@v2 83 | - name: Run tests 84 | run: cargo test --all-features --workspace 85 | 86 | test-loom-msrv: 87 | needs: [check, check-msrv, check-all-features] 88 | runs-on: ubuntu-latest 89 | steps: 90 | - uses: actions/checkout@v4 91 | - uses: dtolnay/rust-toolchain@stable 92 | with: 93 | toolchain: ${{env.RUST_TOOLCHAIN_MSRV}} 94 | - uses: Swatinem/rust-cache@v2 95 | - name: Run tests 96 | run: cargo test test_loom --release 97 | env: 98 | RUSTFLAGS: --cfg loom 99 | 100 | test-beta: 101 | needs: [check, check-msrv, check-all-features] 102 | runs-on: ubuntu-latest 103 | steps: 104 | - uses: actions/checkout@v4 105 | - uses: dtolnay/rust-toolchain@stable 106 | with: 107 | toolchain: ${{env.RUST_TOOLCHAIN_BETA}} 108 | - uses: Swatinem/rust-cache@v2 109 | - name: Run tests 110 | run: cargo test --all-features --workspace 111 | 112 | test-loom-beta: 113 | needs: [check, check-msrv, check-all-features] 114 | runs-on: ubuntu-latest 115 | steps: 116 | - uses: actions/checkout@v4 117 | - uses: dtolnay/rust-toolchain@stable 118 | with: 119 | toolchain: ${{env.RUST_TOOLCHAIN_BETA}} 120 | - uses: Swatinem/rust-cache@v2 121 | - name: Run tests 122 | run: cargo test test_loom --release 123 | env: 124 | RUSTFLAGS: --cfg loom 125 | 126 | test: 127 | needs: [check, check-msrv, check-all-features] 128 | runs-on: ubuntu-latest 129 | steps: 130 | - uses: actions/checkout@v4 131 | - uses: dtolnay/rust-toolchain@stable 132 | with: 133 | toolchain: ${{env.RUST_TOOLCHAIN}} 134 | - uses: Swatinem/rust-cache@v2 135 | - name: Run tests 136 | run: cargo test --all-features --workspace 137 | 138 | test-loom: 139 | needs: [check, check-msrv, check-all-features] 140 | runs-on: ubuntu-latest 141 | steps: 142 | - uses: actions/checkout@v4 143 | - uses: dtolnay/rust-toolchain@stable 144 | with: 145 | toolchain: ${{env.RUST_TOOLCHAIN}} 146 | - uses: Swatinem/rust-cache@v2 147 | - name: Run tests 148 | run: cargo test test_loom --release 149 | env: 150 | RUSTFLAGS: --cfg loom 151 | 152 | test-macos-msrv: 153 | needs: [check, check-msrv, check-all-features] 154 | runs-on: macos-latest 155 | steps: 156 | - uses: actions/checkout@v4 157 | - uses: dtolnay/rust-toolchain@stable 158 | with: 159 | toolchain: ${{env.RUST_TOOLCHAIN_MSRV}} 160 | - uses: Swatinem/rust-cache@v2 161 | - name: Run tests 162 | run: cargo test --all-features --workspace 163 | 164 | test-macos-beta: 165 | needs: [check, check-msrv, check-all-features] 166 | runs-on: macos-latest 167 | steps: 168 | - uses: actions/checkout@v4 169 | - uses: dtolnay/rust-toolchain@stable 170 | with: 171 | toolchain: ${{env.RUST_TOOLCHAIN_MSRV}} 172 | - uses: Swatinem/rust-cache@v2 173 | - name: Run tests 174 | run: cargo test --all-features --workspace 175 | 176 | test-macos: 177 | needs: [check, check-msrv, check-all-features] 178 | runs-on: macos-latest 179 | steps: 180 | - uses: actions/checkout@v4 181 | - uses: dtolnay/rust-toolchain@stable 182 | with: 183 | toolchain: ${{env.RUST_TOOLCHAIN}} 184 | - uses: Swatinem/rust-cache@v2 185 | - name: Run tests 186 | run: cargo test --all-features --workspace 187 | 188 | test-docs: 189 | needs: [check, check-msrv, check-all-features] 190 | runs-on: ubuntu-latest 191 | steps: 192 | - uses: actions/checkout@v4 193 | - uses: dtolnay/rust-toolchain@stable 194 | with: 195 | toolchain: ${{env.RUST_TOOLCHAIN}} 196 | - uses: Swatinem/rust-cache@v2 197 | - name: Run doc tests 198 | run: cargo test --doc --all-features --workspace 199 | 200 | test-examples-beta: 201 | needs: [check, check-msrv, check-all-features] 202 | runs-on: ubuntu-latest 203 | steps: 204 | - uses: actions/checkout@v4 205 | - uses: dtolnay/rust-toolchain@stable 206 | with: 207 | toolchain: ${{env.RUST_TOOLCHAIN_BETA}} 208 | - uses: Swatinem/rust-cache@v2 209 | - name: Run doc tests 210 | run: cargo test --all-features --examples --workspace 211 | 212 | test-examples-msrv: 213 | needs: [check, check-msrv, check-all-features] 214 | runs-on: ubuntu-latest 215 | steps: 216 | - uses: actions/checkout@v4 217 | - uses: dtolnay/rust-toolchain@stable 218 | with: 219 | toolchain: ${{env.RUST_TOOLCHAIN_MSRV}} 220 | - uses: Swatinem/rust-cache@v2 221 | - name: Run doc tests 222 | run: cargo test --all-features --examples --workspace 223 | 224 | test-examples: 225 | needs: [check, check-msrv, check-all-features] 226 | runs-on: ubuntu-latest 227 | steps: 228 | - uses: actions/checkout@v4 229 | - uses: dtolnay/rust-toolchain@stable 230 | with: 231 | toolchain: ${{env.RUST_TOOLCHAIN}} 232 | - uses: Swatinem/rust-cache@v2 233 | - name: Run doc tests 234 | run: cargo test --all-features --examples --workspace 235 | 236 | test-examples-macos-beta: 237 | needs: [check, check-msrv, check-all-features] 238 | runs-on: macos-latest 239 | steps: 240 | - uses: actions/checkout@v4 241 | - uses: dtolnay/rust-toolchain@stable 242 | with: 243 | toolchain: ${{env.RUST_TOOLCHAIN_BETA}} 244 | - uses: Swatinem/rust-cache@v2 245 | - name: Run doc tests 246 | run: cargo test --all-features --examples --workspace 247 | 248 | test-examples-macos-msrv: 249 | needs: [check, check-msrv, check-all-features] 250 | runs-on: macos-latest 251 | steps: 252 | - uses: actions/checkout@v4 253 | - uses: dtolnay/rust-toolchain@stable 254 | with: 255 | toolchain: ${{env.RUST_TOOLCHAIN_MSRV}} 256 | - uses: Swatinem/rust-cache@v2 257 | - name: Run doc tests 258 | run: cargo test --all-features --examples --workspace 259 | 260 | test-examples-macos: 261 | needs: [check, check-msrv, check-all-features] 262 | runs-on: macos-latest 263 | steps: 264 | - uses: actions/checkout@v4 265 | - uses: dtolnay/rust-toolchain@stable 266 | with: 267 | toolchain: ${{env.RUST_TOOLCHAIN}} 268 | - uses: Swatinem/rust-cache@v2 269 | - name: Run doc tests 270 | run: cargo test --all-features --examples --workspace 271 | 272 | cargo-hack: 273 | needs: [check, check-msrv, check-all-features] 274 | runs-on: ubuntu-latest 275 | steps: 276 | - uses: actions/checkout@v4 277 | - uses: dtolnay/rust-toolchain@stable 278 | with: 279 | toolchain: ${{env.RUST_TOOLCHAIN}} 280 | - name: install cargo-hack 281 | uses: taiki-e/install-action@cargo-hack 282 | - name: cargo hack check 283 | run: cargo hack check --each-feature --no-dev-deps --workspace 284 | 285 | dependencies-are-sorted: 286 | needs: [check, check-msrv, check-all-features] 287 | runs-on: ubuntu-latest 288 | steps: 289 | - uses: actions/checkout@v4 290 | - uses: dtolnay/rust-toolchain@stable 291 | with: 292 | toolchain: ${{env.RUST_TOOLCHAIN}} 293 | - uses: Swatinem/rust-cache@v2 294 | - name: Install cargo-sort 295 | run: | 296 | cargo install cargo-sort 297 | - name: Check dependency tables 298 | working-directory: . 299 | run: | 300 | cargo sort --workspace --grouped --check 301 | 302 | cargo-deny: 303 | needs: [check, check-msrv, check-all-features] 304 | runs-on: ubuntu-latest 305 | steps: 306 | - uses: actions/checkout@v4 307 | - uses: EmbarkStudios/cargo-deny-action@v1 308 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /Cargo.lock 3 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 7 | 8 | # 0.2.2 (30. September, 2024) 9 | 10 | Expose main trace events at Info level for increased visibility, 11 | log-directives can be used by dependencies 12 | to filter out tokio-graceful info events if not desired. 13 | 14 | # 0.2.1 (30. September, 2024) 15 | 16 | Expose a signal that can be awaited on without awaiting the configured 17 | delay first. If no delay is used this API is equivalent to the already 18 | existing `cancelled` function. 19 | 20 | This can be used for scenarios where you do not need a graceful buffer and would like to 21 | cancel as soon as a signal is received. 22 | 23 | # 0.2.0 (29. September, 2024) 24 | 25 | This is usability wise not a breaking release, 26 | however it does make changes to the API which might break subtle edge cases 27 | and it also increases the MSRV to 1.75. 28 | 29 | New Features: 30 | 31 | - add a delay (Duration) that can be used 32 | to trigger the cancel notification to ongoing jobs once the shutdown trigger (signal) 33 | has been received; 34 | - add a second signal factory that can be used to create an overwrite 35 | signal to be created and triggered once the main signal has been triggered, 36 | as an alternative to the jobs being complete or max delay has been reached. 37 | 38 | Both features can be configured using the newly introduced `ShutdownBuilder`, 39 | which can be made directly or via `Shutdown::builder`. 40 | 41 | # 0.1.6 (01. December, 2023) 42 | 43 | - Upgrade hyper examples to adapt to dev dependency hyper v1.0 (was hyper v0.14); 44 | 45 | # 0.1.5 (20. September, 2023) 46 | 47 | - Support and use Loom for testing; 48 | - Fixes a bug in the private trigger code where a race condition could cause a deadlock (found using loom); 49 | - Signal / Project support for the Windows platform; 50 | - affected code: `crate::default_signal` and `crate::Shutdown::default`; 51 | - Unix and Windows are supported and have this code enabled; 52 | - Other platforms won't have this code; 53 | - When using Loom this code is also not there; 54 | - This fixes build errors for platforms that we do not support for the default signal; 55 | 56 | # 0.1.4 (08. September, 2023) 57 | 58 | - Add example regarding ensuring you do catch exits and document it; 59 | 60 | # 0.1.3 (07. September, 2023) 61 | 62 | - Support and add Waitgroup example; 63 | - Fix mistake in docs (thank you [Mike Cronce](https://github.com/mcronce)); 64 | - Update 0.1.2 changelog to highlight the library is no longer 100% Rust Safe Code; 65 | 66 | # 0.1.2 (05. September, 2023) 67 | 68 | - Fix typos in README (thank you [@hds](https://github.com/hds)); 69 | - Performance improvements (thank you awake readers on Reddit); 70 | - add more docs to README and internal code; 71 | - library is no longer 100% safe Rust code, due to usage of 72 | in an internal struct; 73 | 74 | # 0.1.1 (05. September, 2023) 75 | 76 | - Improved documentation and add FAQ to readme; 77 | - Optimization to the `into_spawn*` methods (don't clone first); 78 | - add CI semver check; 79 | 80 | # 0.1.0 (04. September, 2023) 81 | 82 | - Initial release. 83 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | support@plabayo.tech. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | 1. [File an issue](https://github.com/plabayo/rama/issues/new). 4 | The issue will be used to discuss the bug or feature and should be created before opening an MR. 5 | > Best to even wait on actually developing it as to make sure 6 | > that we're all aligned on what you're trying to contribute, 7 | > as to avoid having to reject your hard work and code. 8 | 9 | In case you also want to help resolve it by contributing to the code base you would continue as follows: 10 | 11 | 2. Install Rust and configure correctly (https://www.rust-lang.org/tools/install). 12 | 3. Clone the repo: `git clone https://github.com/plabayo/tokio-graceful` 13 | 4. Change into the checked out source: `cd news` 14 | 5. Fork the repo. 15 | 6. Set your fork as a remote: `git remote add fork git@github.com:GITHUB_USERNAME/tokio-graceful.git` 16 | 7. Make changes, commit to your fork. 17 | Please add a short summary and a detailed commit message for each commit. 18 | > Feel free to make as many commits as you want in your branch, 19 | > prior to making your MR ready for review, please clean up the git history 20 | > from your branch by rebasing and squashing relevant commits together, 21 | > with the final commits being minimal in number and detailed in their description. 22 | 8. To minimize friction, consider setting Allow edits from maintainers on the PR, 23 | which will enable project committers and automation to update your PR. 24 | 9. A maintainer will review the pull request and make comments. 25 | 26 | Prefer adding additional commits over amending and force-pushing 27 | since it can be difficult to follow code reviews when the commit history changes. 28 | 29 | Commits will be squashed when they're merged. 30 | 31 | ## Testing 32 | 33 | All tests can be run locally against the latest Rust version (or whichever supported Rust version you're using on your development machine): 34 | 35 | ```bash 36 | cargo test --all 37 | ``` 38 | 39 | ```bash 40 | cargo clippy --all 41 | ``` 42 | 43 | ```bash 44 | cargo sort --workspace --grouped 45 | ``` 46 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | categories = ["asynchronous", "network-programming"] 3 | edition = "2021" 4 | name = "tokio-graceful" 5 | version = "0.2.2" 6 | description = "util for graceful shutdown of tokio applications" 7 | homepage = "https://github.com/plabayo/tokio-graceful" 8 | readme = "README.md" 9 | keywords = ["io", "async", "non-blocking", "futures"] 10 | license = "MIT OR Apache-2.0" 11 | repository = "https://github.com/plabayo/tokio-graceful" 12 | rust-version = "1.75.0" 13 | 14 | [target.'cfg(loom)'.dependencies] 15 | loom = { version = "0.7", features = ["futures", "checkpoint"] } 16 | 17 | [dependencies] 18 | pin-project-lite = "0.2" 19 | slab = "0.4" 20 | tokio = { version = "1", features = ["rt", "signal", "sync", "macros", "time"] } 21 | tracing = "0.1" 22 | 23 | [dev-dependencies] 24 | rand = "0.8" 25 | tokio = { version = "1", features = ["net", "rt-multi-thread", "io-util", "test-util"] } 26 | tracing-subscriber = { version = "0.3", features = ["env-filter"] } 27 | 28 | [target.'cfg(not(loom))'.dev-dependencies] 29 | hyper = { version = "1.0.1", features = [ "server", "http1", "http2" ] } 30 | hyper-util = { version = "0.1.1", features = [ "server", "server-auto", "http1", "http2", "tokio" ] } 31 | http-body-util = "0.1" 32 | bytes = "1" 33 | 34 | [lints.rust] 35 | unexpected_cfgs = { level = "allow", check-cfg = ['cfg(loom)'] } 36 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 - Glen Henri J. De Cauwsemaecker 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Crates.io][crates-badge]][crates-url] 2 | [![Docs.rs][docs-badge]][docs-url] 3 | [![MIT License][license-mit-badge]][license-mit-url] 4 | [![Apache 2.0 License][license-apache-badge]][license-apache-url] 5 | [![rust version][rust-version-badge]][rust-version-url] 6 | [![Build Status][actions-badge]][actions-url] 7 | 8 | [![Buy Me A Coffee][bmac-badge]][bmac-url] 9 | [![GitHub Sponsors][ghs-badge]][ghs-url] 10 | 11 | [crates-badge]: https://img.shields.io/crates/v/tokio-graceful.svg 12 | [crates-url]: https://crates.io/crates/tokio-graceful 13 | [docs-badge]: https://img.shields.io/docsrs/tokio-graceful/latest 14 | [docs-url]: https://docs.rs/tokio-graceful/latest/tokio_graceful/index.html 15 | [license-mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg 16 | [license-mit-url]: https://github.com/plabayo/tokio-graceful/blob/main/LICENSE-MIT 17 | [license-apache-badge]: https://img.shields.io/badge/license-APACHE-blue.svg 18 | [license-apache-url]: https://github.com/plabayo/tokio-graceful/blob/main/LICENSE-APACHE 19 | [rust-version-badge]: https://img.shields.io/badge/rustc-1.75+-blue?style=flat-square&logo=rust 20 | [rust-version-url]: https://www.rust-lang.org 21 | [actions-badge]: https://github.com/plabayo/tokio-graceful/workflows/CI/badge.svg 22 | [actions-url]: https://github.com/plabayo/tokio-graceful/actions/workflows/CI.yml?query=branch%3Amain 23 | 24 | [bmac-badge]: https://img.shields.io/badge/Buy%20Me%20a%20Coffee-ffdd00?style=for-the-badge&logo=buy-me-a-coffee&logoColor=black 25 | [bmac-url]: https://www.buymeacoffee.com/plabayo 26 | [ghs-badge]: https://img.shields.io/badge/sponsor-30363D?style=for-the-badge&logo=GitHub-Sponsors&logoColor=#EA4AAA 27 | [ghs-url]: https://github.com/sponsors/plabayo 28 | 29 | Shutdown management for graceful shutdown of [tokio](https://tokio.rs/) applications. 30 | Guard creating and usage is lock-free and the crate only locks when: 31 | 32 | - the shutdown signal was not yet given and you wait with a (weak or strong) guard 33 | on whether or not it was in fact cancelled; 34 | - the check of whether or not the app can shut down typically is locked until 35 | the shutdown signal was received and all (strong) guards were dropped. 36 | 37 | ## Index 38 | 39 | - [Examples](#examples): quick overview of how to use this crate; 40 | - Make sure to also check out the 41 | [Tokio TCP](https://github.com/plabayo/tokio-graceful/tree/main/examples/tokio_tcp.rs) 42 | and [Hyper](https://github.com/plabayo/tokio-graceful/tree/main/examples/hyper.rs) examples for typical "real world" usage! 43 | - [Contributing information](#contributing) and special [shoutouts](#shoutouts). 44 | - [Licensing](#license) info and what happens to [your contributions](#contribution). 45 | - [Frequently Asked Questions](#faq) 46 | 47 | ## Examples 48 | 49 | One example to show it all: 50 | 51 | ```rust 52 | use std::time::Duration; 53 | use tokio_graceful::Shutdown; 54 | 55 | #[tokio::main] 56 | async fn main() { 57 | // most users can just use `Shutdown::default()` to initiate 58 | // shutdown upon the default system signals. 59 | let signal = tokio::time::sleep(std::time::Duration::from_millis(100)); 60 | let shutdown = Shutdown::builder() 61 | .with_delay(std::time::Duration::from_millis(50)) 62 | .with_signal(signal) 63 | .with_overwrite_fn(tokio::signal::ctrl_c) 64 | .build(); 65 | 66 | // you can use shutdown to spawn tasks that will 67 | // include a guard to prevent the shutdown from completing 68 | // aslong as these tasks are open 69 | shutdown.spawn_task(async { 70 | tokio::time::sleep(std::time::Duration::from_millis(10)).await; 71 | }); 72 | // or spawn a function such that you have access to the guard coupled to the task 73 | shutdown.spawn_task_fn(|guard| async move { 74 | let guard2 = guard.clone(); 75 | guard.cancelled().await; 76 | }); 77 | 78 | // this guard isn't dropped, but as it's a weak guard 79 | // it has no impact on the ref count of the common tokens. 80 | let guard_weak = shutdown.guard_weak(); 81 | 82 | // this guard needs to be dropped as otherwise the shutdown is prevented; 83 | let guard = shutdown.guard(); 84 | drop(guard); 85 | 86 | // guards can be downgraded to weak guards, to not have it be counted any longer in the ref count 87 | let weak_guard_2 = shutdown.guard().downgrade(); 88 | 89 | // guards (weak or not) are cancel safe 90 | tokio::select! { 91 | _ = tokio::time::sleep(std::time::Duration::from_millis(10)) => {}, 92 | _ = weak_guard_2.into_cancelled() => {}, 93 | } 94 | 95 | // you can also wait to shut down without any timeout limit 96 | // `shutdown.shutdown().await;` 97 | shutdown 98 | .shutdown_with_limit(Duration::from_secs(60)) 99 | .await 100 | .unwrap(); 101 | 102 | // once a shutdown is triggered the ::cancelled() fn will immediately return true, 103 | // forever, not just once. Even after shutdown process is completely finished. 104 | guard_weak.cancelled().await; 105 | 106 | // weak guards can be upgraded to regular guards to take into account for ref count 107 | let guard = guard_weak.upgrade(); 108 | // even this one however will know it was cancelled 109 | guard.cancelled().await; 110 | } 111 | ``` 112 | 113 | ### Runnable Examples 114 | 115 | While the above example shows pretty much all parts of this crate at once, 116 | it might be useful to see examples on how this crate is to be used in 117 | an actual production-like setting. That's what these runnable examples are for. 118 | 119 | The runnable examples are best run with `RUST_LOG=trace` environment variable set, 120 | such that you see the verbose logs of `tokio-graceful` and really see it in action 121 | and get a sense on how it works, or at least its flow. 122 | 123 | > [examples/tokio_tcp.rs](https://github.com/plabayo/tokio-graceful/tree/main/examples/tokio_tcp.rs) 124 | > 125 | > ```bash 126 | > RUST_LOG=trace cargo run --example tokio_tcp 127 | > ``` 128 | 129 | The `tokio_tcp` example showcases the original use case of why `tokio-graceful` shutdown was developed, 130 | as it makes managing graceful shutdown from start to finish a lot easier, without immediately grabbing 131 | to big power tools or providing more than is needed. 132 | 133 | The example runs a tcp 'echo' server which you can best play with using 134 | telnet: `telnet 127.0.0.1 8080`. As you are in control of when to exit you can easily let it timeout if you wish. 135 | 136 | > [examples/tokio_tcp_with_overwrite_fn.rs](https://github.com/plabayo/tokio-graceful/tree/main/examples/tokio_tcp_with_overwrite_fn.rs) 137 | > 138 | > ```bash 139 | > RUST_LOG=trace cargo run --example tokio_tcp_with_overwrite_fn 140 | > ``` 141 | 142 | Same as `tokio_tcp` but with an overwrite fn added. 143 | 144 | > [examples/hyper.rs](https://github.com/plabayo/tokio-graceful/tree/main/examples/hyper.rs) 145 | > 146 | > ```bash 147 | > RUST_LOG=trace cargo run --example hyper 148 | > ``` 149 | 150 | In case you wish to use this library as a [Hyper](https://hyper.rs/) user 151 | you can do so using pretty much the same approach as 152 | the Tokio tcp example. 153 | 154 | This example only has one router server function which returns 'hello' (200 OK) after 5s. 155 | The delay is there to allow you to see the graceful shutdown in action. 156 | 157 | > [examples/hyper_with_overwrite_fn.rs](https://github.com/plabayo/tokio-graceful/tree/main/examples/hyper_with_overwrite_fn.rs) 158 | > 159 | > ```bash 160 | > RUST_LOG=trace cargo run --example hyper_with_overwrite_fn 161 | > ``` 162 | 163 | Same as the `hyper` example but showcasing how you can add a overwrite signal fn. 164 | 165 | > [examples/hyper_with_shutdown_delay.rs](https://github.com/plabayo/tokio-graceful/tree/main/examples/hyper_with_shutdown_delay.rs) 166 | > 167 | > ```bash 168 | > RUST_LOG=trace cargo run --example hyper_with_shutdown_delay 169 | > ``` 170 | 171 | Same as the `hyper` example but showcasing how you can add a delay buffer. 172 | 173 | > [examples/hyper_panic.rs](https://github.com/plabayo/tokio-graceful/tree/main/examples/hyper_panic.rs) 174 | > 175 | > ```bash 176 | > RUST_LOG=trace cargo run --example hyper_panic 177 | > ``` 178 | 179 | Same as [the `hyper` example](https://github.com/plabayo/tokio-graceful/tree/main/examples/hyper.rs) 180 | but showcasing how you would ensure that you manually trigger a shutdown 181 | using your custom signal (on top of the regular exit signal) in case for example a spawned task exits 182 | unexpectedly, due to an error, panic or just without any info at all (probably the worst kind of option). 183 | 184 | This is especially important to do if you perform also a setup prior to running a server in a loop, 185 | as those are often the parts of your code that you do make assumptions and panic otherwise. 186 | A common example of this is that you'll let your server (created and started from within a task) 187 | panic in case the chosen port was already bound to by something else. 188 | 189 | An alternative to this is approach is where you use `tokio::select!` on your `Shutdown::shutdown*` future 190 | together with all your critical task handles, this will also ensure that you do exit 191 | on unexpected exit scenarios. However that would mean that you are skipping a graceful shutdown in that case, 192 | which is why it is not the approach that we recommend and thus also not shutcase in our example code. 193 | 194 | > [examples/waitgroup.rs](https://github.com/plabayo/tokio-graceful/tree/main/examples/waitgroup.rs) 195 | > 196 | > ```bash 197 | > cargo run --example waitgroup 198 | > ``` 199 | 200 | An example which showcases how you would use this crate to create a Waitgroup, 201 | which allows you to wait for multiple async jobs/tasks without 202 | first having to trigger a signal first. 203 | 204 | In case you need a waitgroup which does first need to wait for a signal, 205 | you would create a regular `Shutdown` instance using `Shutdown::new` to give 206 | your 'trigger' signal (a future). 207 | 208 | ## Contributing 209 | 210 | 🎈 Thanks for your help improving the project! We are so happy to have 211 | you! We have a [contributing guide][contributing] to help you get involved in the 212 | `tokio-graceful` project. 213 | 214 | ### Shoutouts 215 | 216 | Special shoutout for this library goes to [the Tokio ecosystem](https://tokio.rs/). 217 | Those who developed it as well as the folks hanging on the [Tokio discord server](https://discord.gg/tokio). 218 | The discussions and Q&A sessions with them were very crucial to the development of this project. 219 | Tokio's codebase is also a gem of examples on what is possible and what are good practices. 220 | 221 | In this context also an extra shoutout to [@tobz](https://github.com/tobz) who 222 | gave me the idea of approaching it from an Atomic perspective instead 223 | of immediately going for channel solutions. 224 | 225 | ## License 226 | 227 | This project is dual-licensed under both the [MIT license][mit-license] and [Apache 2.0 License][apache-license]. 228 | 229 | ### Contribution 230 | 231 | Unless you explicitly state otherwise, any contribution intentionally submitted 232 | for inclusion in `tokio-graceful` by you, shall be licensed as both [MIT][mit-license] and [Apache 2.0][apache-license], 233 | without any additional terms or conditions. 234 | 235 | [contributing]: https://github.com/plabayo/tokio-graceful/blob/main/CONTRIBUTING.md 236 | [mit-license]: https://github.com/plabayo/tokio-graceful/blob/main/LICENSE-MIT 237 | [apache-license]: https://github.com/plabayo/tokio-graceful/blob/main/LICENSE-APACHE 238 | 239 | ## Sponsors 240 | 241 | tokio-graceful is **completely free, open-source software** which needs time to develop and maintain. 242 | 243 | Support this project by becoming a [sponsor][ghs-url]. One time payments are accepted [at GitHub][ghs-url] as well as at ["Buy me a Coffee"][bmac-url] 244 | 245 | Sponsors help us continue to maintain and improve `tokio-graceful`, as well as other 246 | Free and Open Source (FOSS) technology. It also helps us to create 247 | educational content such as , 248 | and other open source libraries such as . 249 | 250 | Sponsors receive perks and depending on your regular contribution it also 251 | allows you to rely on us for support and consulting. 252 | 253 | ## FAQ 254 | 255 | > What is the difference with ? 256 | 257 | is an excellent tutorial by the Tokio developers. 258 | It is meant to teach and inspire you on how to be able to gracefully shutdown your 259 | Tokio-driven application and also to give you a rough idea on when to use it. 260 | 261 | That said, nothing stops you from applying what you learn in that tutorial directly 262 | in your production application. It will work and very well so. However 263 | there is a lot of management of components you have to do yourself. 264 | 265 | > Ok, but what about the other crates on that provide graceful shutdown? 266 | 267 | They work fine and they are just as easy to use as this crate. However we think that 268 | those crates offer more features then you need in a typical use case, are as a consequence 269 | more complex on the surface as well as the machinery inside. 270 | 271 | > How do I trigger the Shutdown from within a task? 272 | 273 | You can achieve this by providing your own mechanism that you feed as the "signal" 274 | to [`Shutdown::new`](https://docs.rs/tokio-graceful/0.1.0/tokio_graceful/struct.Shutdown.html#method.new). E.g. you could easily achieve this by using so you can notify from any task where you wish and have your signal be 275 | . 276 | 277 | This is however not a usecase we have, as most web services (be it servers or proxies) typically 278 | wish to run all its connections independent without critical failures. In such 279 | environments there is no need for top-down cancellation mechanisms. Therefore we have 280 | nothing built in as this allows us to keep the API and source code simpler, and on top of 281 | that gives us the freedom to change some internal details in the future without having 282 | to continue to support this usecase. 283 | 284 | Related to this is the usecase where you might want to early exit in case on of your 285 | critical background tasks exited (with or without an error), e.g. one of your server tasks. 286 | See [the `examples/hyper_panic.rs`](https://github.com/plabayo/tokio-graceful/tree/main/examples/hyper_panic.rs) on how to do that. 287 | That same approach is what you would do for shutting down from within a task, except that 288 | you might use `notify` instead of `oneshot`, or something similar. 289 | 290 | > Could you make a video explaining why you made this crate, how to use it and how it works? 291 | 292 | Most certainly. You can find the VOD at 293 | which is part of our Rust 101 video playlist: 294 | 295 | Do you want to learn Rust or improve your Rust knowledge? 296 | 297 | Check out and see if it can help you in that journey. 298 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | | Version | Supported | 6 | |----------|--------------------| 7 | | >= 0.0.0 | :white_check_mark: | 8 | 9 | ## Reporting a Vulnerability 10 | 11 | If you discover a vulnerability, please do the following: 12 | 13 | - E-mail your findings to security [at] plabayo [dot] tech. 14 | - Do not take advantage of the vulnerability or problem you have discovered, for example by downloading more data than necessary to demonstrate the vulnerability or deleting or modifying other people's data. 15 | - Do not reveal the problem to others until it has been resolved. 16 | - Do not use attacks on physical security, social engineering, distributed denial of service, spam or applications of third parties. 17 | - Do provide sufficient information to reproduce the problem, so we will be able to resolve it as quickly as possible. Complex vulnerabilities may require further explanation! 18 | 19 | -------------------------------------------------------------------------------- /deny.toml: -------------------------------------------------------------------------------- 1 | [advisories] 2 | vulnerability = "deny" 3 | unmaintained = "warn" 4 | notice = "warn" 5 | ignore = [] 6 | 7 | [licenses] 8 | unlicensed = "deny" 9 | allow = [] 10 | deny = [] 11 | copyleft = "warn" 12 | allow-osi-fsf-free = "either" 13 | confidence-threshold = 0.8 14 | 15 | [bans] 16 | multiple-versions = "warn" 17 | highlight = "all" 18 | skip-tree = [] 19 | 20 | [sources] 21 | unknown-registry = "warn" 22 | unknown-git = "warn" 23 | allow-git = [] 24 | -------------------------------------------------------------------------------- /examples/hyper.rs: -------------------------------------------------------------------------------- 1 | //! An example showcasing how to use [`tokio_graceful`] to gracefully shutdown a 2 | //! [`tokio`] application which makes use of [`hyper`] (0.14). 3 | //! 4 | //! Libraries such as [`axum`] are built on top of Hyper and thus 5 | //! [`tokio_graceful`] can be used to gracefully shutdown applications built on 6 | //! top of them. 7 | //! 8 | //! [`tokio_graceful`]: https://docs.rs/tokio-graceful 9 | //! [`tokio`]: https://docs.rs/tokio 10 | //! [`hyper`]: https://docs.rs/hyper/0.14/hyper 11 | //! [`axum`]: https://docs.rs/axum 12 | 13 | use std::convert::Infallible; 14 | use std::net::SocketAddr; 15 | use std::time::Duration; 16 | 17 | use bytes::Bytes; 18 | use http_body_util::Full; 19 | use hyper::server::conn::http1::Builder; 20 | use hyper::service::service_fn; 21 | use hyper::{body::Incoming, Request, Response}; 22 | use hyper_util::rt::TokioIo; 23 | use tokio::net::TcpListener; 24 | use tracing_subscriber::{fmt, prelude::*, EnvFilter}; 25 | 26 | #[tokio::main] 27 | async fn main() { 28 | tracing_subscriber::registry() 29 | .with(fmt::layer()) 30 | .with(EnvFilter::from_default_env()) 31 | .init(); 32 | 33 | let shutdown = tokio_graceful::Shutdown::default(); 34 | 35 | // Short for `shutdown.guard().into_spawn_task_fn(serve_tcp)` 36 | // In case you only wish to pass in a future (in contrast to a function) 37 | // as you do not care about being able to use the linked guard, 38 | // you can also use [`Shutdown::spawn_task`](https://docs.rs/tokio-graceful/latest/tokio_graceful/struct.Shutdown.html#method.spawn_task). 39 | shutdown.spawn_task_fn(serve_tcp); 40 | 41 | // use [`Shutdown::shutdown`](https://docs.rs/tokio-graceful/latest/tokio_graceful/struct.Shutdown.html#method.shutdown) 42 | // to wait for all guards to drop without any limit on how long to wait. 43 | match shutdown.shutdown_with_limit(Duration::from_secs(10)).await { 44 | Ok(elapsed) => { 45 | tracing::info!( 46 | "shutdown: gracefully {}s after shutdown signal received", 47 | elapsed.as_secs_f64() 48 | ); 49 | } 50 | Err(e) => { 51 | tracing::warn!("shutdown: forcefully due to timeout: {}", e); 52 | } 53 | } 54 | 55 | tracing::info!("Bye!"); 56 | } 57 | 58 | async fn serve_tcp(shutdown_guard: tokio_graceful::ShutdownGuard) { 59 | let addr: SocketAddr = ([127, 0, 0, 1], 8080).into(); 60 | 61 | let listener = TcpListener::bind(&addr).await.unwrap(); 62 | 63 | loop { 64 | let stream = tokio::select! { 65 | _ = shutdown_guard.cancelled() => { 66 | tracing::info!("signal received: initiate graceful shutdown"); 67 | break; 68 | } 69 | result = listener.accept() => { 70 | match result { 71 | Ok((stream, _)) => { 72 | stream 73 | } 74 | Err(e) => { 75 | tracing::warn!("accept error: {:?}", e); 76 | continue; 77 | } 78 | } 79 | } 80 | }; 81 | let stream = TokioIo::new(stream); 82 | 83 | shutdown_guard.spawn_task_fn(move |guard: tokio_graceful::ShutdownGuard| async move { 84 | let conn = Builder::new() 85 | .serve_connection(stream, service_fn(hello)); 86 | let mut conn = std::pin::pin!(conn); 87 | 88 | tokio::select! { 89 | _ = guard.cancelled() => { 90 | tracing::info!("signal received: initiate graceful shutdown"); 91 | conn.as_mut().graceful_shutdown(); 92 | } 93 | result = conn.as_mut() => { 94 | if let Err(err) = result { 95 | tracing::error!(error = &err as &dyn std::error::Error, "conn exited with error"); 96 | } 97 | return; 98 | } 99 | } 100 | if let Err(err) = conn.as_mut().await { 101 | tracing::error!(error = &err as &dyn std::error::Error, "conn exited with error after graceful shutdown"); 102 | } 103 | }); 104 | } 105 | } 106 | 107 | async fn hello(_: Request) -> Result>, Infallible> { 108 | tokio::time::sleep(std::time::Duration::from_secs(5)).await; 109 | Ok(Response::new(Full::from("Hello World!"))) 110 | } 111 | -------------------------------------------------------------------------------- /examples/hyper_panic.rs: -------------------------------------------------------------------------------- 1 | //! An example showcasing how to use [`tokio_graceful`] to gracefully shutdown a 2 | //! [`tokio`] application which makes use of [`hyper`] (0.14). 3 | //! 4 | //! Libraries such as [`axum`] are built on top of Hyper and thus 5 | //! [`tokio_graceful`] can be used to gracefully shutdown applications built on 6 | //! top of them. 7 | //! 8 | //! [`tokio_graceful`]: https://docs.rs/tokio-graceful 9 | //! [`tokio`]: https://docs.rs/tokio 10 | //! [`hyper`]: https://docs.rs/hyper/0.14/hyper 11 | //! [`axum`]: https://docs.rs/axum 12 | 13 | use std::convert::Infallible; 14 | use std::net::SocketAddr; 15 | use std::time::Duration; 16 | 17 | use bytes::Bytes; 18 | use http_body_util::Full; 19 | use hyper::server::conn::http1::Builder; 20 | use hyper::service::service_fn; 21 | use hyper::{body::Incoming, Request, Response}; 22 | use hyper_util::rt::TokioIo; 23 | use tokio::net::TcpListener; 24 | use tracing_subscriber::{fmt, prelude::*, EnvFilter}; 25 | 26 | #[tokio::main] 27 | async fn main() { 28 | tracing_subscriber::registry() 29 | .with(fmt::layer()) 30 | .with(EnvFilter::from_default_env()) 31 | .init(); 32 | 33 | // oneshot channel used to be able to trigger a shutdown 34 | // in case of an unexpected task exit 35 | let (task_exit_tx, task_exit_rx) = tokio::sync::oneshot::channel::<()>(); 36 | 37 | let shutdown = tokio_graceful::Shutdown::new(async move { 38 | tokio::select! { 39 | _ = task_exit_rx => { 40 | tracing::warn!("critical task exit observed, shutting down"); 41 | } 42 | _ = tokio_graceful::default_signal() => { 43 | tracing::info!("external exit signal received, shutting down"); 44 | } 45 | } 46 | }); 47 | 48 | // Short for `shutdown.guard().into_spawn_task_fn(serve_tcp)` 49 | // In case you only wish to pass in a future (in contrast to a function) 50 | // as you do not care about being able to use the linked guard, 51 | // you can also use [`Shutdown::spawn_task`](https://docs.rs/tokio-graceful/latest/tokio_graceful/struct.Shutdown.html#method.spawn_task). 52 | let server_handle = shutdown.spawn_task_fn(serve_tcp); 53 | 54 | // spawn a task that will trigger a shutdown in case of an error with our server, 55 | // a common reason for this could be because you have an issue at server setup 56 | // (e.g. port that you try to bind to is already in use) 57 | let shutdown_err_guard = shutdown.guard_weak(); 58 | tokio::spawn(async move { 59 | tokio::select! { 60 | _ = shutdown_err_guard.cancelled() => { 61 | // shutdown signal received, do nothing but exit this task 62 | return; 63 | } 64 | result = server_handle => { 65 | match result { 66 | Ok(_) => { 67 | tracing::info!("server exited, triggering manual shutdown"); 68 | } 69 | Err(err) => { 70 | tracing::error!(error = &err as &dyn std::error::Error, "server exited, triggering error shutdown"); 71 | } 72 | } 73 | } 74 | } 75 | task_exit_tx.send(()).unwrap(); 76 | }); 77 | 78 | // use [`Shutdown::shutdown`](https://docs.rs/tokio-graceful/latest/tokio_graceful/struct.Shutdown.html#method.shutdown) 79 | // to wait for all guards to drop without any limit on how long to wait. 80 | match shutdown.shutdown_with_limit(Duration::from_secs(10)).await { 81 | Ok(elapsed) => { 82 | tracing::info!( 83 | "shutdown: gracefully {}s after shutdown signal received", 84 | elapsed.as_secs_f64() 85 | ); 86 | } 87 | Err(e) => { 88 | tracing::warn!( 89 | error = &e as &dyn std::error::Error, 90 | "shutdown: forcefully due to timeout" 91 | ); 92 | } 93 | } 94 | 95 | tracing::info!("Bye!"); 96 | } 97 | 98 | async fn serve_tcp(shutdown_guard: tokio_graceful::ShutdownGuard) { 99 | let addr: SocketAddr = ([127, 0, 0, 1], 8080).into(); 100 | 101 | let listener = TcpListener::bind(&addr).await.unwrap(); 102 | 103 | loop { 104 | let stream = tokio::select! { 105 | _ = shutdown_guard.cancelled() => { 106 | tracing::info!("signal received: initiate graceful shutdown"); 107 | break; 108 | } 109 | result = listener.accept() => { 110 | match result { 111 | Ok((stream, _)) => { 112 | stream 113 | } 114 | Err(e) => { 115 | tracing::warn!("accept error: {:?}", e); 116 | continue; 117 | } 118 | } 119 | } 120 | }; 121 | let stream = TokioIo::new(stream); 122 | 123 | shutdown_guard.spawn_task_fn(move |guard: tokio_graceful::ShutdownGuard| async move { 124 | let conn = Builder::new() 125 | .serve_connection(stream, service_fn(hello)); 126 | let mut conn = std::pin::pin!(conn); 127 | 128 | tokio::select! { 129 | _ = guard.cancelled() => { 130 | tracing::info!("signal received: initiate graceful shutdown"); 131 | conn.as_mut().graceful_shutdown(); 132 | } 133 | result = conn.as_mut() => { 134 | if let Err(err) = result { 135 | tracing::error!(error = &err as &dyn std::error::Error, "conn exited with error"); 136 | } 137 | return; 138 | } 139 | } 140 | if let Err(err) = conn.as_mut().await { 141 | tracing::error!(error = &err as &dyn std::error::Error, "conn exited with error after graceful shutdown"); 142 | } 143 | }); 144 | } 145 | } 146 | 147 | async fn hello(_: Request) -> Result>, Infallible> { 148 | tokio::time::sleep(std::time::Duration::from_secs(5)).await; 149 | Ok(Response::new(Full::from("Hello World!"))) 150 | } 151 | -------------------------------------------------------------------------------- /examples/hyper_with_overwrite_fn.rs: -------------------------------------------------------------------------------- 1 | //! An example showcasing how to use [`tokio_graceful`] to gracefully shutdown a 2 | //! [`tokio`] application which makes use of [`hyper`] (0.14). 3 | //! 4 | //! Libraries such as [`axum`] are built on top of Hyper and thus 5 | //! [`tokio_graceful`] can be used to gracefully shutdown applications built on 6 | //! top of them. 7 | //! 8 | //! [`tokio_graceful`]: https://docs.rs/tokio-graceful 9 | //! [`tokio`]: https://docs.rs/tokio 10 | //! [`hyper`]: https://docs.rs/hyper/0.14/hyper 11 | //! [`axum`]: https://docs.rs/axum 12 | 13 | use std::convert::Infallible; 14 | use std::net::SocketAddr; 15 | use std::time::Duration; 16 | 17 | use bytes::Bytes; 18 | use http_body_util::Full; 19 | use hyper::server::conn::http1::Builder; 20 | use hyper::service::service_fn; 21 | use hyper::{body::Incoming, Request, Response}; 22 | use hyper_util::rt::TokioIo; 23 | use tokio::net::TcpListener; 24 | use tracing_subscriber::{fmt, prelude::*, EnvFilter}; 25 | 26 | #[tokio::main] 27 | async fn main() { 28 | tracing_subscriber::registry() 29 | .with(fmt::layer()) 30 | .with(EnvFilter::from_default_env()) 31 | .init(); 32 | 33 | let shutdown = tokio_graceful::Shutdown::builder() 34 | .with_delay(Duration::from_secs(2)) 35 | .with_overwrite_fn(tokio::signal::ctrl_c) 36 | .build(); 37 | 38 | // Short for `shutdown.guard().into_spawn_task_fn(serve_tcp)` 39 | // In case you only wish to pass in a future (in contrast to a function) 40 | // as you do not care about being able to use the linked guard, 41 | // you can also use [`Shutdown::spawn_task`](https://docs.rs/tokio-graceful/latest/tokio_graceful/struct.Shutdown.html#method.spawn_task). 42 | shutdown.spawn_task_fn(serve_tcp); 43 | 44 | // use [`Shutdown::shutdown`](https://docs.rs/tokio-graceful/latest/tokio_graceful/struct.Shutdown.html#method.shutdown) 45 | // to wait for all guards to drop without any limit on how long to wait. 46 | match shutdown.shutdown_with_limit(Duration::from_secs(10)).await { 47 | Ok(elapsed) => { 48 | tracing::info!( 49 | "shutdown: gracefully {}s after shutdown signal received", 50 | elapsed.as_secs_f64() 51 | ); 52 | } 53 | Err(e) => { 54 | tracing::warn!("shutdown: forcefully due to timeout: {}", e); 55 | } 56 | } 57 | 58 | tracing::info!("Bye!"); 59 | } 60 | 61 | async fn serve_tcp(shutdown_guard: tokio_graceful::ShutdownGuard) { 62 | let addr: SocketAddr = ([127, 0, 0, 1], 8080).into(); 63 | 64 | let listener = TcpListener::bind(&addr).await.unwrap(); 65 | 66 | loop { 67 | let stream = tokio::select! { 68 | _ = shutdown_guard.cancelled() => { 69 | tracing::info!("signal received: exit serve tcp accept loopt"); 70 | break; 71 | } 72 | result = listener.accept() => { 73 | match result { 74 | Ok((stream, _)) => { 75 | stream 76 | } 77 | Err(e) => { 78 | tracing::warn!("accept error: {:?}", e); 79 | continue; 80 | } 81 | } 82 | } 83 | }; 84 | let stream = TokioIo::new(stream); 85 | 86 | shutdown_guard.spawn_task_fn(move |guard: tokio_graceful::ShutdownGuard| async move { 87 | let conn = Builder::new() 88 | .serve_connection(stream, service_fn(hello)); 89 | let mut conn = std::pin::pin!(conn); 90 | 91 | tokio::select! { 92 | _ = guard.cancelled() => { 93 | tracing::info!("signal received: initiate graceful shutdown"); 94 | conn.as_mut().graceful_shutdown(); 95 | } 96 | result = conn.as_mut() => { 97 | if let Err(err) = result { 98 | tracing::error!(error = &err as &dyn std::error::Error, "conn exited with error"); 99 | } 100 | return; 101 | } 102 | } 103 | if let Err(err) = conn.as_mut().await { 104 | tracing::error!(error = &err as &dyn std::error::Error, "conn exited with error after graceful shutdown"); 105 | } 106 | }); 107 | } 108 | tracing::info!("serve tcp fn exit"); 109 | } 110 | 111 | async fn hello(_: Request) -> Result>, Infallible> { 112 | tokio::time::sleep(std::time::Duration::from_secs(5)).await; 113 | Ok(Response::new(Full::from("Hello World!"))) 114 | } 115 | -------------------------------------------------------------------------------- /examples/hyper_with_shutdown_delay.rs: -------------------------------------------------------------------------------- 1 | //! An example showcasing how to use [`tokio_graceful`] to gracefully shutdown a 2 | //! [`tokio`] application which makes use of [`hyper`] (0.14). 3 | //! 4 | //! Libraries such as [`axum`] are built on top of Hyper and thus 5 | //! [`tokio_graceful`] can be used to gracefully shutdown applications built on 6 | //! top of them. 7 | //! 8 | //! [`tokio_graceful`]: https://docs.rs/tokio-graceful 9 | //! [`tokio`]: https://docs.rs/tokio 10 | //! [`hyper`]: https://docs.rs/hyper/0.14/hyper 11 | //! [`axum`]: https://docs.rs/axum 12 | 13 | use std::convert::Infallible; 14 | use std::net::SocketAddr; 15 | use std::time::Duration; 16 | 17 | use bytes::Bytes; 18 | use http_body_util::Full; 19 | use hyper::server::conn::http1::Builder; 20 | use hyper::service::service_fn; 21 | use hyper::{body::Incoming, Request, Response}; 22 | use hyper_util::rt::TokioIo; 23 | use tokio::net::TcpListener; 24 | use tracing_subscriber::{fmt, prelude::*, EnvFilter}; 25 | 26 | #[tokio::main] 27 | async fn main() { 28 | tracing_subscriber::registry() 29 | .with(fmt::layer()) 30 | .with(EnvFilter::from_default_env()) 31 | .init(); 32 | 33 | let shutdown = tokio_graceful::Shutdown::builder() 34 | .with_delay(Duration::from_secs(5)) 35 | .build(); 36 | 37 | // Short for `shutdown.guard().into_spawn_task_fn(serve_tcp)` 38 | // In case you only wish to pass in a future (in contrast to a function) 39 | // as you do not care about being able to use the linked guard, 40 | // you can also use [`Shutdown::spawn_task`](https://docs.rs/tokio-graceful/latest/tokio_graceful/struct.Shutdown.html#method.spawn_task). 41 | shutdown.spawn_task_fn(serve_tcp); 42 | 43 | // use [`Shutdown::shutdown`](https://docs.rs/tokio-graceful/latest/tokio_graceful/struct.Shutdown.html#method.shutdown) 44 | // to wait for all guards to drop without any limit on how long to wait. 45 | match shutdown.shutdown_with_limit(Duration::from_secs(10)).await { 46 | Ok(elapsed) => { 47 | tracing::info!( 48 | "shutdown: gracefully {}s after shutdown signal received", 49 | elapsed.as_secs_f64() 50 | ); 51 | } 52 | Err(e) => { 53 | tracing::warn!("shutdown: forcefully due to timeout: {}", e); 54 | } 55 | } 56 | 57 | tracing::info!("Bye!"); 58 | } 59 | 60 | async fn serve_tcp(shutdown_guard: tokio_graceful::ShutdownGuard) { 61 | let addr: SocketAddr = ([127, 0, 0, 1], 8080).into(); 62 | 63 | let listener = TcpListener::bind(&addr).await.unwrap(); 64 | 65 | loop { 66 | let stream = tokio::select! { 67 | _ = shutdown_guard.cancelled() => { 68 | tracing::info!("signal received: initiate graceful shutdown"); 69 | break; 70 | } 71 | result = listener.accept() => { 72 | match result { 73 | Ok((stream, _)) => { 74 | stream 75 | } 76 | Err(e) => { 77 | tracing::warn!("accept error: {:?}", e); 78 | continue; 79 | } 80 | } 81 | } 82 | }; 83 | let stream = TokioIo::new(stream); 84 | 85 | shutdown_guard.spawn_task_fn(move |guard: tokio_graceful::ShutdownGuard| async move { 86 | let conn = Builder::new() 87 | .serve_connection(stream, service_fn(hello)); 88 | let mut conn = std::pin::pin!(conn); 89 | 90 | tokio::select! { 91 | _ = guard.cancelled() => { 92 | tracing::info!("signal received: initiate graceful shutdown"); 93 | conn.as_mut().graceful_shutdown(); 94 | } 95 | result = conn.as_mut() => { 96 | if let Err(err) = result { 97 | tracing::error!(error = &err as &dyn std::error::Error, "conn exited with error"); 98 | } 99 | return; 100 | } 101 | } 102 | if let Err(err) = conn.as_mut().await { 103 | tracing::error!(error = &err as &dyn std::error::Error, "conn exited with error after graceful shutdown"); 104 | } 105 | }); 106 | } 107 | } 108 | 109 | async fn hello(_: Request) -> Result>, Infallible> { 110 | tokio::time::sleep(std::time::Duration::from_secs(5)).await; 111 | Ok(Response::new(Full::from("Hello World!"))) 112 | } 113 | -------------------------------------------------------------------------------- /examples/tokio_tcp.rs: -------------------------------------------------------------------------------- 1 | //! An example showcasing how to use [`tokio_graceful`] to gracefully shutdown a 2 | //! [`tokio`] application which makes use of [`tokio::net::TcpListener`]. 3 | //! 4 | //! [`tokio_graceful`]: https://docs.rs/tokio-graceful 5 | //! [`tokio`]: https://docs.rs/tokio 6 | //! [`tokio::net::TcpListener`]: https://docs.rs/tokio/latest/tokio/net/struct.TcpListener.html 7 | 8 | use std::time::Duration; 9 | 10 | use tokio::net::TcpListener; 11 | use tracing_subscriber::{fmt, prelude::*, EnvFilter}; 12 | 13 | #[tokio::main] 14 | async fn main() { 15 | tracing_subscriber::registry() 16 | .with(fmt::layer()) 17 | .with(EnvFilter::from_default_env()) 18 | .init(); 19 | 20 | let shutdown = tokio_graceful::Shutdown::default(); 21 | 22 | // Short for `shutdown.guard().into_spawn_task_fn(serve_tcp)` 23 | // In case you only wish to pass in a future (in contrast to a function) 24 | // as you do not care about being able to use the linked guard, 25 | // you can also use [`Shutdown::spawn_task`](https://docs.rs/tokio-graceful/latest/tokio_graceful/struct.Shutdown.html#method.spawn_task). 26 | shutdown.spawn_task_fn(serve_tcp); 27 | 28 | // use [`Shutdown::shutdown`](https://docs.rs/tokio-graceful/latest/tokio_graceful/struct.Shutdown.html#method.shutdown) 29 | // to wait for all guards to drop without any limit on how long to wait. 30 | match shutdown.shutdown_with_limit(Duration::from_secs(10)).await { 31 | Ok(elapsed) => { 32 | tracing::info!( 33 | "shutdown: gracefully {}s after shutdown signal received", 34 | elapsed.as_secs_f64() 35 | ); 36 | } 37 | Err(e) => { 38 | tracing::warn!("shutdown: forcefully due to timeout: {}", e); 39 | } 40 | } 41 | 42 | tracing::info!("Bye!"); 43 | } 44 | 45 | async fn serve_tcp(shutdown_guard: tokio_graceful::ShutdownGuard) { 46 | let listener = TcpListener::bind("127.0.0.1:8080").await.unwrap(); 47 | tracing::info!("listening on {}", listener.local_addr().unwrap()); 48 | 49 | loop { 50 | let shutdown_guard = shutdown_guard.clone(); 51 | tokio::select! { 52 | _ = shutdown_guard.cancelled() => { 53 | tracing::info!("signal received: initiate graceful shutdown"); 54 | break; 55 | } 56 | result = listener.accept() => { 57 | match result { 58 | Ok((socket, _)) => { 59 | tokio::spawn(async move { 60 | // NOTE, make sure to pass a clone of the shutdown guard to this function 61 | // or any of its children in case you wish to be able to cancel a long running process should the 62 | // shutdown signal be received and you know that your task might not finish on time. 63 | // This allows you to at least leave it behind in a consistent state such that another 64 | // process can pick up where you left that task. 65 | let (mut reader, mut writer) = tokio::io::split(socket); 66 | let _ = tokio::io::copy(&mut reader, &mut writer).await; 67 | drop(shutdown_guard); 68 | }); 69 | } 70 | Err(e) => { 71 | tracing::warn!("accept error: {:?}", e); 72 | } 73 | } 74 | } 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /examples/tokio_tcp_with_overwrite_fn.rs: -------------------------------------------------------------------------------- 1 | //! An example showcasing how to use [`tokio_graceful`] to gracefully shutdown a 2 | //! [`tokio`] application which makes use of [`tokio::net::TcpListener`]. 3 | //! 4 | //! [`tokio_graceful`]: https://docs.rs/tokio-graceful 5 | //! [`tokio`]: https://docs.rs/tokio 6 | //! [`tokio::net::TcpListener`]: https://docs.rs/tokio/latest/tokio/net/struct.TcpListener.html 7 | 8 | use std::time::Duration; 9 | 10 | use tokio::net::TcpListener; 11 | use tracing_subscriber::{fmt, prelude::*, EnvFilter}; 12 | 13 | #[tokio::main] 14 | async fn main() { 15 | tracing_subscriber::registry() 16 | .with(fmt::layer()) 17 | .with(EnvFilter::from_default_env()) 18 | .init(); 19 | 20 | let shutdown = tokio_graceful::Shutdown::builder() 21 | .with_overwrite_fn(tokio::signal::ctrl_c) 22 | .build(); 23 | 24 | // Short for `shutdown.guard().into_spawn_task_fn(serve_tcp)` 25 | // In case you only wish to pass in a future (in contrast to a function) 26 | // as you do not care about being able to use the linked guard, 27 | // you can also use [`Shutdown::spawn_task`](https://docs.rs/tokio-graceful/latest/tokio_graceful/struct.Shutdown.html#method.spawn_task). 28 | shutdown.spawn_task_fn(serve_tcp); 29 | 30 | // use [`Shutdown::shutdown`](https://docs.rs/tokio-graceful/latest/tokio_graceful/struct.Shutdown.html#method.shutdown) 31 | // to wait for all guards to drop without any limit on how long to wait. 32 | match shutdown.shutdown_with_limit(Duration::from_secs(10)).await { 33 | Ok(elapsed) => { 34 | tracing::info!( 35 | "shutdown: gracefully {}s after shutdown signal received", 36 | elapsed.as_secs_f64() 37 | ); 38 | } 39 | Err(e) => { 40 | tracing::warn!("shutdown: forcefully due to timeout: {}", e); 41 | } 42 | } 43 | 44 | tracing::info!("Bye!"); 45 | } 46 | 47 | async fn serve_tcp(shutdown_guard: tokio_graceful::ShutdownGuard) { 48 | let listener = TcpListener::bind("127.0.0.1:8080").await.unwrap(); 49 | tracing::info!("listening on {}", listener.local_addr().unwrap()); 50 | 51 | loop { 52 | let shutdown_guard = shutdown_guard.clone(); 53 | tokio::select! { 54 | _ = shutdown_guard.cancelled() => { 55 | tracing::info!("signal received: initiate graceful shutdown"); 56 | break; 57 | } 58 | result = listener.accept() => { 59 | match result { 60 | Ok((socket, _)) => { 61 | tokio::spawn(async move { 62 | // NOTE, make sure to pass a clone of the shutdown guard to this function 63 | // or any of its children in case you wish to be able to cancel a long running process should the 64 | // shutdown signal be received and you know that your task might not finish on time. 65 | // This allows you to at least leave it behind in a consistent state such that another 66 | // process can pick up where you left that task. 67 | let (mut reader, mut writer) = tokio::io::split(socket); 68 | let _ = tokio::io::copy(&mut reader, &mut writer).await; 69 | drop(shutdown_guard); 70 | }); 71 | } 72 | Err(e) => { 73 | tracing::warn!("accept error: {:?}", e); 74 | } 75 | } 76 | } 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /examples/waitgroup.rs: -------------------------------------------------------------------------------- 1 | //! An example showcasing how to use [`tokio_graceful`] to 2 | //! await ongoing tasks before shutting down. 3 | //! 4 | //! Some people know this concept better as Waitgroup. 5 | //! 6 | //! In languages like Golang this is a very common pattern 7 | //! for waiting for all tasks to finish before shutting down, 8 | //! and is even part of their standard library. 9 | //! 10 | //! [`tokio_graceful`]: https://docs.rs/tokio-graceful 11 | 12 | use std::time::Duration; 13 | 14 | use tokio_graceful::Shutdown; 15 | 16 | #[tokio::main] 17 | async fn main() { 18 | let shutdown = Shutdown::no_signal(); 19 | 20 | const MAX: u64 = 5; 21 | 22 | for countdown in 0..=MAX { 23 | // NOTE: you can also manually create 24 | // a guard using `shutdown.guard()` and spawn 25 | // you async tasks manually in case you do not wish to run these 26 | // using `tokio_graceful::sync::spawn` (Tokio by default). 27 | let sleep = tokio::time::sleep(Duration::from_secs(countdown)); 28 | shutdown.spawn_task(async move { 29 | sleep.await; 30 | if countdown == MAX { 31 | println!("Go!"); 32 | } else { 33 | println!("{}...", MAX - countdown); 34 | } 35 | }); 36 | } 37 | 38 | shutdown.shutdown().await; 39 | println!("Success :)"); 40 | } 41 | -------------------------------------------------------------------------------- /justfile: -------------------------------------------------------------------------------- 1 | fmt: 2 | cargo fmt --all 3 | 4 | sort: 5 | cargo sort --grouped 6 | 7 | lint: fmt sort 8 | 9 | check: 10 | cargo check --all-targets 11 | 12 | clippy: 13 | cargo clippy --all-targets 14 | 15 | clippy-fix: 16 | cargo clippy --fix 17 | 18 | typos: 19 | typos -w 20 | 21 | doc: 22 | RUSTDOCFLAGS="-D rustdoc::broken-intra-doc-links" cargo doc --no-deps 23 | 24 | doc-open: 25 | RUSTDOCFLAGS="-D rustdoc::broken-intra-doc-links" cargo doc --no-deps --open 26 | 27 | test: 28 | cargo test 29 | 30 | test-loom: 31 | RUSTFLAGS="--cfg loom" cargo test test_loom_sender_trigger 32 | 33 | qa: lint check clippy doc test test-loom 34 | -------------------------------------------------------------------------------- /rust-toolchain.toml: -------------------------------------------------------------------------------- 1 | [toolchain] 2 | channel = "stable" 3 | -------------------------------------------------------------------------------- /src/guard.rs: -------------------------------------------------------------------------------- 1 | use std::{future::Future, mem::ManuallyDrop}; 2 | 3 | use crate::{ 4 | sync::{Arc, AtomicUsize, JoinHandle, Ordering}, 5 | trigger::{Receiver, Sender}, 6 | }; 7 | 8 | /// A guard, linked to a [`Shutdown`] struct, 9 | /// prevents the [`Shutdown::shutdown`] future from completing. 10 | /// 11 | /// Can be cloned to create multiple [`ShutdownGuard`]s 12 | /// and can be downgraded to a [`WeakShutdownGuard`] to 13 | /// no longer prevent the [`Shutdown::shutdown`] future from completing. 14 | /// 15 | /// [`Shutdown`]: crate::Shutdown 16 | /// [`Shutdown::shutdown`]: crate::Shutdown::shutdown 17 | #[derive(Debug)] 18 | pub struct ShutdownGuard(ManuallyDrop); 19 | 20 | /// A weak guard, linked to a [`Shutdown`] struct, 21 | /// is similar to a [`ShutdownGuard`] but does not 22 | /// prevent the [`Shutdown::shutdown`] future from completing. 23 | /// 24 | /// [`Shutdown`]: crate::Shutdown 25 | /// [`Shutdown::shutdown`]: crate::Shutdown::shutdown 26 | #[derive(Debug, Clone)] 27 | pub struct WeakShutdownGuard { 28 | pub(crate) trigger_rx: Receiver, 29 | pub(crate) shutdown_signal_trigger_rx: Option, 30 | pub(crate) zero_tx: Sender, 31 | pub(crate) ref_count: Arc, 32 | } 33 | 34 | impl ShutdownGuard { 35 | pub(crate) fn new( 36 | trigger_rx: Receiver, 37 | shutdown_signal_trigger_rx: Option, 38 | zero_tx: Sender, 39 | ref_count: Arc, 40 | ) -> Self { 41 | let value = ref_count.fetch_add(1, Ordering::SeqCst); 42 | tracing::trace!("new shutdown guard: ref_count+1: {}", value + 1); 43 | Self(ManuallyDrop::new(WeakShutdownGuard::new( 44 | trigger_rx, 45 | shutdown_signal_trigger_rx, 46 | zero_tx, 47 | ref_count, 48 | ))) 49 | } 50 | 51 | /// Returns a Future that gets fulfilled when cancellation (shutdown) is requested 52 | /// and the delay (if any) duration has been awaited. 53 | /// 54 | /// Use [`Self::shutdown_signal_triggered`] for tasks that do not 55 | /// require this opt-in delay buffer duration. 56 | /// 57 | /// The future will complete immediately if the token is already cancelled when this method is called. 58 | /// 59 | /// # Cancel safety 60 | /// 61 | /// This method is cancel safe. 62 | /// 63 | /// # Panics 64 | /// 65 | /// This method panics if the iternal mutex 66 | /// is poisoned while being used. 67 | #[inline] 68 | pub async fn cancelled(&self) { 69 | self.0.cancelled().await 70 | } 71 | 72 | /// Returns a Future that gets fulfilled when cancellation (shutdown) is requested. 73 | /// 74 | /// Use [`Self::cancelled`] if you want to make sure the future 75 | /// only completes when the buffer delay has been awaited. 76 | /// 77 | /// In case no delay has been configured for the parent `Shutdown`, 78 | /// this function will be equal in behaviour to [`Self::cancelled`]. 79 | /// 80 | /// The future will complete immediately if the token is already cancelled when this method is called. 81 | /// 82 | /// # Cancel safety 83 | /// 84 | /// This method is cancel safe. 85 | /// 86 | /// # Panics 87 | /// 88 | /// This method panics if the iternal mutex 89 | /// is poisoned while being used. 90 | #[inline] 91 | pub async fn shutdown_signal_triggered(&self) { 92 | self.0.shutdown_signal_triggered().await 93 | } 94 | 95 | /// Returns a [`crate::sync::JoinHandle`] that can be awaited on 96 | /// to wait for the spawned task to complete. See 97 | /// [`crate::sync::spawn`] for more information. 98 | pub fn spawn_task(&self, task: T) -> JoinHandle 99 | where 100 | T: Future + Send + 'static, 101 | T::Output: Send + 'static, 102 | { 103 | let guard = self.clone(); 104 | crate::sync::spawn(async move { 105 | let output = task.await; 106 | drop(guard); 107 | output 108 | }) 109 | } 110 | 111 | /// Returns a Tokio [`crate::sync::JoinHandle`] that can be awaited on 112 | /// to wait for the spawned task (future) to complete. See 113 | /// [`crate::sync::spawn`] for more information. 114 | /// 115 | /// In contrast to [`ShutdownGuard::spawn_task`] this method consumes the guard, 116 | /// ensuring the guard is dropped once the task future is fulfilled. 117 | /// [`ShutdownGuard::spawn_task`]: crate::ShutdownGuard::spawn_task 118 | pub fn into_spawn_task(self, task: T) -> JoinHandle 119 | where 120 | T: Future + Send + 'static, 121 | T::Output: Send + 'static, 122 | { 123 | crate::sync::spawn(async move { 124 | let output = task.await; 125 | drop(self); 126 | output 127 | }) 128 | } 129 | 130 | /// Returns a Tokio [`crate::sync::JoinHandle`] that can be awaited on 131 | /// to wait for the spawned task (fn) to complete. See 132 | /// [`crate::sync::spawn`] for more information. 133 | pub fn spawn_task_fn(&self, task: F) -> JoinHandle 134 | where 135 | F: FnOnce(ShutdownGuard) -> T + Send + 'static, 136 | T: Future + Send + 'static, 137 | T::Output: Send + 'static, 138 | { 139 | let guard = self.clone(); 140 | crate::sync::spawn(async move { task(guard).await }) 141 | } 142 | 143 | /// Returns a Tokio [`crate::sync::JoinHandle`] that can be awaited on 144 | /// to wait for the spawned task (fn) to complete. See 145 | /// [`crate::sync::spawn`] for more information. 146 | /// 147 | /// In contrast to [`ShutdownGuard::spawn_task_fn`] this method consumes the guard, 148 | /// ensuring the guard is dropped once the task future is fulfilled. 149 | /// [`ShutdownGuard::spawn_task_fn`]: crate::ShutdownGuard::spawn_task_fn 150 | pub fn into_spawn_task_fn(self, task: F) -> JoinHandle 151 | where 152 | F: FnOnce(ShutdownGuard) -> T + Send + 'static, 153 | T: Future + Send + 'static, 154 | T::Output: Send + 'static, 155 | { 156 | crate::sync::spawn(async move { task(self).await }) 157 | } 158 | 159 | /// Downgrades the guard to a [`WeakShutdownGuard`], 160 | /// ensuring that the guard no longer prevents the 161 | /// [`Shutdown::shutdown`] future from completing. 162 | /// 163 | /// [`Shutdown::shutdown`]: crate::Shutdown::shutdown 164 | pub fn downgrade(mut self) -> WeakShutdownGuard { 165 | unsafe { ManuallyDrop::take(&mut self.0) } 166 | } 167 | 168 | /// Clones the guard as a [`WeakShutdownGuard`], 169 | /// ensuring that the cloned guard does not prevent the 170 | /// [`Shutdown::shutdown`] future from completing. 171 | /// 172 | /// [`Shutdown::shutdown`]: crate::Shutdown::shutdown 173 | pub fn clone_weak(&self) -> WeakShutdownGuard { 174 | ManuallyDrop::into_inner(self.0.clone()) 175 | } 176 | } 177 | 178 | impl Clone for ShutdownGuard { 179 | fn clone(&self) -> Self { 180 | let value = &self.0.ref_count.fetch_add(1, Ordering::SeqCst); 181 | tracing::trace!("clone shutdown guard: ref_count+1: {}", value + 1); 182 | Self(self.0.clone()) 183 | } 184 | } 185 | 186 | impl From for ShutdownGuard { 187 | fn from(weak_guard: WeakShutdownGuard) -> ShutdownGuard { 188 | let value = weak_guard.ref_count.fetch_add(1, Ordering::SeqCst); 189 | tracing::trace!("from weak shutdown guard: ref_count+1: {}", value + 1); 190 | Self(ManuallyDrop::new(weak_guard)) 191 | } 192 | } 193 | 194 | impl Drop for ShutdownGuard { 195 | fn drop(&mut self) { 196 | let cnt = self.0.ref_count.fetch_sub(1, Ordering::SeqCst); 197 | tracing::trace!("drop shutdown guard: ref_count-1: {}", cnt - 1); 198 | if cnt == 1 { 199 | self.0.zero_tx.trigger(); 200 | } 201 | } 202 | } 203 | 204 | impl WeakShutdownGuard { 205 | pub(crate) fn new( 206 | trigger_rx: Receiver, 207 | shutdown_signal_trigger_rx: Option, 208 | zero_tx: Sender, 209 | ref_count: Arc, 210 | ) -> Self { 211 | Self { 212 | trigger_rx, 213 | shutdown_signal_trigger_rx, 214 | zero_tx, 215 | ref_count, 216 | } 217 | } 218 | 219 | /// Returns a Future that gets fulfilled when cancellation (shutdown) is requested 220 | /// and the delay (buffer) duration has been awaited on. 221 | /// 222 | /// Use [`Self::shutdown_signal_triggered`] in case you want to get 223 | /// a future which is triggered immediately when the shutdown signal is received, 224 | /// without waiting for the delay duration first. 225 | /// 226 | /// The future will complete immediately if the token is already cancelled when this method is called. 227 | /// 228 | /// # Cancel safety 229 | /// 230 | /// This method is cancel safe. 231 | /// 232 | /// # Panics 233 | /// 234 | /// This method panics if the iternal mutex 235 | /// is poisoned while being used. 236 | #[inline] 237 | pub async fn cancelled(&self) { 238 | self.trigger_rx.clone().await; 239 | } 240 | 241 | /// Returns a Future that gets fulfilled when cancellation (shutdown) is requested 242 | /// without awaiting the delay duration first, if one is set. 243 | /// 244 | /// In case no delay has been configured for the parent `Shutdown`, 245 | /// this function will be equal in behaviour to [`Self::cancelled`]. 246 | /// 247 | /// Use [`Self::cancelled`] in case you want to get 248 | /// a future which is triggered when the shutdown signal is received 249 | /// and thethe delay duration is awaited. 250 | /// 251 | /// The future will complete immediately if the token is already cancelled when this method is called. 252 | /// 253 | /// # Cancel safety 254 | /// 255 | /// This method is cancel safe. 256 | /// 257 | /// # Panics 258 | /// 259 | /// This method panics if the iternal mutex 260 | /// is poisoned while being used. 261 | #[inline] 262 | pub async fn shutdown_signal_triggered(&self) { 263 | self.shutdown_signal_trigger_rx 264 | .clone() 265 | .unwrap_or_else(|| self.trigger_rx.clone()) 266 | .await 267 | } 268 | 269 | /// Returns a Future that gets fulfilled when cancellation (shutdown) is requested. 270 | /// 271 | /// In contrast to [`ShutdownGuard::cancelled`] this method consumes the guard, 272 | /// ensuring the guard is dropped once the future is fulfilled. 273 | /// 274 | /// The future will complete immediately if the token is already cancelled when this method is called. 275 | /// 276 | /// # Cancel safety 277 | /// 278 | /// This method is cancel safe. 279 | /// 280 | /// # Panics 281 | /// 282 | /// This method panics if the iternal mutex 283 | /// is poisoned while being used. 284 | #[inline] 285 | pub async fn into_cancelled(self) { 286 | self.cancelled().await; 287 | } 288 | 289 | /// Upgrades the weak guard to a [`ShutdownGuard`], 290 | /// ensuring that the guard has to be dropped prior to 291 | /// being able to complete the [`Shutdown::shutdown`] future. 292 | /// 293 | /// [`Shutdown::shutdown`]: crate::Shutdown::shutdown 294 | #[inline] 295 | pub fn upgrade(self) -> ShutdownGuard { 296 | self.into() 297 | } 298 | } 299 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![doc = include_str!("../README.md")] 2 | #![warn( 3 | clippy::all, 4 | clippy::dbg_macro, 5 | clippy::todo, 6 | clippy::empty_enum, 7 | clippy::enum_glob_use, 8 | clippy::mem_forget, 9 | clippy::unused_self, 10 | clippy::filter_map_next, 11 | clippy::needless_continue, 12 | clippy::needless_borrow, 13 | clippy::match_wildcard_for_single_variants, 14 | clippy::if_let_mutex, 15 | clippy::await_holding_lock, 16 | clippy::match_on_vec_items, 17 | clippy::imprecise_flops, 18 | clippy::suboptimal_flops, 19 | clippy::lossy_float_literal, 20 | clippy::rest_pat_in_fully_bound_structs, 21 | clippy::fn_params_excessive_bools, 22 | clippy::exit, 23 | clippy::inefficient_to_string, 24 | clippy::linkedlist, 25 | clippy::macro_use_imports, 26 | clippy::option_option, 27 | clippy::verbose_file_reads, 28 | clippy::unnested_or_patterns, 29 | rust_2018_idioms, 30 | future_incompatible, 31 | nonstandard_style, 32 | missing_docs 33 | )] 34 | #![allow(elided_lifetimes_in_paths, clippy::type_complexity)] 35 | #![cfg_attr(test, allow(clippy::float_cmp))] 36 | #![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg))] 37 | 38 | mod guard; 39 | pub use guard::{ShutdownGuard, WeakShutdownGuard}; 40 | 41 | mod shutdown; 42 | #[cfg(not(loom))] 43 | pub use shutdown::default_signal; 44 | pub use shutdown::{Shutdown, ShutdownBuilder}; 45 | 46 | pub(crate) mod sync; 47 | pub(crate) mod trigger; 48 | 49 | #[doc = include_str!("../README.md")] 50 | #[cfg(doctest)] 51 | pub struct ReadmeDoctests; 52 | 53 | #[cfg(test)] 54 | mod tests { 55 | use std::time::Duration; 56 | 57 | use tokio::sync::oneshot; 58 | 59 | use super::*; 60 | 61 | #[tokio::test] 62 | async fn test_shutdown_nope() { 63 | let (tx, rx) = oneshot::channel::<()>(); 64 | let shutdown = Shutdown::new(async { 65 | rx.await.unwrap(); 66 | }); 67 | crate::sync::spawn(async move { 68 | tx.send(()).unwrap(); 69 | }); 70 | shutdown.shutdown().await; 71 | } 72 | 73 | #[tokio::test] 74 | async fn test_shutdown_nope_limit() { 75 | let (tx, rx) = oneshot::channel::<()>(); 76 | let shutdown = Shutdown::new(async { 77 | rx.await.unwrap(); 78 | }); 79 | crate::sync::spawn(async move { 80 | tx.send(()).unwrap(); 81 | }); 82 | shutdown 83 | .shutdown_with_limit(Duration::from_secs(60)) 84 | .await 85 | .unwrap(); 86 | } 87 | 88 | #[tokio::test] 89 | async fn test_shutdown_guard_cancel_safety() { 90 | let (tx, rx) = oneshot::channel::<()>(); 91 | let shutdown = Shutdown::new(async { 92 | rx.await.unwrap(); 93 | }); 94 | let guard = shutdown.guard(); 95 | 96 | tokio::select! { 97 | _ = guard.cancelled() => {} 98 | _ = tokio::time::sleep(Duration::from_millis(50)) => {}, 99 | } 100 | 101 | tx.send(()).unwrap(); 102 | 103 | drop(guard); 104 | 105 | shutdown.shutdown().await; 106 | } 107 | 108 | #[tokio::test] 109 | async fn test_shutdown_guard_weak_cancel_safety() { 110 | let (tx, rx) = oneshot::channel::<()>(); 111 | let shutdown = Shutdown::new(async { 112 | rx.await.unwrap(); 113 | }); 114 | let guard = shutdown.guard_weak(); 115 | 116 | tokio::select! { 117 | _ = guard.into_cancelled() => {} 118 | _ = tokio::time::sleep(Duration::from_millis(50)) => {}, 119 | } 120 | 121 | tx.send(()).unwrap(); 122 | 123 | shutdown.shutdown().await; 124 | } 125 | 126 | #[tokio::test] 127 | async fn test_shutdown_cancelled_after_shutdown() { 128 | let (tx, rx) = oneshot::channel::<()>(); 129 | let shutdown = Shutdown::new(async { 130 | rx.await.unwrap(); 131 | }); 132 | let weak_guard = shutdown.guard_weak(); 133 | tx.send(()).unwrap(); 134 | shutdown.shutdown().await; 135 | weak_guard.cancelled().await; 136 | } 137 | 138 | #[tokio::test] 139 | async fn test_shutdown_after_delay() { 140 | let (tx, rx) = oneshot::channel::<()>(); 141 | let shutdown = Shutdown::builder() 142 | .with_delay(Duration::from_micros(500)) 143 | .with_signal(async { 144 | rx.await.unwrap(); 145 | }) 146 | .build(); 147 | tx.send(()).unwrap(); 148 | shutdown.shutdown().await; 149 | } 150 | 151 | #[tokio::test] 152 | async fn test_shutdown_force() { 153 | let (tx, rx) = oneshot::channel::<()>(); 154 | let (overwrite_tx, overwrite_rx) = oneshot::channel::<()>(); 155 | let shutdown = Shutdown::builder() 156 | .with_signal(rx) 157 | .with_overwrite_fn(|| overwrite_rx) 158 | .build(); 159 | let _guard = shutdown.guard(); 160 | tx.send(()).unwrap(); 161 | overwrite_tx.send(()).unwrap(); 162 | shutdown.shutdown().await; 163 | } 164 | 165 | #[tokio::test] 166 | async fn test_shutdown_with_limit_force() { 167 | let (tx, rx) = oneshot::channel::<()>(); 168 | let (overwrite_tx, overwrite_rx) = oneshot::channel::<()>(); 169 | let shutdown = Shutdown::builder() 170 | .with_signal(rx) 171 | .with_overwrite_fn(|| overwrite_rx) 172 | .build(); 173 | let _guard = shutdown.guard(); 174 | tx.send(()).unwrap(); 175 | overwrite_tx.send(()).unwrap(); 176 | assert!(shutdown 177 | .shutdown_with_limit(Duration::from_secs(60)) 178 | .await 179 | .is_err()); 180 | } 181 | 182 | #[tokio::test] 183 | async fn test_shutdown_with_delay_force() { 184 | let (tx, rx) = oneshot::channel::<()>(); 185 | let (overwrite_tx, overwrite_rx) = oneshot::channel::<()>(); 186 | let shutdown = Shutdown::builder() 187 | .with_delay(Duration::from_micros(500)) 188 | .with_signal(rx) 189 | .with_overwrite_fn(|| overwrite_rx) 190 | .build(); 191 | let _guard = shutdown.guard(); 192 | tx.send(()).unwrap(); 193 | overwrite_tx.send(()).unwrap(); 194 | shutdown.shutdown().await; 195 | } 196 | 197 | #[tokio::test] 198 | async fn test_shutdown_with_limit_and_delay_force() { 199 | let (tx, rx) = oneshot::channel::<()>(); 200 | let (overwrite_tx, overwrite_rx) = oneshot::channel::<()>(); 201 | let shutdown = Shutdown::builder() 202 | .with_delay(Duration::from_micros(500)) 203 | .with_signal(rx) 204 | .with_overwrite_fn(|| overwrite_rx) 205 | .build(); 206 | let _guard = shutdown.guard(); 207 | tx.send(()).unwrap(); 208 | overwrite_tx.send(()).unwrap(); 209 | assert!(shutdown 210 | .shutdown_with_limit(Duration::from_secs(60)) 211 | .await 212 | .is_err()); 213 | } 214 | 215 | #[tokio::test] 216 | async fn test_shutdown_after_delay_check() { 217 | let (tx, rx) = oneshot::channel::<()>(); 218 | let shutdown = Shutdown::builder() 219 | .with_delay(Duration::from_secs(5)) 220 | .with_signal(rx) 221 | .build(); 222 | tx.send(()).unwrap(); 223 | let result = tokio::time::timeout(Duration::from_micros(100), shutdown.shutdown()).await; 224 | assert!(result.is_err(), "{result:?}"); 225 | } 226 | 227 | #[tokio::test] 228 | async fn test_shutdown_cancelled_vs_shutdown_signal_triggered() { 229 | let (tx, rx) = oneshot::channel::<()>(); 230 | let shutdown = Shutdown::builder() 231 | .with_delay(Duration::from_secs(5)) 232 | .with_signal(rx) 233 | .build(); 234 | tx.send(()).unwrap(); 235 | 236 | let weak_guard = shutdown.guard_weak(); 237 | 238 | // will fail because delay is still being awaited 239 | let result = tokio::time::timeout(Duration::from_micros(100), weak_guard.cancelled()).await; 240 | assert!(result.is_err(), "{result:?}"); 241 | 242 | // this will succeed however, as it does not await the delay 243 | let result = tokio::time::timeout( 244 | Duration::from_millis(100), 245 | weak_guard.shutdown_signal_triggered(), 246 | ) 247 | .await; 248 | assert!(result.is_ok(), "{result:?}"); 249 | } 250 | 251 | #[tokio::test] 252 | async fn test_shutdown_nested_guards() { 253 | let (tx, rx) = oneshot::channel::<()>(); 254 | let shutdown = Shutdown::new(async { 255 | rx.await.unwrap(); 256 | }); 257 | shutdown.spawn_task_fn(|guard| async move { 258 | guard.spawn_task_fn(|guard| async move { 259 | guard.spawn_task_fn(|guard| async move { 260 | guard.spawn_task(async { 261 | tokio::time::sleep(Duration::from_millis(50)).await; 262 | }); 263 | }); 264 | }); 265 | }); 266 | tx.send(()).unwrap(); 267 | shutdown.shutdown().await; 268 | } 269 | 270 | #[tokio::test] 271 | async fn test_shutdown_sixten_thousand_guards() { 272 | let (tx, rx) = oneshot::channel::<()>(); 273 | let shutdown = Shutdown::new(async { 274 | rx.await.unwrap(); 275 | }); 276 | for _ in 0..16_000 { 277 | shutdown.spawn_task(async { 278 | // sleep random between 1 and 80ms 279 | let duration = Duration::from_millis(rand::random::() % 80 + 1); 280 | tokio::time::sleep(duration).await; 281 | }); 282 | } 283 | tx.send(()).unwrap(); 284 | shutdown.shutdown().await; 285 | } 286 | } 287 | -------------------------------------------------------------------------------- /src/shutdown.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | sync::JoinHandle, 3 | trigger::{trigger, Receiver}, 4 | ShutdownGuard, WeakShutdownGuard, 5 | }; 6 | use std::{ 7 | fmt, 8 | future::Future, 9 | time::{self, Duration}, 10 | }; 11 | 12 | /// [`ShutdownBuilder`] to build a [`Shutdown`] manager. 13 | pub struct ShutdownBuilder { 14 | data: T, 15 | } 16 | 17 | impl Default for ShutdownBuilder> { 18 | fn default() -> Self { 19 | Self::new() 20 | } 21 | } 22 | 23 | impl fmt::Debug for ShutdownBuilder { 24 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 25 | f.debug_struct("ShutdownBuilder") 26 | .field("data", &self.data) 27 | .finish() 28 | } 29 | } 30 | 31 | impl ShutdownBuilder> { 32 | /// Create a new [`ShutdownBuilder`], which by default 33 | /// is ready to build a [`Shutdown`]. 34 | pub fn new() -> Self { 35 | Self { 36 | data: sealed::WithSignal { 37 | signal: sealed::Default, 38 | delay: None, 39 | }, 40 | } 41 | } 42 | 43 | /// Create a [`ShutdownBuilder`] without a trigger signal, 44 | /// meaning it will act like a WaitGroup. 45 | pub fn without_signal(self) -> ShutdownBuilder { 46 | ShutdownBuilder { 47 | data: sealed::WithoutSignal, 48 | } 49 | } 50 | 51 | /// Create a [`ShutdownBuilder`] with a custom [`Future`] signal. 52 | pub fn with_signal( 53 | self, 54 | future: F, 55 | ) -> ShutdownBuilder> { 56 | ShutdownBuilder { 57 | data: sealed::WithSignal { 58 | signal: future, 59 | delay: self.data.delay, 60 | }, 61 | } 62 | } 63 | } 64 | 65 | impl ShutdownBuilder> { 66 | /// Create a [`ShutdownBuilder`] with a function 67 | /// which creates a future that will be awaited on 68 | /// as an alternative to waiting for all jobs to be complete. 69 | pub fn with_overwrite_fn( 70 | self, 71 | f: F, 72 | ) -> ShutdownBuilder> 73 | where 74 | F: FnOnce() -> Fut + Send + 'static, 75 | Fut: Future + Send + 'static, 76 | { 77 | ShutdownBuilder { 78 | data: sealed::WithSignalAndOverwriteFn { 79 | signal: self.data.signal, 80 | overwrite_fn: f, 81 | delay: self.data.delay, 82 | }, 83 | } 84 | } 85 | 86 | /// Attach a delay to this [`ShutdownBuilder`] 87 | /// which will used as a timeout buffer between the shutdown 88 | /// trigger signal and signalling the jobs to be cancelled. 89 | pub fn with_delay(self, delay: Duration) -> Self { 90 | Self { 91 | data: sealed::WithSignal { 92 | signal: self.data.signal, 93 | delay: Some(delay), 94 | }, 95 | } 96 | } 97 | 98 | /// Attach a delay to this [`ShutdownBuilder`] 99 | /// which will used as a timeout buffer between the shutdown 100 | /// trigger signal and signalling the jobs to be cancelled. 101 | pub fn maybe_with_delay(self, delay: Option) -> Self { 102 | Self { 103 | data: sealed::WithSignal { 104 | signal: self.data.signal, 105 | delay, 106 | }, 107 | } 108 | } 109 | 110 | /// Attach a delay to this [`ShutdownBuilder`] 111 | /// which will used as a timeout buffer between the shutdown 112 | /// trigger signal and signalling the jobs to be cancelled. 113 | pub fn set_delay(&mut self, delay: Duration) -> &mut Self { 114 | self.data.delay = Some(delay); 115 | self 116 | } 117 | } 118 | 119 | impl ShutdownBuilder> { 120 | /// Attach a delay to this [`ShutdownBuilder`] 121 | /// which will used as a timeout buffer between the shutdown 122 | /// trigger signal and signalling the jobs to be cancelled. 123 | pub fn with_delay(self, delay: Duration) -> Self { 124 | Self { 125 | data: sealed::WithSignalAndOverwriteFn { 126 | signal: self.data.signal, 127 | overwrite_fn: self.data.overwrite_fn, 128 | delay: Some(delay), 129 | }, 130 | } 131 | } 132 | 133 | /// Attach a delay to this [`ShutdownBuilder`] 134 | /// which will used as a timeout buffer between the shutdown 135 | /// trigger signal and signalling the jobs to be cancelled. 136 | pub fn maybe_with_delay(self, delay: Option) -> Self { 137 | Self { 138 | data: sealed::WithSignalAndOverwriteFn { 139 | signal: self.data.signal, 140 | overwrite_fn: self.data.overwrite_fn, 141 | delay, 142 | }, 143 | } 144 | } 145 | 146 | /// Attach a delay to this [`ShutdownBuilder`] 147 | /// which will used as a timeout buffer between the shutdown 148 | /// trigger signal and signalling the jobs to be cancelled. 149 | pub fn set_delay(&mut self, delay: Duration) -> &mut Self { 150 | self.data.delay = Some(delay); 151 | self 152 | } 153 | } 154 | 155 | impl ShutdownBuilder { 156 | /// Build a [`Shutdown`] that acts like a WaitGroup. 157 | pub fn build(self) -> Shutdown { 158 | let (zero_tx, zero_rx) = trigger(); 159 | 160 | let guard = ShutdownGuard::new(Receiver::closed(), None, zero_tx, Default::default()); 161 | 162 | Shutdown { 163 | guard, 164 | zero_rx, 165 | zero_overwrite_rx: Receiver::pending(), 166 | } 167 | } 168 | } 169 | 170 | impl ShutdownBuilder> { 171 | /// Build a [`Shutdown`] which will allow a shutdown 172 | /// when the shutdown signal has been triggered AND 173 | /// all jobs are complete. 174 | pub fn build(self) -> Shutdown { 175 | let trigger_signal = self.data.signal.into_future(); 176 | 177 | let (delay_tuple, maybe_shutdown_signal_rx) = match self.data.delay { 178 | Some(delay) => { 179 | let (shutdown_signal_tx, shutdown_signal_rx) = trigger(); 180 | (Some((delay, shutdown_signal_tx)), Some(shutdown_signal_rx)) 181 | } 182 | None => (None, None), 183 | }; 184 | 185 | let (signal_tx, signal_rx) = trigger(); 186 | let (zero_tx, zero_rx) = trigger(); 187 | 188 | let guard = ShutdownGuard::new( 189 | signal_rx, 190 | maybe_shutdown_signal_rx, 191 | zero_tx, 192 | Default::default(), 193 | ); 194 | 195 | crate::sync::spawn(async move { 196 | let _ = trigger_signal.await; 197 | if let Some((delay, shutdown_signal_tx)) = delay_tuple { 198 | shutdown_signal_tx.trigger(); 199 | tracing::trace!( 200 | "::trigger signal recieved: delay buffer activated: {:?}", 201 | delay 202 | ); 203 | tokio::time::sleep(delay).await; 204 | } 205 | signal_tx.trigger(); 206 | }); 207 | 208 | Shutdown { 209 | guard, 210 | zero_rx, 211 | zero_overwrite_rx: Receiver::pending(), 212 | } 213 | } 214 | } 215 | 216 | impl ShutdownBuilder> 217 | where 218 | I: sealed::IntoFuture, 219 | F: FnOnce() -> Fut + Send + 'static, 220 | Fut: Future + Send + 'static, 221 | { 222 | /// Build a [`Shutdown`] which will allow a shutdown 223 | /// when the shutdown signal has been triggered AND 224 | /// either all jobs are complete or the overwrite (force) 225 | /// signal has been triggered instead. 226 | pub fn build(self) -> Shutdown { 227 | let trigger_signal = self.data.signal.into_future(); 228 | let overwrite_fn = self.data.overwrite_fn; 229 | 230 | let (delay_tuple, maybe_shutdown_signal_rx) = match self.data.delay { 231 | Some(delay) => { 232 | let (shutdown_signal_tx, shutdown_signal_rx) = trigger(); 233 | (Some((delay, shutdown_signal_tx)), Some(shutdown_signal_rx)) 234 | } 235 | None => (None, None), 236 | }; 237 | 238 | let (signal_tx, signal_rx) = trigger(); 239 | let (zero_tx, zero_rx) = trigger(); 240 | let (zero_overwrite_tx, zero_overwrite_rx) = trigger(); 241 | 242 | let guard = ShutdownGuard::new( 243 | signal_rx, 244 | maybe_shutdown_signal_rx, 245 | zero_tx, 246 | Default::default(), 247 | ); 248 | 249 | crate::sync::spawn(async move { 250 | let _ = trigger_signal.await; 251 | let overwrite_signal = overwrite_fn(); 252 | crate::sync::spawn(async move { 253 | let _ = overwrite_signal.await; 254 | zero_overwrite_tx.trigger(); 255 | }); 256 | if let Some((delay, shutdown_signal_tx)) = delay_tuple { 257 | shutdown_signal_tx.trigger(); 258 | tracing::trace!( 259 | "::trigger signal recieved: delay buffer activated: {:?}", 260 | delay 261 | ); 262 | tokio::time::sleep(delay).await; 263 | } 264 | signal_tx.trigger(); 265 | }); 266 | 267 | Shutdown { 268 | guard, 269 | zero_rx, 270 | zero_overwrite_rx, 271 | } 272 | } 273 | } 274 | 275 | /// The [`Shutdown`] struct is the main entry point to the shutdown system. 276 | /// 277 | /// It is created by calling [`Shutdown::new`], which takes a [`Future`] that 278 | /// will be awaited on when shutdown is requested. Most users will want to 279 | /// create a [`Shutdown`] with [`Shutdown::default`], which uses the default 280 | /// signal handler to trigger shutdown. See [`default_signal`] for more info. 281 | /// 282 | /// > (NOTE: that these defaults are not available when compiling with --cfg loom) 283 | /// 284 | /// See the [README] for more info on how to use this crate. 285 | /// 286 | /// [`Future`]: std::future::Future 287 | /// [README]: https://github.com/plabayo/tokio-graceful/blob/main/README.md 288 | pub struct Shutdown { 289 | guard: ShutdownGuard, 290 | zero_rx: Receiver, 291 | zero_overwrite_rx: Receiver, 292 | } 293 | 294 | impl Shutdown { 295 | /// Create a [`ShutdownBuilder`] allowing you to add a delay, 296 | /// a custom shutdown trigger signal and even an overwrite signal 297 | /// to force a shutdown even if workers are still busy. 298 | pub fn builder() -> ShutdownBuilder> { 299 | ShutdownBuilder::default() 300 | } 301 | 302 | /// Creates a new [`Shutdown`] struct with the given [`Future`]. 303 | /// 304 | /// The [`Future`] will be awaited on when shutdown is requested. 305 | /// 306 | /// [`Future`]: std::future::Future 307 | pub fn new(signal: impl Future + Send + 'static) -> Self { 308 | ShutdownBuilder::default().with_signal(signal).build() 309 | } 310 | 311 | /// Creates a new [`Shutdown`] struct with no signal. 312 | /// 313 | /// This is useful if you want to support a Waitgroup 314 | /// like system where you wish to wait for all open tasks 315 | /// without requiring a signal to be triggered first. 316 | pub fn no_signal() -> Self { 317 | ShutdownBuilder::default().without_signal().build() 318 | } 319 | 320 | /// Returns a [`ShutdownGuard`] which primary use 321 | /// is to prevent the [`Shutdown`] from shutting down. 322 | /// 323 | /// The creation of a [`ShutdownGuard`] is lockfree. 324 | /// 325 | /// [`ShutdownGuard`]: crate::ShutdownGuard 326 | #[inline] 327 | pub fn guard(&self) -> ShutdownGuard { 328 | self.guard.clone() 329 | } 330 | 331 | /// Returns a [`WeakShutdownGuard`] which in contrast to 332 | /// [`ShutdownGuard`] does not prevent the [`Shutdown`] 333 | /// from shutting down. 334 | /// 335 | /// Instead it is used to wait for 336 | /// "shutdown signal" to be triggered or to create 337 | /// a [`ShutdownGuard`] which prevents the [`Shutdown`] 338 | /// once and only once it is needed. 339 | /// 340 | /// The creation of a [`WeakShutdownGuard`] is lockfree. 341 | /// 342 | /// [`ShutdownGuard`]: crate::ShutdownGuard 343 | /// [`WeakShutdownGuard`]: crate::WeakShutdownGuard 344 | /// [`Shutdown`]: crate::Shutdown 345 | #[inline] 346 | pub fn guard_weak(&self) -> WeakShutdownGuard { 347 | self.guard.clone_weak() 348 | } 349 | 350 | /// Returns a Tokio [`crate::sync::JoinHandle`] that can be awaited on 351 | /// to wait for the spawned task to complete. See 352 | /// [`crate::sync::spawn`] for more information. 353 | #[inline] 354 | pub fn spawn_task(&self, task: T) -> JoinHandle 355 | where 356 | T: Future + Send + 'static, 357 | T::Output: Send + 'static, 358 | { 359 | self.guard.spawn_task(task) 360 | } 361 | 362 | /// Returns a Tokio [`crate::sync::JoinHandle`] that can be awaited on 363 | /// to wait for the spawned task (fn) to complete. See 364 | /// [`crate::sync::spawn`] for more information. 365 | #[inline] 366 | pub fn spawn_task_fn(&self, task: F) -> JoinHandle 367 | where 368 | T: Future + Send + 'static, 369 | T::Output: Send + 'static, 370 | F: FnOnce(ShutdownGuard) -> T + Send + 'static, 371 | { 372 | self.guard.spawn_task_fn(task) 373 | } 374 | 375 | /// Returns a future that completes once the [`Shutdown`] has been triggered 376 | /// and all [`ShutdownGuard`]s have been dropped. 377 | /// 378 | /// The resolved [`Duration`] is the time it took for the [`Shutdown`] to 379 | /// to wait for all [`ShutdownGuard`]s to be dropped. 380 | /// 381 | /// You can use [`Shutdown::shutdown_with_limit`] to limit the time the 382 | /// [`Shutdown`] waits for all [`ShutdownGuard`]s to be dropped. 383 | /// 384 | /// # Panics 385 | /// 386 | /// This method can panic if the internal mutex is poisoned. 387 | /// 388 | /// [`ShutdownGuard`]: crate::ShutdownGuard 389 | /// [`Duration`]: std::time::Duration 390 | pub async fn shutdown(mut self) -> time::Duration { 391 | tracing::info!("::shutdown: waiting for signal to trigger (read: to be cancelled)"); 392 | let weak_guard = self.guard.downgrade(); 393 | let start: time::Instant = time::Instant::now(); 394 | tokio::select! { 395 | _ = weak_guard.cancelled() => { 396 | tracing::info!("::shutdown: waiting for all guards to drop"); 397 | } 398 | _ = &mut self.zero_overwrite_rx => { 399 | let elapsed = start.elapsed(); 400 | tracing::warn!("::shutdown: enforced: overwrite delayed cancellation after {}s", elapsed.as_secs_f64()); 401 | return elapsed; 402 | } 403 | }; 404 | 405 | let start: time::Instant = time::Instant::now(); 406 | tokio::select! { 407 | _ = self.zero_rx => { 408 | let elapsed = start.elapsed(); 409 | tracing::info!("::shutdown: ready after {}s", elapsed.as_secs_f64()); 410 | elapsed 411 | } 412 | _ = self.zero_overwrite_rx => { 413 | let elapsed = start.elapsed(); 414 | tracing::warn!("::shutdown: enforced: overwrite signal triggered after {}s", elapsed.as_secs_f64()); 415 | elapsed 416 | } 417 | } 418 | } 419 | 420 | /// Returns a future that completes once the [`Shutdown`] has been triggered 421 | /// and all [`ShutdownGuard`]s have been dropped or the given [`Duration`] 422 | /// has elapsed. 423 | /// 424 | /// The resolved [`Duration`] is the time it took for the [`Shutdown`] to 425 | /// to wait for all [`ShutdownGuard`]s to be dropped. 426 | /// 427 | /// You can use [`Shutdown::shutdown`] to wait for all [`ShutdownGuard`]s 428 | /// to be dropped without a time limit. 429 | /// 430 | /// # Panics 431 | /// 432 | /// This method can panic if the internal mutex is poisoned. 433 | /// 434 | /// [`ShutdownGuard`]: crate::ShutdownGuard 435 | /// [`Duration`]: std::time::Duration 436 | pub async fn shutdown_with_limit( 437 | mut self, 438 | limit: time::Duration, 439 | ) -> Result { 440 | tracing::info!("::shutdown: waiting for signal to trigger (read: to be cancelled)"); 441 | let weak_guard = self.guard.downgrade(); 442 | let start: time::Instant = time::Instant::now(); 443 | tokio::select! { 444 | _ = weak_guard.cancelled() => { 445 | tracing::info!( 446 | "::shutdown: waiting for all guards to drop for a max of {}s", 447 | limit.as_secs_f64() 448 | ); 449 | } 450 | _ = &mut self.zero_overwrite_rx => { 451 | let elapsed = start.elapsed(); 452 | tracing::warn!("::shutdown: enforced: overwrite delayed cancellation after {}s", elapsed.as_secs_f64()); 453 | return Err(TimeoutError(elapsed)); 454 | } 455 | }; 456 | 457 | let start: time::Instant = time::Instant::now(); 458 | tokio::select! { 459 | _ = tokio::time::sleep(limit) => { 460 | tracing::info!("::shutdown: timeout after {}s", limit.as_secs_f64()); 461 | Err(TimeoutError(limit)) 462 | } 463 | _ = self.zero_rx => { 464 | let elapsed = start.elapsed(); 465 | tracing::info!("::shutdown: ready after {}s", elapsed.as_secs_f64()); 466 | Ok(elapsed) 467 | } 468 | _ = self.zero_overwrite_rx => { 469 | let elapsed = start.elapsed(); 470 | tracing::warn!("::shutdown: enforced: overwrite signal triggered after {}s", elapsed.as_secs_f64()); 471 | Err(TimeoutError(elapsed)) 472 | } 473 | } 474 | } 475 | } 476 | 477 | /// Returns a [`Future`] that completes once one of the default signals. 478 | /// 479 | /// Which on Unix is Ctrl-C (sigint) or sigterm, 480 | /// and on Windows is Ctrl-C, Ctrl-Close or Ctrl-Shutdown. 481 | /// 482 | /// Exposed to you so you can easily expand it by for example 483 | /// chaining it with a [`tokio::time::sleep`] to have a delay 484 | /// before shutdown is triggered. 485 | /// 486 | /// [`Future`]: std::future::Future 487 | /// [`tokio::time::sleep`]: https://docs.rs/tokio/*/tokio/time/fn.sleep.html 488 | #[cfg(all(not(loom), any(unix, windows)))] 489 | pub async fn default_signal() { 490 | let ctrl_c = tokio::signal::ctrl_c(); 491 | #[cfg(all(unix, not(windows)))] 492 | { 493 | let signal = async { 494 | let mut os_signal = 495 | tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?; 496 | os_signal.recv().await; 497 | std::io::Result::Ok(()) 498 | }; 499 | tokio::select! { 500 | _ = ctrl_c => {} 501 | _ = signal => {} 502 | } 503 | } 504 | #[cfg(all(not(unix), windows))] 505 | { 506 | let ctrl_close = async { 507 | let mut signal = tokio::signal::windows::ctrl_close()?; 508 | signal.recv().await; 509 | std::io::Result::Ok(()) 510 | }; 511 | let ctrl_shutdown = async { 512 | let mut signal = tokio::signal::windows::ctrl_shutdown()?; 513 | signal.recv().await; 514 | std::io::Result::Ok(()) 515 | }; 516 | tokio::select! { 517 | _ = ctrl_c => {} 518 | _ = ctrl_close => {} 519 | _ = ctrl_shutdown => {} 520 | } 521 | } 522 | } 523 | 524 | #[cfg(all(not(loom), any(unix, windows)))] 525 | impl Default for Shutdown { 526 | fn default() -> Self { 527 | Self::new(default_signal()) 528 | } 529 | } 530 | 531 | #[derive(Debug)] 532 | pub struct TimeoutError(time::Duration); 533 | 534 | impl std::fmt::Display for TimeoutError { 535 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 536 | write!(f, "timeout after {}s", self.0.as_secs_f64()) 537 | } 538 | } 539 | 540 | impl std::error::Error for TimeoutError {} 541 | 542 | mod sealed { 543 | use std::{fmt, future::Future, time::Duration}; 544 | 545 | pub trait IntoFuture: Send + 'static { 546 | fn into_future(self) -> impl Future + Send + 'static; 547 | } 548 | 549 | impl IntoFuture for F 550 | where 551 | F: Future + Send + 'static, 552 | { 553 | fn into_future(self) -> impl Future + Send + 'static { 554 | self 555 | } 556 | } 557 | 558 | #[derive(Debug)] 559 | #[non_exhaustive] 560 | pub struct Default; 561 | 562 | impl IntoFuture for Default { 563 | #[cfg(loom)] 564 | fn into_future(self) -> impl Future + Send + 'static { 565 | std::future::pending::<()>() 566 | } 567 | #[cfg(not(loom))] 568 | fn into_future(self) -> impl Future + Send + 'static { 569 | super::default_signal() 570 | } 571 | } 572 | 573 | #[derive(Debug)] 574 | #[non_exhaustive] 575 | pub struct WithoutSignal; 576 | 577 | pub struct WithSignal { 578 | pub(super) signal: S, 579 | pub(super) delay: Option, 580 | } 581 | 582 | impl fmt::Debug for WithSignal { 583 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 584 | f.debug_struct("WithSignal") 585 | .field("signal", &self.signal) 586 | .field("delay", &self.delay) 587 | .finish() 588 | } 589 | } 590 | 591 | pub struct WithSignalAndOverwriteFn { 592 | pub(super) signal: S, 593 | pub(super) overwrite_fn: F, 594 | pub(super) delay: Option, 595 | } 596 | 597 | impl fmt::Debug for WithSignalAndOverwriteFn { 598 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 599 | f.debug_struct("WithSignalAndOverwriteFn") 600 | .field("signal", &self.signal) 601 | .field("overwrite_fn", &self.overwrite_fn) 602 | .field("delay", &self.delay) 603 | .finish() 604 | } 605 | } 606 | } 607 | -------------------------------------------------------------------------------- /src/sync/default.rs: -------------------------------------------------------------------------------- 1 | pub use std::sync::{ 2 | atomic::{AtomicBool, AtomicUsize, Ordering}, 3 | Arc, Mutex, 4 | }; 5 | -------------------------------------------------------------------------------- /src/sync/loom.rs: -------------------------------------------------------------------------------- 1 | pub use loom::sync::{ 2 | atomic::{AtomicBool, AtomicUsize, Ordering}, 3 | Arc, Mutex, 4 | }; 5 | -------------------------------------------------------------------------------- /src/sync/mod.rs: -------------------------------------------------------------------------------- 1 | #[cfg(loom)] 2 | mod loom; 3 | #[cfg(loom)] 4 | pub use self::loom::*; 5 | 6 | #[cfg(not(loom))] 7 | mod default; 8 | #[cfg(not(loom))] 9 | pub use default::*; 10 | 11 | pub use tokio::task::{spawn, JoinHandle}; 12 | -------------------------------------------------------------------------------- /src/trigger.rs: -------------------------------------------------------------------------------- 1 | //! A trigger is a way to wake up a task from another task. 2 | //! 3 | //! This is useful for implementing graceful shutdowns, among other things. 4 | //! The way it works is a Sender and Receiver both have access to shared data, 5 | //! being a WakerList and a boolean indicating whether the trigger has been triggered. 6 | //! 7 | //! The Sender can trigger the Receiver by setting the boolean to true and waking up all the wakers. 8 | //! The Receiver can add itself to the waker list (when being polled) and check whether the boolean 9 | //! has been set to true. 10 | //! 11 | //! Using Arc, Mutex and Atomic* this is all done in a safe manner. 12 | //! The trick is further to use Slab to store the wakers, as it allows 13 | //! us to very efficiently keep track of the wakers and remove them when they are no longer needed. 14 | //! 15 | //! To make this work, in a cancel safe manner, we need to make sure 16 | //! we remove the waker from the waker list when the Receiver is dropped. 17 | 18 | use std::{ 19 | future::Future, 20 | pin::Pin, 21 | task::{Context, Poll, Waker}, 22 | }; 23 | 24 | use pin_project_lite::pin_project; 25 | use slab::Slab; 26 | 27 | use crate::sync::{Arc, AtomicBool, Mutex, Ordering}; 28 | 29 | type WakerList = Arc>>>; 30 | type TriggerState = Arc; 31 | 32 | /// A subscriber is the active state of a Receiver, 33 | /// and is there only when the Receiver did not yet detect a trigger. 34 | #[derive(Debug, Clone)] 35 | struct Subscriber { 36 | wakers: WakerList, 37 | state: TriggerState, 38 | } 39 | 40 | /// The state of a [`Subscriber] returned by `Subscriber::state`, 41 | /// which is used to determine whether the Subscriber has been triggered 42 | /// or has instead stored the callee's `Waker` for being able to wake it up 43 | /// when the trigger is triggered. 44 | #[derive(Debug)] 45 | enum SubscriberState { 46 | Waiting(usize), 47 | Triggered, 48 | } 49 | 50 | impl Subscriber { 51 | /// Returns the state of the Subscriber, 52 | /// which is used as a main driver in the Receiver's `Future::poll` implementation. 53 | /// 54 | /// If the Subscriber has been triggered, it returns `SubscriberState::Triggered`. 55 | /// If the Subscriber has not yet been triggered, it returns `SubscriberState::Waiting` 56 | /// with the key of the waker in the waker list. 57 | /// 58 | /// If the key is `Some`, it means the waker is already in the waker list, 59 | /// and we can update the waker with the new waker. Otherwise we insert the waker 60 | /// into the waker list as a new waker. Either way, we return the key of the waker. 61 | pub fn state(&self, cx: &mut Context, key: Option) -> SubscriberState { 62 | if self.state.load(Ordering::SeqCst) { 63 | return SubscriberState::Triggered; 64 | } 65 | 66 | let mut wakers = self.wakers.lock().unwrap(); 67 | 68 | // check again after locking the wakers 69 | // if we didn't miss this for some reason... 70 | // (without this, we could miss a trigger, and never wake up...) 71 | // (this was a bug detected by loom) 72 | if self.state.load(Ordering::SeqCst) { 73 | return SubscriberState::Triggered; 74 | } 75 | 76 | let waker = Some(cx.waker().clone()); 77 | 78 | SubscriberState::Waiting(if let Some(key) = key { 79 | tracing::trace!("trigger::Subscriber: updating waker for key: {}", key); 80 | *wakers.get_mut(key).unwrap() = waker; 81 | key 82 | } else { 83 | let key = wakers.insert(waker); 84 | tracing::trace!("trigger::Subscriber: insert waker for key: {}", key); 85 | key 86 | }) 87 | } 88 | } 89 | 90 | /// The state of a [`Receiver`], which is either open or closed. 91 | /// The closed state is mostly for simplification and optimization reasons. 92 | /// 93 | /// When the Receiver is open, it contains a [`Subscriber`], 94 | /// which is used to determine whether the Receiver has been triggered. 95 | #[derive(Debug)] 96 | enum ReceiverState { 97 | Open { sub: Subscriber, key: Option }, 98 | Closed, 99 | Pending, 100 | } 101 | 102 | impl Clone for ReceiverState { 103 | /// Clone either nothing or the [`Subscriber`]. 104 | /// Very important however to not clone its key as 105 | /// that is linked to a polled future of the original Receiver, 106 | /// and not the cloned one. 107 | fn clone(&self) -> Self { 108 | match self { 109 | ReceiverState::Open { sub, .. } => ReceiverState::Open { 110 | sub: sub.clone(), 111 | key: None, 112 | }, 113 | ReceiverState::Closed => ReceiverState::Closed, 114 | ReceiverState::Pending => ReceiverState::Pending, 115 | } 116 | } 117 | } 118 | 119 | impl Drop for ReceiverState { 120 | /// When the Receiver is dropped, we need to remove the waker from the waker list. 121 | /// As to ensure the Receiver is cancel safe. 122 | fn drop(&mut self) { 123 | if let ReceiverState::Open { sub, key } = self { 124 | if let Some(key) = key.take() { 125 | let mut wakers = sub.wakers.lock().unwrap(); 126 | tracing::trace!( 127 | "trigger::ReceiverState::Drop: remove waker for key: {}", 128 | key 129 | ); 130 | wakers.remove(key); 131 | } 132 | } 133 | } 134 | } 135 | 136 | pin_project! { 137 | #[derive(Debug, Clone)] 138 | pub struct Receiver { 139 | state: ReceiverState, 140 | } 141 | } 142 | 143 | impl Receiver { 144 | fn new(wakers: WakerList, state: TriggerState) -> Self { 145 | Self { 146 | state: ReceiverState::Open { 147 | sub: Subscriber { wakers, state }, 148 | key: None, 149 | }, 150 | } 151 | } 152 | 153 | /// Create a always-closed [`Receiver`]. 154 | pub(crate) fn closed() -> Self { 155 | Self { 156 | state: ReceiverState::Closed, 157 | } 158 | } 159 | 160 | /// Create a always-pending [`Receiver`]. 161 | pub(crate) fn pending() -> Self { 162 | Self { 163 | state: ReceiverState::Pending, 164 | } 165 | } 166 | } 167 | 168 | impl Future for Receiver { 169 | type Output = (); 170 | 171 | /// Polls the Receiver, which is either open or closed. 172 | /// 173 | /// When the Receiver is open, it uses the [`Subscriber`] to determine 174 | /// whether the Receiver has been triggered. 175 | fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll { 176 | let this = self.project(); 177 | match this.state { 178 | ReceiverState::Open { sub, key } => { 179 | let state = sub.state(cx, *key); 180 | match state { 181 | SubscriberState::Waiting(new_key) => { 182 | *key = Some(new_key); 183 | std::task::Poll::Pending 184 | } 185 | SubscriberState::Triggered => { 186 | *this.state = ReceiverState::Closed; 187 | std::task::Poll::Ready(()) 188 | } 189 | } 190 | } 191 | ReceiverState::Closed => std::task::Poll::Ready(()), 192 | ReceiverState::Pending => std::task::Poll::Pending, 193 | } 194 | } 195 | } 196 | 197 | #[derive(Debug, Clone)] 198 | pub struct Sender { 199 | state: TriggerState, 200 | wakers: WakerList, 201 | } 202 | 203 | impl Sender { 204 | fn new(wakers: WakerList, state: TriggerState) -> Self { 205 | Self { wakers, state } 206 | } 207 | 208 | /// Triggers the Receiver, with a short circuit if the trigger has already been triggered. 209 | pub fn trigger(&self) { 210 | if self.state.swap(true, Ordering::SeqCst) { 211 | return; 212 | } 213 | 214 | let mut wakers = self.wakers.lock().unwrap(); 215 | for (key, waker) in wakers.iter_mut() { 216 | match waker.take() { 217 | Some(waker) => { 218 | tracing::trace!("trigger::Sender: wake up waker with key: {}", key); 219 | waker.wake(); 220 | } 221 | None => { 222 | tracing::trace!( 223 | "trigger::Sender: nop: waker already triggered with key: {}", 224 | key 225 | ); 226 | } 227 | } 228 | } 229 | } 230 | } 231 | 232 | pub fn trigger() -> (Sender, Receiver) { 233 | let wakers = Arc::new(Mutex::new(Slab::new())); 234 | let state = Arc::new(AtomicBool::new(false)); 235 | 236 | let sender = Sender::new(wakers.clone(), state.clone()); 237 | let receiver = Receiver::new(wakers, state); 238 | 239 | (sender, receiver) 240 | } 241 | 242 | #[cfg(all(test, not(loom)))] 243 | mod tests { 244 | use super::*; 245 | 246 | #[tokio::test] 247 | async fn test_sender_trigger() { 248 | let (sender, receiver) = trigger(); 249 | 250 | let th = tokio::spawn(async move { 251 | sender.trigger(); 252 | }); 253 | 254 | receiver.await; 255 | 256 | th.await.unwrap(); 257 | } 258 | 259 | #[tokio::test] 260 | async fn test_sender_never_trigger() { 261 | let (_, receiver) = trigger(); 262 | tokio::time::timeout(std::time::Duration::from_millis(100), receiver) 263 | .await 264 | .unwrap_err(); 265 | } 266 | } 267 | 268 | #[cfg(all(test, loom))] 269 | mod loom_tests { 270 | use super::*; 271 | 272 | use loom::{future::block_on, thread}; 273 | 274 | #[test] 275 | fn test_loom_sender_trigger() { 276 | loom::model(|| { 277 | let (sender, receiver) = trigger(); 278 | 279 | let th = thread::spawn(move || { 280 | sender.trigger(); 281 | }); 282 | 283 | block_on(async move { 284 | receiver.await; 285 | }); 286 | 287 | th.join().unwrap(); 288 | }); 289 | } 290 | } 291 | --------------------------------------------------------------------------------