Dealing with cancel safety in async Rust
17 hours ago
- #async-cancellation
- #rust-async
- #cancel-safety
- Cancellation in async Rust occurs when futures are dropped, stopping execution abruptly, which can cause unpredictable behavior.
- Cancellation only happens at await points, not while a future's poll method is running, due to cooperative multitasking.
- Cancel safety means a future can be dropped without harming the system; cancel correctness requires the whole system to handle cancellations properly.
- Common cancellation sources include `select!` macros, timeouts, try-joins, task aborts, and runtime shutdowns.
- Writing cancel-safe async APIs involves techniques like splitting complex operations, resuming from partial progress, using explicit cancellation channels, avoiding Tokio mutexes, spawning background tasks, and using synchronous channels.
- Marking cancel-unsafe APIs involves naming conventions and documentation to warn users about potential issues.
- Consuming async code safely requires paying attention to API signals, resuming futures in `select!` loops, using `then_try` adapters, leveraging background tasks, and avoiding task aborts.
- Future directions include advocating for clearer cancel safety documentation in upstream libraries and exploring systematic solutions like async drop or unforgettable types.