use std::future::Future;
use std::sync::Arc;
use std::sync::atomic::{AtomicU8, Ordering};
use tokio::sync::Mutex;
use tokio::task::JoinHandle;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TaskStop {
Cancelled,
Returned,
Panicked,
AlreadyStopped,
}
const RUNNING: u8 = 0;
const REQUESTED: u8 = 1;
const OBSERVED: u8 = 2;
#[derive(Debug)]
pub struct StopSignal {
state: Arc<AtomicU8>,
}
impl StopSignal {
fn new() -> Self {
Self {
state: Arc::new(AtomicU8::new(RUNNING)),
}
}
fn share(&self) -> Self {
Self {
state: Arc::clone(&self.state),
}
}
#[must_use]
pub fn is_requested(&self) -> bool {
match self
.state
.compare_exchange(REQUESTED, OBSERVED, Ordering::AcqRel, Ordering::Acquire)
{
Ok(_) => true,
Err(now) => now == OBSERVED,
}
}
fn request(&self) {
let _ =
self.state
.compare_exchange(RUNNING, REQUESTED, Ordering::AcqRel, Ordering::Acquire);
}
fn was_observed(&self) -> bool {
self.state.load(Ordering::Acquire) == OBSERVED
}
}
pub struct OwnedTask {
slot: Mutex<Option<JoinHandle<()>>>,
signal: Option<StopSignal>,
}
impl OwnedTask {
#[must_use = "dropping an OwnedTask aborts its task at once"]
pub fn spawn<F>(future: F) -> Self
where
F: Future<Output = ()> + Send + 'static,
{
Self {
slot: Mutex::new(Some(tokio::spawn(future))),
signal: None,
}
}
#[must_use = "dropping an OwnedTask asks its closure to stop at once"]
pub fn spawn_blocking<F>(work: F) -> Self
where
F: FnOnce(StopSignal) + Send + 'static,
{
let signal = StopSignal::new();
let for_work = signal.share();
Self {
slot: Mutex::new(Some(tokio::task::spawn_blocking(move || work(for_work)))),
signal: Some(signal),
}
}
pub async fn stop(&self) -> TaskStop {
let mut slot = self.slot.lock().await;
let Some(handle) = slot.as_mut() else {
return TaskStop::AlreadyStopped;
};
if let Some(signal) = &self.signal {
signal.request();
}
handle.abort();
let joined = handle.await;
*slot = None;
match joined {
Ok(()) if self.signal.as_ref().is_some_and(StopSignal::was_observed) => {
TaskStop::Cancelled
}
Ok(()) => TaskStop::Returned,
Err(e) if e.is_cancelled() => TaskStop::Cancelled,
Err(_) => TaskStop::Panicked,
}
}
}
impl Drop for OwnedTask {
fn drop(&mut self) {
if let Some(signal) = &self.signal {
signal.request();
}
if let Some(handle) = self.slot.get_mut() {
handle.abort();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
const STOP_BOUND: Duration = Duration::from_secs(5);
const LEAK_GUARD: Duration = Duration::from_secs(10);
fn park_until_stopped(stop: &StopSignal) {
let parked = std::time::Instant::now();
while !stop.is_requested() && parked.elapsed() < LEAK_GUARD {
std::thread::sleep(Duration::from_millis(1));
}
}
fn parked_holding(held: &Arc<()>) -> OwnedTask {
let in_task = Arc::clone(held);
OwnedTask::spawn(async move {
std::future::pending::<()>().await;
drop(in_task);
})
}
fn blocking_holding(held: &Arc<()>) -> OwnedTask {
let in_task = Arc::clone(held);
let (started_tx, started_rx) = std::sync::mpsc::channel::<()>();
let task = OwnedTask::spawn_blocking(move |stop| {
let _ = started_tx.send(());
park_until_stopped(&stop);
drop(in_task);
});
assert!(
started_rx.recv_timeout(STOP_BOUND).is_ok(),
"precondition: the closure started"
);
task
}
async fn bounded_stop(task: &OwnedTask) -> TaskStop {
tokio::time::timeout(STOP_BOUND, task.stop())
.await
.unwrap_or_else(|_| panic!("stop did not return within {STOP_BOUND:?}"))
}
async fn stop_then_count(task: &OwnedTask, held: &Arc<()>) -> (TaskStop, usize) {
let outcome = bounded_stop(task).await;
(outcome, Arc::strong_count(held))
}
#[tokio::test]
async fn stop_returns_only_after_the_task_dropped_what_it_held() {
let held = Arc::new(());
let task = parked_holding(&held);
assert_eq!(
Arc::strong_count(&held),
2,
"precondition: the task holds a ref"
);
assert_eq!(task.stop().await, TaskStop::Cancelled);
assert_eq!(
Arc::strong_count(&held),
1,
"stop returned while the aborted task still held its reference"
);
}
#[tokio::test]
async fn a_concurrent_second_stop_waits_for_the_first() {
let held = Arc::new(());
let task = parked_holding(&held);
let (a, b) = tokio::join!(stop_then_count(&task, &held), stop_then_count(&task, &held));
let mut outcomes = [a.0, b.0];
outcomes.sort_by_key(|o| *o == TaskStop::AlreadyStopped);
assert_eq!(
outcomes,
[TaskStop::Cancelled, TaskStop::AlreadyStopped],
"exactly one stop cancels; the other reports it already stopped"
);
assert_eq!(a.1, 1, "first stop returned before the task was gone");
assert_eq!(b.1, 1, "second stop returned before the task was gone");
}
#[tokio::test]
async fn a_task_that_returned_on_its_own_is_reported_returned() {
let (done_tx, done_rx) = tokio::sync::oneshot::channel::<()>();
let task = OwnedTask::spawn(async move {
let _ = done_tx.send(());
});
let _ = done_rx.await;
assert_eq!(task.stop().await, TaskStop::Returned);
assert_eq!(task.stop().await, TaskStop::AlreadyStopped);
}
#[tokio::test]
async fn a_task_that_panicked_is_reported_panicked_not_cancelled() {
let (started_tx, started_rx) = tokio::sync::oneshot::channel::<()>();
let task = OwnedTask::spawn(async move {
let _ = started_tx.send(());
panic!("owned-task test: deliberate panic");
});
let _ = started_rx.await;
assert_eq!(task.stop().await, TaskStop::Panicked);
}
#[tokio::test]
async fn stop_ends_a_running_blocking_closure_and_waits_for_its_return() {
let held = Arc::new(());
let task = blocking_holding(&held);
assert_eq!(bounded_stop(&task).await, TaskStop::Cancelled);
assert_eq!(
Arc::strong_count(&held),
1,
"stop returned while the blocking closure still held its reference"
);
assert_eq!(task.stop().await, TaskStop::AlreadyStopped);
}
#[tokio::test]
async fn a_blocking_closure_that_returned_on_its_own_is_reported_returned() {
let (done_tx, done_rx) = std::sync::mpsc::channel::<()>();
let task = OwnedTask::spawn_blocking(move |_stop| {
let _ = done_tx.send(());
});
let _ = done_rx.recv_timeout(STOP_BOUND);
assert_eq!(bounded_stop(&task).await, TaskStop::Returned);
}
#[tokio::test]
async fn a_blocking_closure_that_panicked_is_reported_panicked() {
let (started_tx, started_rx) = std::sync::mpsc::channel::<()>();
let task = OwnedTask::spawn_blocking(move |_stop| {
let _ = started_tx.send(());
panic!("owned-task test: deliberate blocking panic");
});
assert!(started_rx.recv_timeout(STOP_BOUND).is_ok());
assert_eq!(bounded_stop(&task).await, TaskStop::Panicked);
}
#[tokio::test]
async fn dropping_a_blocking_task_asks_its_closure_to_stop() {
let (started_tx, started_rx) = std::sync::mpsc::channel::<()>();
let (ended_tx, ended_rx) = std::sync::mpsc::channel::<()>();
let task = OwnedTask::spawn_blocking(move |stop| {
let _ = started_tx.send(());
park_until_stopped(&stop);
let _ = ended_tx.send(());
});
assert!(
started_rx.recv_timeout(STOP_BOUND).is_ok(),
"precondition: the closure started"
);
drop(task);
assert!(
ended_rx.recv_timeout(STOP_BOUND).is_ok(),
"a dropped blocking task's closure was never asked to stop"
);
}
}