-
Notifications
You must be signed in to change notification settings - Fork 18
feat: cancelable crate #465
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
afoxman
wants to merge
15
commits into
main
Choose a base branch
from
cancelable-crate
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
eac390f
beginnings of a new crate. needs to be polished and prepped for a v1 …
afoxman 001203c
Merge remote-tracking branch 'origin/main' into cancelable-crate
afoxman 48aee1d
v1 draft
afoxman d443a1b
fixes
afoxman 5167a0a
PR feedback and fixes
afoxman 836b31b
Merge remote-tracking branch 'origin/main' into cancelable-crate
afoxman 5f5f524
Copilot feedback, fix lockfile
afoxman ee8b26a
pr feedback, test coverage
afoxman f8662ca
Merge remote-tracking branch 'origin/main' into cancelable-crate
afoxman 932d4f5
fix comment
afoxman c14166f
fix test
afoxman a5a5230
spelling
afoxman 95ae43f
Merge branch 'main' into cancelable-crate
afoxman cde0385
Merge remote-tracking branch 'origin/main' into cancelable-crate
afoxman ff067d4
lockfile
afoxman File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| # Changelog |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| # Copyright (c) Microsoft Corporation. | ||
| # Licensed under the MIT License. | ||
|
|
||
| [package] | ||
| name = "cancelable" | ||
| description = "Cooperative cancellation via tokens" | ||
| version = "0.1.0" | ||
| readme = "README.md" | ||
| keywords = ["oxidizer", "async", "futures"] | ||
| categories = ["asynchronous", "concurrency"] | ||
|
|
||
| edition.workspace = true | ||
| rust-version.workspace = true | ||
| authors.workspace = true | ||
| license.workspace = true | ||
| homepage.workspace = true | ||
| repository = "https://github.com/microsoft/oxidizer/tree/main/crates/cancelable" | ||
|
|
||
| [package.metadata.cargo_check_external_types] | ||
| allowed_external_types = [ | ||
| "ohno::enrichable::Enrichable", | ||
| "ohno::error_ext::ErrorExt", | ||
| ] | ||
|
|
||
| [package.metadata.docs.rs] | ||
| all-features = true | ||
|
|
||
| [dependencies] | ||
| ohno = { workspace = true } | ||
| pin-project = { workspace = true } | ||
|
|
||
| [dev-dependencies] | ||
| mutants = { workspace = true } | ||
| ohno = { workspace = true, features = ["app-err"] } | ||
| tick = { workspace = true, features = ["tokio"] } | ||
| tokio = { workspace = true, features = ["macros", "rt-multi-thread"] } | ||
|
|
||
| [lints] | ||
| workspace = true |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| <div align="center"> | ||
| <img src="./logo.png" alt="Cancelable Logo" width="96"> | ||
|
|
||
| # Cancelable | ||
|
|
||
| [](https://crates.io/crates/cancelable) | ||
| [](https://docs.rs/cancelable) | ||
| [](https://crates.io/crates/cancelable) | ||
| [](https://github.com/microsoft/oxidizer/actions/workflows/main.yml) | ||
| [](https://codecov.io/gh/microsoft/oxidizer) | ||
| [](../../LICENSE) | ||
| <a href="../.."><img src="../../logo.svg" alt="This crate was developed as part of the Oxidizer project" width="20"></a> | ||
|
|
||
| </div> | ||
|
|
||
| Cooperative cancellation via tokens. | ||
|
|
||
| This module provides [`CancellationTokenSource`][__link0] and [`CancellationToken`][__link1], | ||
| modeled after the equivalent C# types. A source controls cancellation and | ||
| hands out lightweight, cloneable tokens for observers to check. | ||
|
|
||
| ## Linked Sources | ||
|
|
||
| A linked source cancels when *any* of its parent tokens are canceled, | ||
| enabling composition of multiple cancellation signals: | ||
|
|
||
| ```rust | ||
| use cancelable::CancellationTokenSource; | ||
|
|
||
| let first = CancellationTokenSource::new(); | ||
| let second = CancellationTokenSource::new(); | ||
|
|
||
| let linked = CancellationTokenSource::linked(&[first.token(), second.token()]); | ||
| let token = linked.token(); | ||
|
|
||
| assert!(!token.is_cancelled()); | ||
| second.cancel(); | ||
| assert!(token.is_cancelled()); | ||
| ``` | ||
|
|
||
| ## Subscribers | ||
|
|
||
| Register callbacks that fire exactly once when cancellation occurs: | ||
|
|
||
| ```rust | ||
| use cancelable::CancellationTokenSource; | ||
|
|
||
| let source = CancellationTokenSource::new(); | ||
| source.subscribe(|| println!("Operation canceled")); | ||
| source.cancel(); | ||
| ``` | ||
|
|
||
| ## Futures | ||
|
|
||
| The [`CancelableExt`][__link2] trait adds a [`cancelable`][__link3] method | ||
| to any [`Future`][__link4], pairing it with a [`CancellationToken`][__link5] so that each | ||
| poll checks for cancellation before and after driving the inner future. | ||
|
|
||
| ```rust | ||
| use cancelable::{CancelableExt, CancellationTokenSource}; | ||
|
|
||
| let source = CancellationTokenSource::new(); | ||
| let token = source.token(); | ||
|
|
||
| let result = async { 42 }.cancelable(token).await?; | ||
| assert_eq!(result, 42); | ||
| ``` | ||
|
|
||
|
|
||
| <hr/> | ||
| <sub> | ||
| This crate was developed as part of <a href="../..">The Oxidizer Project</a>. Browse this crate's <a href="https://github.com/microsoft/oxidizer/tree/main/crates/cancelable">source code</a>. | ||
| </sub> | ||
|
|
||
| [__cargo_doc2readme_dependencies_info]: ggGmYW0CYXZlMC43LjJhdIQbLiTyV0MU86EbZU15e0PmecoboQ9jo59bnAEbyDXw04U13GlhYvRhcoQbE3Iea_zSpkIbvcbCI0vEEEEb7KqsBtUtyHsbFhKo1iYbGRphZIGCamNhbmNlbGFibGVlMC4xLjA | ||
| [__link0]: https://docs.rs/cancelable/0.1.0/cancelable/?search=CancellationTokenSource | ||
| [__link1]: https://docs.rs/cancelable/0.1.0/cancelable/?search=CancellationToken | ||
| [__link2]: https://docs.rs/cancelable/0.1.0/cancelable/?search=future::CancelableExt | ||
| [__link3]: https://docs.rs/cancelable/0.1.0/cancelable/?search=future::CancelableExt::cancelable | ||
| [__link4]: https://doc.rust-lang.org/stable/std/future/trait.Future.html | ||
| [__link5]: https://docs.rs/cancelable/0.1.0/cancelable/?search=CancellationToken |
Git LFS file not shown
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,204 @@ | ||
| // Copyright (c) Microsoft Corporation. | ||
| // Licensed under the MIT License. | ||
|
|
||
|
afoxman marked this conversation as resolved.
|
||
| //! Future extension for cooperative cancellation | ||
| //! | ||
| //! The [`CancelableExt`] trait adds a | ||
| //! [`cancelable`](CancelableExt::cancelable) method | ||
| //! to any [`Future`], pairing it with a [`CancellationToken`] so that each | ||
| //! poll checks for cancellation before and after driving the inner future. | ||
| //! | ||
| //! ``` | ||
| //! # async fn example() -> Result<(), ohno::AppError> { | ||
|
afoxman marked this conversation as resolved.
afoxman marked this conversation as resolved.
|
||
| //! use cancelable::{CancelableExt, CancellationTokenSource}; | ||
| //! | ||
| //! let source = CancellationTokenSource::new(); | ||
| //! let token = source.token(); | ||
| //! | ||
| //! let result = async { 42 }.cancelable(token).await?; | ||
| //! assert_eq!(result, 42); | ||
| //! # Ok(()) | ||
| //! # } | ||
| //! ``` | ||
|
afoxman marked this conversation as resolved.
|
||
|
|
||
| use std::pin::Pin; | ||
| use std::task::{Context, Poll}; | ||
|
afoxman marked this conversation as resolved.
|
||
|
|
||
|
afoxman marked this conversation as resolved.
afoxman marked this conversation as resolved.
afoxman marked this conversation as resolved.
|
||
| use pin_project::pin_project; | ||
|
|
||
| use crate::CancellationToken; | ||
|
|
||
| /// Error returned when a future is canceled | ||
| #[ohno::error] | ||
| #[display("operation was canceled")] | ||
| pub struct Canceled {} | ||
|
afoxman marked this conversation as resolved.
|
||
|
|
||
| /// Extension trait that adds cancellation support to any [`Future`]. | ||
| pub trait CancelableExt: Future + Sized { | ||
| /// Wraps this future so that each poll checks the given [`CancellationToken`]: | ||
| /// | ||
| /// - If the token is canceled (before *or* after polling the inner | ||
| /// future), the combined future resolves to <code>Err([Canceled])</code>. | ||
| /// - Otherwise the inner future's output is forwarded as `Ok(output)`. | ||
|
afoxman marked this conversation as resolved.
|
||
| /// | ||
| /// # Note on wake semantics | ||
| /// | ||
| /// Cancellation is checked cooperatively: the extension inspects the token | ||
| /// each time the inner future is polled. If the inner future is pending | ||
| /// and nothing else wakes the task, cancellation will not be noticed until | ||
| /// the next poll. This mirrors the cooperative model of the `C#` method | ||
| /// `CancellationToken.ThrowIfCancellationRequested()`. | ||
| /// | ||
| /// # Examples | ||
| /// | ||
| /// Successful completion: | ||
| /// | ||
| /// ``` | ||
| /// # async fn example() { | ||
| /// use cancelable::{CancelableExt, CancellationTokenSource}; | ||
| /// | ||
| /// let source = CancellationTokenSource::new(); | ||
| /// let result = async { "hello" }.cancelable(source.token()).await; | ||
| /// assert_eq!(result.unwrap(), "hello"); | ||
| /// # } | ||
| /// ``` | ||
| /// | ||
| /// Cancelled before first poll: | ||
| /// | ||
| /// ``` | ||
| /// # async fn example() { | ||
| /// use cancelable::{CancelableExt, CancellationTokenSource}; | ||
| /// | ||
| /// let source = CancellationTokenSource::new(); | ||
| /// source.cancel(); | ||
| /// | ||
| /// let result = async { unreachable!() }.cancelable(source.token()).await; | ||
| /// assert!(result.unwrap_err().to_string().contains("canceled")); | ||
| /// # } | ||
| /// ``` | ||
| fn cancelable(self, token: CancellationToken) -> Cancelable<Self>; | ||
| } | ||
|
|
||
| impl<F: Future> CancelableExt for F { | ||
| fn cancelable(self, token: CancellationToken) -> Cancelable<Self> { | ||
| Cancelable { inner: self, token } | ||
| } | ||
| } | ||
|
|
||
| /// Future returned by | ||
| /// [`cancelable`](CancelableExt::cancelable). | ||
| /// | ||
| /// See the trait method documentation for semantics. | ||
| #[derive(Debug)] | ||
| #[pin_project] | ||
| #[must_use = "futures do nothing unless you `.await` or poll them"] | ||
| pub struct Cancelable<F> { | ||
| #[pin] | ||
| inner: F, | ||
| token: CancellationToken, | ||
| } | ||
|
|
||
| impl<F: Future> Future for Cancelable<F> { | ||
| type Output = Result<F::Output, Canceled>; | ||
|
|
||
| fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { | ||
| let this = self.project(); | ||
|
|
||
| // Check cancellation before running the inner future so we can | ||
| // short-circuit without performing unnecessary work. | ||
| if this.token.is_cancelled() { | ||
| return Poll::Ready(Err(Canceled::new())); | ||
| } | ||
|
|
||
| match this.inner.poll(cx) { | ||
|
afoxman marked this conversation as resolved.
|
||
| Poll::Ready(output) => Poll::Ready(Ok(output)), | ||
|
afoxman marked this conversation as resolved.
|
||
| Poll::Pending => { | ||
| // Check for cancellation again, now that we've spent time running the inner future. | ||
| if this.token.is_cancelled() { | ||
| Poll::Ready(Err(Canceled::new())) | ||
| } else { | ||
| Poll::Pending | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use std::time::Duration; | ||
|
|
||
| use tick::{Clock, FutureExt}; | ||
|
|
||
| use super::*; | ||
| use crate::CancellationTokenSource; | ||
|
|
||
| #[cfg_attr(miri, ignore)] | ||
| #[tokio::test] | ||
| async fn future_returns_ok() { | ||
| let clock = Clock::new_tokio(); | ||
| let source = CancellationTokenSource::new(); | ||
| clock | ||
| .delay(Duration::from_millis(100)) | ||
| .cancelable(source.token()) | ||
| .await | ||
| .expect("should succeed without being canceled"); | ||
| } | ||
|
|
||
| #[cfg_attr(miri, ignore)] | ||
| #[tokio::test] | ||
| async fn completed_future_returns_ok() { | ||
| let source = CancellationTokenSource::new(); | ||
| let result = async { 42 }.cancelable(source.token()).await; | ||
| assert_eq!(result.unwrap(), 42); | ||
| } | ||
|
|
||
| #[cfg_attr(miri, ignore)] | ||
| #[tokio::test] | ||
| async fn cancelled_future_returns_err() { | ||
| let source = CancellationTokenSource::new(); | ||
| source.cancel(); | ||
|
|
||
| let result = async { unreachable!("should not poll inner future") } | ||
| .cancelable(source.token()) | ||
| .await; | ||
| assert!(result.unwrap_err().to_string().contains("canceled")); | ||
| } | ||
|
|
||
| #[cfg_attr(miri, ignore)] | ||
| #[tokio::test] | ||
| async fn cancellation_triggered_by_inner_future_leads_to_cancellation_error() { | ||
| struct CancelOnPoll(CancellationTokenSource); | ||
| impl Future for CancelOnPoll { | ||
| type Output = (); | ||
| fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<()> { | ||
| self.0.cancel(); | ||
| Poll::Pending | ||
| } | ||
| } | ||
|
|
||
| let clock = Clock::new_tokio(); | ||
| let source = CancellationTokenSource::new(); | ||
| let token = source.token(); | ||
| let message = CancelOnPoll(source) | ||
| .timeout(&clock, std::time::Duration::from_secs(5)) | ||
| .cancelable(token) | ||
| .await | ||
| .expect_err("should fail") | ||
| .to_string(); | ||
| assert!(message.contains("canceled")); | ||
| } | ||
|
|
||
| #[cfg_attr(miri, ignore)] | ||
| #[tokio::test] | ||
| async fn already_cancelled_token() { | ||
| let clock = Clock::new_tokio(); | ||
| let message = async { unreachable!() } | ||
| .timeout(&clock, std::time::Duration::from_secs(5)) | ||
| .cancelable(CancellationToken::cancelled()) | ||
| .await | ||
| .expect_err("should fail") | ||
| .to_string(); | ||
| assert!(message.contains("canceled")); | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.