1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
//! 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.
//!
//! ```rust
//! # use tokio as task;
//! # #[task::main]
//! # async fn main() {
//! 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()); // See notes below
//! # }
//! ```
//!
//! `!Send` tasks implement the [`LocalAlert`] trait:
//! ```rust
//! # use tokio::{runtime, task};
//! # fn main() {
//! use pandet::*;
//!
//! let detector = PanicDetector::new();
//!
//! # let local = task::LocalSet::new();
//! # let rt = runtime::Runtime::new().unwrap();
//! # local.block_on(&rt, async {
//! 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 information to the alert/monitor
//! when a panic occurs:
//! ```rust
//! # use tokio as task;
//! # #[task::main]
//! # async fn main() {
//! 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 })
//!     );
//! }
//!
//! while let Some(Panicked(msg)) = monitor.next().await {
//!     assert_eq!(msg.task_id % 3, 0);
//! }
//! # }
//! ```

use std::{
    future::Future,
    pin::Pin,
    task::{Context, Poll},
};

use futures::stream::FuturesUnordered;
use futures::{
    channel::{
        mpsc::{unbounded, UnboundedReceiver, UnboundedSender},
        oneshot,
    },
    FutureExt, Stream,
};

/// Created by the panic detector when a panic occurs.
///
/// Its first and only field is the additional information emitted when the corresponding task panics.
/// The field defaults to `()`.
pub struct Panicked<Msg = ()>(pub Msg)
where
    Msg: Send + 'static;

/// Notifies [`PanicDetector`]/[`PanicMonitor`] of panics.
///
/// Can be bounded to [`Alert`] and [`LocalAlert`] types.
pub struct DetectorHook<Msg = ()>(UnboundedSender<RxHandle<Msg>>)
where
    Msg: Send + 'static;

