use std::sync::Arc;
use tokio_util::sync::CancellationToken;
#[derive(Clone)]
pub struct AbortHandle {
token: CancellationToken,
}
impl AbortHandle {
pub fn new() -> Self {
Self {
token: CancellationToken::new(),
}
}
pub fn abort(&self) {
self.token.cancel();
}
pub fn is_aborted(&self) -> bool {
self.token.is_cancelled()
}
pub fn token(&self) -> CancellationToken {
self.token.clone()
}
pub fn child(&self) -> CancellationToken {
self.token.child_token()
}
}
impl Default for AbortHandle {
fn default() -> Self {
Self::new()
}
}
pub fn from_token(token: CancellationToken) -> AbortHandle {
AbortHandle { token }
}
pub type SharedAbortHandle = Arc<AbortHandle>;
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn abort_propagates_to_children() {
let handle = AbortHandle::new();
let child = handle.child();
assert!(!child.is_cancelled());
handle.abort();
assert!(handle.is_aborted());
assert!(child.is_cancelled());
}
#[tokio::test]
async fn child_cancel_does_not_cancel_parent() {
let handle = AbortHandle::new();
let child = handle.child();
child.cancel();
assert!(child.is_cancelled());
assert!(!handle.is_aborted());
}
}