drop-handle 1.0.1

A handle that will abort a Tokio task when dropped.
Documentation
use crate::DropHandle;
use std::{
    sync::{Arc, Barrier, Once},
    time::Duration,
};
use tracing::Level;

fn init_tracing() {
    static INIT: Once = Once::new();

    INIT.call_once(|| {
        let subscriber = tracing_subscriber::fmt()
            .with_max_level(Level::TRACE)
            .with_line_number(true)
            .with_test_writer()
            .finish();
        tracing::subscriber::set_global_default(subscriber)
            .expect("global tracing subscriber should only be initialized once");
    });
}

async fn wait_for_arc_count<T: Send + Sync>(arc: &Arc<T>, expected: usize) {
    tokio::time::timeout(Duration::from_secs(2), async {
        while Arc::strong_count(arc) != expected {
            tokio::task::yield_now().await;
        }
    })
    .await
    .unwrap_or_else(|_| {
        panic!(
            "timed out waiting for Arc strong_count: got {}, expected {expected}",
            Arc::strong_count(arc)
        )
    });
}

#[tokio::test]
async fn test_drop_handle() {
    init_tracing();

    // Create an `Arc` to track the number of references to the task
    let arc_counter = Arc::new(String::from("counter"));
    assert_eq!(Arc::strong_count(&arc_counter), 1);

    let arc_counter_clone = arc_counter.clone();
    let drop_handle: DropHandle = tokio::spawn(async move {
        loop {
            // Just use the counter to ensure the task stays alive and isn't optimized away by the compiler
            tokio::time::sleep(Duration::from_millis(
                Arc::strong_count(&arc_counter_clone) as u64 * 100,
            ))
            .await;
        }
    })
    .into();

    assert!(!drop_handle.is_finished());
    assert_eq!(Arc::strong_count(&arc_counter), 2);

    // Drop the handle, but clone it first
    drop(drop_handle.clone());
    tokio::time::sleep(Duration::from_millis(200)).await;

    // Should not be `finished` because there are still references to this `drop_handle` since we cloned it
    assert!(!drop_handle.is_finished());
    // ... so there should still be 2 counters left
    assert_eq!(Arc::strong_count(&arc_counter), 2);

    // Now drop the last handle tracked by the `Arc`; the task should then be aborted.
    drop(drop_handle);
    wait_for_arc_count(&arc_counter, 1).await;

    // ... so there should be only 1 counter left (this one). This attests that the task was successfully terminated.
    assert_eq!(Arc::strong_count(&arc_counter), 1);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_concurrent_drop_handle_drops() {
    // Each clone will be dropped by a different OS thread.
    const THREAD_COUNT: usize = 64;

    init_tracing();

    // This Arc acts as a witness: the task holds it until it is aborted.
    let counter = Arc::new(());
    let task_counter = counter.clone();
    let drop_handle: DropHandle = tokio::spawn(async move {
        loop {
            let _ = &task_counter;
            tokio::time::sleep(Duration::from_secs(1)).await;
        }
    })
    .into();
    assert_eq!(Arc::strong_count(&counter), 2);

    // Move the clones to separate threads; keep the original handle in the test thread.
    let clones: Vec<_> = (0..THREAD_COUNT).map(|_| drop_handle.clone()).collect();
    // Prevent any thread from dropping its handle until all threads are ready.
    let barrier = Barrier::new(THREAD_COUNT + 1);

    std::thread::scope(|scope| {
        for handle in clones {
            scope.spawn(|| {
                barrier.wait();
                drop(handle);
            });
        }

        // Release all 16 threads at once and drop the original handle as well.
        barrier.wait();
        drop(drop_handle);
    });

    // All handles have been dropped when the scope exits. Give Tokio time to process
    // the cancellation, then verify that the task released its Arc.
    wait_for_arc_count(&counter, 1).await;
}