impl<Msg> Clone for DetectorHook<Msg>
where
    Msg: Send + 'static,
{
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

/// Used to bind a [`PanicDetector`] onto any task. Implemented for all `Future` types.
pub trait LocalAlert<'a, T> {
    /// Consumes a task, and returns a new task with the `PanicDetector` bound to it.
    fn local_alert<A>(self, hook: &'_ A) -> LocalPanicAwareFuture<'a, T>
    where
        A: AsRef<DetectorHook>;

    /// Binds a `PanicDetector` and emits additional information when the panic is detected.
    fn local_alert_msg<Msg, A>(self, hook: &'_ A, msg: Msg) -> LocalPanicAwareFuture<'a, T>
    where
        Msg: Send + 'static,
        A: AsRef<DetectorHook<Msg>>;
}

impl<'a, F> LocalAlert<'a, F::Output> for F
where
    F: Future + 'a,
{
    fn local_alert<A>(self, hook: &'_ A) -> LocalPanicAwareFuture<'a, F::Output>
    where
        A: AsRef<DetectorHook>,
    {
        self.local_alert_msg(hook, ())
    }

    fn local_alert_msg<Msg, A>(self, hook: &'_ A, msg: Msg) -> LocalPanicAwareFuture<'a, F::Output>
    where
        Msg: Send + 'static,
        A: AsRef<DetectorHook<Msg>>,
    {
        let (tx, rx) = oneshot::channel();
        hook.as_ref()
            .0
            .unbounded_send(RxHandle {
                signaler: rx,
                msg: Some(msg),
            })
            .expect("detector dropped early");
        LocalPanicAwareFuture::new(async move {
            let ret = self.await;
            let _ = tx.send(());
            ret
        })
    }
}

#[doc(hidden)]
pub struct LocalPanicAwareFuture<'a, T> {
    inner: Pin<Box<dyn Future<Output = T> + 'a>>,
}

impl<'a, T> LocalPanicAwareFuture<'a, T> {
    fn new<Fut>(fut: Fut) -> Self
    where
        Fut: Future<Output = T> + 'a,
    {
        LocalPanicAwareFuture {
            inner: Box::pin(fut),
        }
    }
}

impl<T> Future for LocalPanicAwareFuture<'_, T> {
    type Output = T;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        self.inner.poll_unpin(cx)
    }
}

/// Used to bind a [`PanicDetector`] onto a `Send` task. Implemented for all types that are
/// `Future + Send`.
pub trait Alert<'a, T> {
    /// Consumes a task, and returns a new task with the `PanicDetector` bound to it.
    fn alert<A>(self, hook: &'_ A) -> PanicAwareFuture<'a, T>
    where
        A: AsRef<DetectorHook>;

    /// Binds a `PanicDetector` and emits additional information when the panic is detected.
    fn alert_msg<Msg, A>(self, hook: &'_ A, msg: Msg) -> PanicAwareFuture<'a, T>
    where
        Msg: Send + 'static,
        A: AsRef<DetectorHook<Msg>>;
}

impl<'a, F> Alert<'a, F::Output> for F
where
    F: Future + Send + 'a,
{
    fn alert<A>(self, hook: &'_ A) -> PanicAwareFuture<'a, F::Output>
    where
        A: AsRef<DetectorHook>,
    {
        self.alert_msg(hook, ())
    }

    fn alert_msg<Msg, A>(self, hook: &'_ A, msg: Msg) -> PanicAwareFuture<'a, F::Output>
    where
        Msg: Send + 'static,
        A: AsRef<DetectorHook<Msg>>,
    {
        let (tx, rx) = oneshot::channel();
        hook.as_ref()
            .0
            .unbounded_send(RxHandle {
                signaler: rx,
                msg: Some(msg),
            })
            .expect("detector dropped early");
        PanicAwareFuture::new(async move {
            let ret = self.await;
            let _ = tx.send(());
            ret
        })
    }
}

#[doc(hidden)]
pub struct PanicAwareFuture<'a, T> {
    inner: Pin<Box<dyn Future<Output = T> + Send + 'a>>,
}

impl<'a, T> PanicAwareFuture<'a, T> {
    fn new<Fut>(fut: Fut) -> Self
    where
        Fut: Future<Output = T> + Send + 'a,
    {
        PanicAwareFuture {
            inner: Box::pin(fut),
        }
    }
}

impl<T> Future for PanicAwareFuture<'_, T> {
    type Output = T;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        self.inner.poll_unpin(cx)
    }
}

struct RxHandle<Msg>
where
    Msg: Send + 'static,
{
    signaler: oneshot::Receiver<()>,
    msg: Option<Msg>,
}

impl<Msg> Future for RxHandle<Msg>
where
    Msg: Unpin + Send + 'static,
{
    type Output = Option<Panicked<Msg>>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let res = self.signaler.poll_unpin(cx);
        res.map(|r| {
            if r.is_err() {
                Some(Panicked(self.msg.take().expect("message already read")))
            } else {
                None
            }
        })
    }
}

/// A future that finishes with an `Some(Panicked<Msg>)` when a task has panicked or `None` if no task panicked.
pub struct PanicDetector<Msg = ()>
where
    Msg: Send + 'static,
{
    detector: Option<DetectorHook<Msg>>,
    rx: UnboundedReceiver<RxHandle<Msg>>,
    hooks: FuturesUnordered<RxHandle<Msg>>,
    rx_closed: bool,
}

impl<Msg> PanicDetector<Msg>
where
    Msg: Send + 'static,
{
    /// Creates a new `PanicMonitor`.
    pub fn new() -> Self {
        let (tx, rx) = unbounded();
        PanicDetector {
            detector: Some(DetectorHook(tx)),
            rx,
            hooks: FuturesUnordered::new(),
            rx_closed: false,
        }
    }
}

impl<Msg> AsRef<DetectorHook<Msg>> for PanicDetector<Msg>
where
    Msg: Unpin + Send + 'static,
{
    fn as_ref(&self) -> &DetectorHook<Msg> {
        match self.detector {
            Some(ref det) => det,
            None => panic!(
                "This detector has been polled. Create a new detector to receive new panic alerts."
            ),
        }
    }
}

impl<Msg> Future for PanicDetector<Msg>
where
    Msg: Unpin + Send + 'static,
{
    type Output = Option<Panicked<Msg>>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        self.detector = None;
        while !self.rx_closed {
            match Pin::new(&mut self.rx).poll_next(cx) {
                Poll::Pending => break,
                Poll::Ready(Some(r)) => self.hooks.push(r),
                Poll::Ready(None) => {
                    self.rx_closed = true;
                    break;
                }
            }
        }

        loop {
            let res = Pin::new(&mut self.hooks).poll_next(cx);
            match res {
                Poll::Ready(Some(r)) => {
                    if r.is_some() {
                        break Poll::Ready(r);
                    }
                }
                Poll::Ready(None) => {
                    if self.rx_closed {
                        break Poll::Ready(None);
                    } else {
                        break Poll::Pending;
                    }
                }
                Poll::Pending => {
                    break Poll::Pending;
                }
            }
        }
    }
}

/// A [`Stream`](https://docs.rs/futures/latest/futures/stream/trait.Stream.html#) of detected panics.
///
/// It finishes when all the futures that it's detecting for have finished.
pub struct PanicMonitor<Msg = ()>
where
    Msg: Send + 'static,
{
    detector: Option<DetectorHook<Msg>>,
    rx: UnboundedReceiver<RxHandle<Msg>>,
    hooks: FuturesUnordered<RxHandle<Msg>>,
    rx_closed: bool,
}

impl<Msg> PanicMonitor<Msg>
where
    Msg: Send + 'static,
{
    /// Creates a new `PanicMonitor`.
    pub fn new() -> Self {
        let (tx, rx) = unbounded();
        PanicMonitor {
            detector: Some(DetectorHook(tx)),
            rx,
            hooks: FuturesUnordered::new(),
            rx_closed: false,
        }
    }
}

impl<Msg> AsRef<DetectorHook<Msg>> for PanicMonitor<Msg>
where
    Msg: Unpin + Send + 'static,
{
    fn as_ref(&self) -> &DetectorHook<Msg> {
        match self.detector {
            Some(ref det) => det,
            None => panic!(
                "This monitor has been polled. Create a new monitor to receive new panic alerts."
            ),
        }
    }
}

impl<Msg> Stream for PanicMonitor<Msg>
where
    Msg: Unpin + Send + 'static,
{
    type Item = Panicked<Msg>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        self.detector = None;
        while !self.rx_closed {
            match Pin::new(&mut self.rx).poll_next(cx) {
                Poll::Pending => break,
                Poll::Ready(Some(r)) => self.hooks.push(r),
                Poll::Ready(None) => {
                    self.rx_closed = true;
                    break;
                }
            }
        }

        loop {
            let res = Pin::new(&mut self.hooks).poll_next(cx);
            match res {
                Poll::Ready(Some(r)) => {
                    if r.is_some() {
                        break Poll::Ready(r);
                    }
                }
                Poll::Ready(None) => {
                    if self.rx_closed {
                        break Poll::Ready(None);
                    } else {
                        break Poll::Pending;
                    }
                }
                Poll::Pending => {
                    break Poll::Pending;
                }
            }
        }
    }
}

impl<Msg: Unpin + Send + 'static> Unpin for PanicMonitor<Msg> {}

#[cfg(test)]
mod tests {
    use futures::StreamExt;

    use super::*;

    #[tokio::test]
    async fn alert_works() {
        let detector = PanicDetector::new();

        for i in 0..=10 {
            tokio::spawn(
                async move {
                    if i == 1 {
                        panic!("What could go wrong");
                    }
                }
                .alert(&detector),
            );
        }
        assert!(detector.await.is_some());

        let detector = PanicDetector::new();
        (0..=10).for_each(|_| {
            tokio::spawn((|| async move {}.alert(&detector))());
        });
        assert!(detector.await.is_none());
    }

    #[tokio::test]
    async fn unsend_works() {
        let detector = PanicDetector::new();

        let local = tokio::task::LocalSet::new();
        local
            .run_until(async move {
                {
                    let _ = tokio::task::spawn_local(
                        async move {
                            // panic!();
                        }
                        .local_alert(&detector),
                    );
                }
                assert!(detector.await.is_none());
            })
            .await;
    }

    #[tokio::test]
    async fn monitor_works() {
        let mut monitor = PanicMonitor::new();

        for i in 0..=10 {
            tokio::spawn(
                async move {
                    if i % 3 == 0 {
                        panic!();
                    }
                }
                .alert_msg(&monitor, i),
            );
        }

        let mut count = 0;
        while let Some(res) = monitor.next().await {
            let id = res.0;
            assert_eq!(id % 3, 0);
            count += 1;
        }
        assert_eq!(count, 4);
    }
}