#async-task #async #panic #fail-fast

pandet

A lightweight library to help act on panics of detached async tasks

3 releases (breaking)

0.4.0 Mar 22, 2023
0.3.0 Aug 27, 2022
0.2.2 May 27, 2022
0.1.2 Apr 30, 2022

#35 in #panic

Download history 10/week @ 2024-02-19 20/week @ 2024-02-26 82/week @ 2024-04-01

82 downloads per month
Used in rework

MIT license

18KB
382 lines

pandet

version documentation

A lightweight library that helps you detect failure of spawned async tasks without having to .await their handles. Useful when you are spawning lots of detached tasks but want to fast-fail if a panic occurs.

use pandet::*;

let detector = PanicDetector::new();

// Whichever async task spawner
task::spawn(
    async move {
        panic!();
    }
    .alert(&detector) // 👈 Binds the detector so it is notified of any panic from the future
);

assert!(detector.await.is_some());

!Send tasks implement the LocalAlert trait:

use pandet::*;

let detector = PanicDetector::new();

task::spawn_local(
    async move {
        // Does some work without panicking...
    }
    .local_alert(&detector)
);

assert!(detector.await.is_none());

Refined control over how to handle panics can also be implemented with PanicMonitor which works like a stream of alerts. You may also pass some message to the detector/monitor when a panic occurs:

use futures::StreamExt;
use pandet::*;

// Any Unpin + Send + 'static type works
struct FailureMsg {
    task_id: usize,
}

let mut monitor = PanicMonitor::<FailureMsg>::new(); // Or simply PanicMonitor::new()
for task_id in 0..=10 {
    task::spawn(
        async move {
            if task_id % 3 == 0 {
                panic!();
            }
        }
        // Notifies the monitor of the panicked task's ID
        .alert_msg(&monitor, FailureMsg { task_id })
    );
}

let cnt = 0;
while let Some(Panicked(msg)) = monitor.next().await {
    cnt += 1;
    assert_eq!(msg.task_id % 3, 0);
}
assert_eq!(cnt, 4);

Dependencies

~1MB
~16K SLoC