Skip to content
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

feat(tokio-util): Add CancellationTokenWithReason #6453

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

conradludgate
Copy link
Contributor

Motivation

#5249

I wanted a way to propagate a reason to the tasks I am cancelling, eg whether it was via a timeout, or via a termination. As the issue states, Go's context.Context has a WithCancelCause feature that is similar.

For now I am making this as a third party crate, but I felt it was easy enough to suggest upstream. Feel free to bikeshed or reject.

Solution

  1. Make cancellation_token/tree_node.rs generic over the cancel reason. Replace is_cancelled: bool with cancelled: Option<T>.
  2. Copy cancellation_token.rs to cancellation_token_with_reason.rs and make the necessary changes to support the reason.

@mox692 mox692 added A-tokio-util Area: The tokio-util crate M-sync Module: tokio/sync labels Apr 2, 2024
@conradludgate
Copy link
Contributor Author

conradludgate commented Apr 2, 2024

I'll start the bikeshedding:

  1. A feature I would like that I couldn't figure out how to implement is having child tokens have more complex reasons. Eg define fn child_token<U: From<T>>. I think it would require some dynamic dispatch to set the cancelled field.

  2. Lots of functions assume CancellationToken as a parameter. It would be nice to decompose a CancellationTokenWithReason into a CancellationToken.

  3. If the cancellation reason is actionable, eg start graceful shutdown vs shutdown immediately, it might be necessary to send multiple cancellation signals.

@Darksonn
Copy link
Contributor

Darksonn commented Apr 3, 2024

Interesting ... I don't love the current API, but I do some sense to it.

If the cancellation reason is actionable, eg start graceful shutdown vs shutdown immediately, it might be necessary to send multiple cancellation signals.

At that point, it sounds like it is out of scope for the token. You can implement it with multiple tokens or a watch channel.

@conradludgate
Copy link
Contributor Author

At that point, it sounds like it is out of scope for the token. You can implement it with multiple tokens or a watch channel.

Yeah, I agree, it's something that needs to be carefully documented, which I haven't properly done for this feature yet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-tokio-util Area: The tokio-util crate M-sync Module: tokio/sync
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants